diff --git a/ASSETS.md b/ASSETS.md index dbdd8b84d8..2c7a07478b 100644 --- a/ASSETS.md +++ b/ASSETS.md @@ -129,6 +129,7 @@ Generated-in-code art is original and has no file to list. This covers the defau | `assets/icons/dc-cap-square.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-center-hide.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-center-show.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-circle-points.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a circle with three dots on its edge) | MIT OR Apache-2.0 | | | `assets/icons/dc-clear.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-color-guide.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-contour.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a solid rounded square inside four corner arcs, its offset outline); not derived from any other application's icon | MIT OR Apache-2.0 | | diff --git a/ROADMAP.md b/ROADMAP.md index b2ebdb0545..b3877be5c8 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -141,6 +141,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-16: Fold Preview in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and the Fold Lines panel's Fold Preview button): a window that folds the document's blank into its 3D shape about its largest panel, or the panel double-clicked, with the printed art on the outside of each panel (fold lines and non-printing layers left out, unless Show Fold Lines is on) and the board's inside color on the back. Creases and perforations fold 90° away from the print and partial cuts 90° toward it; a Fold slider goes from flat to folded, and the view turns by dragging and the arrow keys, zooms, moves and takes a perspective and seven view presets. The status line says when a joint does not close or two panels pass through each other (`addon.packaging.fold`, `ui.foldPreview`). A VectorCraft addition: headline numbers unchanged. - 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged. - 2026-11-15: Circle through three points: three Shift-clicks with the Ellipse tool, or `shape.circleThroughPoints` with three points or three selected anchor points, draw the circle whose edge passes through them, with the current paint, in one undo step; after two points the tool previews the circle through the pointer, and two points that are the same or three on one line are refused with a message. Scores and estimates unchanged. +- 2026-11-17: Circle tool (after the Ellipse tool in its group): two clicks or a drag draw the circle on that diameter, and a click followed by a drag from a second point to a third draws the circle through the three; Shift keeps the diameter at 45° steps, Alt rounds a two-point circle's diameter to the rulers' ticks at the current zoom, points snap to Smart Guides, and the tool shows the circle, its center, its radii and its diameter until the release, or "Circle too large" for points on one line or a circle past the canvas. `shape.circleThroughPoints` also takes two points or two selected anchor points as the ends of a diameter. One undo step per circle. A VectorCraft addition: headline numbers unchanged. - 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`). - 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged. - 2026-11-11: Pattern libraries: Patterns › Optical Effects, a third built-in pattern library, of VectorCraft's own designs, holds eight black wave, moiré and op-art tiles (Sine Bands, Ripple Lines, Interference Rings, Offset Rings, Warped Checks, Pinched Stripes, Chevron Pulse and Radiating Lenses) of 32 to 48 pt, each drawn the same way every time; each tile is one period of its design, and art that reaches past a tile edge continues on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged. @@ -154,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/assets/icons/dc-circle-points.svg b/assets/icons/dc-circle-points.svg new file mode 100644 index 0000000000..46da3a3401 --- /dev/null +++ b/assets/icons/dc-circle-points.svg @@ -0,0 +1 @@ + diff --git a/crates/brush/src/calli.rs b/crates/brush/src/calli.rs index 888294356c..69a8463c92 100644 --- a/crates/brush/src/calli.rs +++ b/crates/brush/src/calli.rs @@ -9,7 +9,6 @@ //! the stroke with what the pen recorded on it (`StrokeLayer::pressure`, `tilt`, `bearing` and //! `rotation`): the sweep is sampled densely and each sample takes the nib for the pen there. -use vectorcraft_color::Paint; use vectorcraft_doc::{Node, StrokeLayer}; use vectorcraft_geom::{BezPath, PathData, Point, SubPath, Vec2}; @@ -198,7 +197,70 @@ fn offset_track(t: &Track, d: f64, trim0: f64, trim1: f64) -> Option { Some(bp) } -pub(crate) fn bristle(b: &Bristle, bp: &BezPath, weight: f64, paint: &Paint, name: &str) -> Vec { +/// A strand that follows the recorded pen pose. Pressure and tilt change its spread; bearing and +/// barrel rotation turn that spread in the path's local frame. Original path corners are included +/// in the samples so a turn is not rounded away by the pose sampling interval. +fn posed_bristle_track( + t: &Track, + d: f64, + trim0: f64, + trim1: f64, + size: f64, + stroke: &StrokeLayer, + varies: bool, +) -> Option<(BezPath, Vec<(f64, f64)>)> { + let l = t.len(); + let (s0, s1) = (trim0.clamp(0.0, l), (l - trim1).clamp(0.0, l)); + if s1 - s0 < 1e-6 { + return None; + } + let steps = if varies { ((s1 - s0) / (size * 0.2).max(0.25)).ceil().clamp(1.0, MAX_STEPS) as usize } else { 1 }; + let mut positions: Vec = (0..=steps).map(|i| s0 + (s1 - s0) * i as f64 / steps as f64).collect(); + positions.extend(t.cum.iter().copied().filter(|&s| s > s0 && s < s1)); + positions.sort_by(f64::total_cmp); + positions.dedup_by(|a, b| (*a - *b).abs() < 1e-6); + let mut path = BezPath::new(); + // Distance along the posed strand -> fraction along the original, untrimmed path. + let mut source = Vec::with_capacity(positions.len()); + let mut previous: Option = None; + let mut distance = 0.0; + for (i, s) in positions.into_iter().enumerate() { + let pen = PenAt::of(stroke, s / l); + let pressure = pen.control(Variation::Pressure).unwrap_or(0.5); + let tilt = pen.control(Variation::Tilt).unwrap_or(0.5); + let bearing = pen.control(Variation::Bearing).unwrap_or(0.5); + let rotation = pen.control(Variation::Rotation).unwrap_or(0.5); + let spread = d * (0.5 + pressure) * (1.25 - 0.5 * tilt); + let angle = std::f64::consts::TAU * (bearing + rotation - 1.0); + let p = t.map(s + spread * angle.sin(), spread * angle.cos()); + if i == 0 { + path.move_to(p) + } else { + path.line_to(p) + } + if let Some(previous) = previous { + distance += previous.distance(p); + } + source.push((distance, s / l)); + previous = Some(p); + } + Some((path, source)) +} + +fn source_fraction(source: &[(f64, f64)], distance: f64) -> f64 { + let next = source.partition_point(|(d, _)| *d < distance); + if next == 0 { + return source.first().map_or(0.0, |(_, f)| *f); + } + if next >= source.len() { + return source.last().map_or(1.0, |(_, f)| *f); + } + let (d0, f0) = source[next - 1]; + let (d1, f1) = source[next]; + if d1 - d0 < 1e-9 { f1 } else { f0 + (f1 - f0) * ((distance - d0) / (d1 - d0)) } +} + +pub(crate) fn bristle(b: &Bristle, bp: &BezPath, weight: f64, stroke: &StrokeLayer, name: &str) -> Vec { let mut rng = Rng::new(seed_of(bp, name)); let size = b.size.max(0.1) * weight; let strands = (3.0 + b.density.clamp(1.0, 100.0) / 100.0 * 13.0).round() as usize; @@ -210,6 +272,13 @@ pub(crate) fn bristle(b: &Bristle, bp: &BezPath, weight: f64, paint: &Paint, nam let wobble = (100.0 - b.stiffness.clamp(1.0, 100.0)) / 100.0; let ragged = b.length.clamp(25.0, 300.0) / 100.0; let opacity = (b.opacity.clamp(1.0, 100.0) / 100.0) as f32; + let posed = stroke.pressure.is_some() || stroke.tilt.is_some() || stroke.bearing.is_some() || stroke.rotation.is_some(); + let varies = |points: &[(f64, f64)]| points.first().is_some_and(|(_, first)| points.iter().any(|(_, value)| (value - first).abs() > 1e-6)); + let pressure_varies = stroke.pressure.as_ref().is_some_and(|p| varies(&p.points)); + let pose_varies = pressure_varies + || stroke.tilt.as_ref().is_some_and(|p| varies(&p.points)) + || stroke.bearing.as_ref().is_some_and(|p| varies(&p.points)) + || stroke.rotation.as_ref().is_some_and(|p| varies(&p.points)); let mut out = vec![]; for t in tracks(bp, tolerance(size)) { let l = t.len(); @@ -220,14 +289,37 @@ pub(crate) fn bristle(b: &Bristle, bp: &BezPath, weight: f64, paint: &Paint, nam let edge = 1.0 - lane.abs(); let trim = |r: &mut Rng| r.unit() * ragged * size * (1.2 - edge) * 0.8; let (t0, t1) = (trim(&mut rng), trim(&mut rng)); - let Some(sp) = offset_track(&t, off, t0.min(l * 0.3), t1.min(l * 0.3)) else { continue }; + let (t0, t1) = (t0.min(l * 0.3), t1.min(l * 0.3)); + let sp = if posed { + posed_bristle_track(&t, off, t0, t1, size, stroke, pose_varies) + } else { + offset_track(&t, off, t0, t1).map(|path| (path, Vec::new())) + }; + let Some((sp, source)) = sp else { continue }; let w = thick * (0.6 + 0.4 * edge) * rng.range(0.8, 1.2); - let nib = Nib::new(0.0, 1.0, w); - let subs: Vec = tracks(&sp, tolerance(w)).iter().flat_map(|tt| sweep(tt, &|_| nib, None)).collect(); + let subs: Vec = tracks(&sp, tolerance(w)) + .iter() + .flat_map(|tt| { + if posed { + sweep( + tt, + &|f| { + let original_fraction = source_fraction(&source, f * tt.len()); + let pressure = PenAt::of(stroke, original_fraction).control(Variation::Pressure).unwrap_or(0.5); + Nib::new(0.0, 1.0, w * (0.5 + pressure)) + }, + pressure_varies.then_some((tt.len() / MAX_STEPS).max(0.25)), + ) + } else { + let nib = Nib::new(0.0, 1.0, w); + sweep(tt, &|_| nib, None) + } + }) + .collect(); if subs.is_empty() { continue; } - let mut n = filled(PathData::new(subs), paint); + let mut n = filled(PathData::new(subs), &stroke.paint); n.opacity = (opacity * rng.range(0.7, 1.0) as f32).clamp(0.0, 1.0); out.push(n); } 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 7129279b31..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) => { @@ -1084,7 +1098,7 @@ pub fn stroke_pieces(doc: &Document, brush: &Brush, bp: &BezPath, stroke: &Strok let w = if stroke.width > 0.0 { stroke.width } else { 1.0 }; let mut out = match &brush.kind { BrushKind::Calligraphic(c) => calli::calligraphic(c, bp, w, stroke, &brush.name), - BrushKind::Bristle(b) => calli::bristle(b, bp, w, &stroke.paint, &brush.name), + BrushKind::Bristle(b) => calli::bristle(b, bp, w, stroke, &brush.name), BrushKind::Art(a) => warp::art(a, bp, w, stroke), BrushKind::Scatter(s) => warp::scatter(s, bp, w, stroke, &brush.name), BrushKind::Pattern(p) => warp::pattern(p, bp, w), @@ -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 } @@ -1245,6 +1265,14 @@ pub fn has_brush(n: &Node) -> bool { n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(s) if s.brush.is_some() && s.visible)) } +/// Does `stroke` draw with a brush of `lib` (the document's [`library`])? [`stroke_pieces`] sizes +/// brush art from the brush and the stroke weight and does not read the stroke's width profile, so +/// the profile does not change what such a stroke draws. A stroke without a brush, or one that +/// names a brush `lib` lacks, draws a plain stroke, which follows the profile. +pub fn keeps_brush_size(lib: &[Brush], stroke: &StrokeLayer) -> bool { + stroke.brush.as_deref().is_some_and(|name| lib.iter().any(|b| b.name == name)) +} + /// How far brush art can paint past the visual box of `n`: `16 × w + 8`, where `w` is the widest /// stroke of `n` (at least 1), when `n` has a visible brushed stroke with a paint; 0 when it has /// none, as a brushed stroke without a paint draws no brush art. This is the room the renderer and diff --git a/crates/brush/src/tests.rs b/crates/brush/src/tests.rs index 437ec4028f..f4f2d1ae20 100644 --- a/crates/brush/src/tests.rs +++ b/crates/brush/src/tests.rs @@ -827,6 +827,86 @@ fn bristle_makes_translucent_strands() { assert!(bb.height() <= 6.0 * 1.3 && bb.height() >= 3.0, "{bb:?}"); } +#[test] +fn bristle_pen_pressure_changes_its_footprint() { + let b = Brush { name: "b".into(), kind: BrushKind::Bristle(Bristle::default()) }; + let render = |pressure| { + let s = StrokeLayer { pressure: Some(vectorcraft_doc::PressureProfile { points: vec![(0.0, pressure), (1.0, pressure)] }), ..stroke(1.0) }; + stroke_pieces(&Document::new(1.0, 1.0), &b, &line(0.0, 0.0, 200.0, 0.0), &s) + }; + let light = render(0.0); + let heavy = render(1.0); + assert_eq!(light.len(), heavy.len()); + assert!(bounds(&heavy).height() > bounds(&light).height() * 1.8); +} + +#[test] +fn bristle_pen_pressure_is_sampled_along_the_stroke() { + let b = Brush { name: "b".into(), kind: BrushKind::Bristle(Bristle::default()) }; + let s = StrokeLayer { pressure: Some(vectorcraft_doc::PressureProfile { points: vec![(0.0, 0.0), (1.0, 1.0)] }), ..stroke(1.0) }; + let out = stroke_pieces(&Document::new(1.0, 1.0), &b, &line(0.0, 0.0, 200.0, 0.0), &s); + let mut points = Vec::new(); + for n in &out { + all_points(n, &mut points); + } + let early = points.iter().filter(|p| p.x > 20.0 && p.x < 60.0).map(|p| p.y.abs()).fold(0.0_f64, f64::max); + let late = points.iter().filter(|p| p.x > 140.0 && p.x < 180.0).map(|p| p.y.abs()).fold(0.0_f64, f64::max); + assert!(late > early * 1.4, "spread along stroke: {early} -> {late}"); +} + +#[test] +fn trimmed_bristle_strands_read_pressure_where_they_begin() { + let b = Brush { name: "b".into(), kind: BrushKind::Bristle(Bristle { size: 20.0, length: 300.0, ..Default::default() }) }; + let render = |points| { + let s = StrokeLayer { pressure: Some(vectorcraft_doc::PressureProfile { points }), ..stroke(1.0) }; + stroke_pieces(&Document::new(1.0, 1.0), &b, &line(0.0, 0.0, 80.0, 0.0), &s) + }; + let ramp = render(vec![(0.0, 0.0), (1.0, 1.0)]); + let neutral = render(vec![(0.0, 0.5), (1.0, 0.5)]); + assert_eq!(ramp.len(), neutral.len()); + let start = |n: &Node| { + let anchors = &n.path_data().unwrap().subpaths[0].anchors; + let first = anchors[0].p; + let opposite = anchors[anchors.len() - 16].p; + (first.x, (first.y - opposite.y).abs()) + }; + let mut checked = false; + for (ramp, neutral) in ramp.iter().zip(&neutral) { + let (x, width) = start(ramp); + if x < 12.0 { + continue; + } + let (_, neutral_width) = start(neutral); + let expected = 0.5 + x / 80.0; + assert!(width / neutral_width > expected - 0.08, "strand at {x}: {width} vs {neutral_width}, expected ratio {expected}"); + checked = true; + } + assert!(checked, "at least one strand begins past the pressure ramp's first eighth"); +} + +#[test] +fn bristle_pen_orientation_changes_its_footprint() { + let b = Brush { name: "b".into(), kind: BrushKind::Bristle(Bristle::default()) }; + let render = |tilt, bearing, rotation| { + let flat = |x| vec![(0.0, x), (1.0, x)]; + let s = StrokeLayer { + tilt: Some(vectorcraft_doc::PressureProfile { points: flat(tilt) }), + bearing: Some(vectorcraft_doc::AngleProfile { points: flat(bearing) }), + rotation: Some(vectorcraft_doc::AngleProfile { points: flat(rotation) }), + ..stroke(1.0) + }; + stroke_pieces(&Document::new(1.0, 1.0), &b, &line(0.0, 0.0, 200.0, 0.0), &s) + }; + let neutral = bounds(&render(0.5, 0.0, 0.0)).height(); + let flat = bounds(&render(1.0, 0.0, 0.0)).height(); + let upright = bounds(&render(0.0, 0.0, 0.0)).height(); + let bearing = bounds(&render(0.5, 90.0, 0.0)).height(); + let rotation = bounds(&render(0.5, 0.0, 90.0)).height(); + assert!(flat > neutral && neutral > upright, "tilt: {flat} > {neutral} > {upright}"); + assert!(bearing < neutral * 0.7, "bearing: {bearing} vs {neutral}"); + assert!(rotation < neutral * 0.7, "rotation: {rotation} vs {neutral}"); +} + #[test] fn tints_colorization_uses_stroke_colour() { let b = art_brush(rect_art(10.0, 4.0), ArtScale::Stretch); @@ -953,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/cad/src/lib.rs b/crates/cad/src/lib.rs index eafb4616f1..8aefe61a0d 100644 --- a/crates/cad/src/lib.rs +++ b/crates/cad/src/lib.rs @@ -7,6 +7,8 @@ //! hatches, type text entities or glyph outlines, and placed images image entities linked to PNG //! or JPEG files the caller writes next to the drawing. Coordinates are y-up, in drawing units: `scale` units per //! `unit` of the art, with the origin at the bottom-left corner of [`DxfOptions::region`]. +//! [`export_drawings`] writes one such drawing for each of several regions, applying the live +//! effects once for all of them. //! //! What DXF can't hold (blending modes, opacity masks, raster effects, gradients, patterns, //! clipping) is approximated or left out, and each such loss comes back as a warning. @@ -436,18 +438,43 @@ pub const SCALE_RANGE: std::ops::RangeInclusive = 1e-6..=1e6; /// Write `doc` as a DXF drawing with `opts`. Live geometry effects are applied first; template /// layers, guides and hidden objects are left out. pub fn export(doc: &Document, opts: &DxfOptions) -> Result { + Ok(export_drawings(doc, opts, &[(opts.region, opts.crop)])?.pop().unwrap_or_default()) +} + +/// Write `doc` as one DXF drawing for each `(region, crop)` of `drawings`, in order, each as +/// [`export`] writes it with `opts` and that region and crop. Live geometry effects are applied +/// once for all the drawings. +pub fn export_drawings(doc: &Document, opts: &DxfOptions, drawings: &[(Rect, bool)]) -> Result, String> { + export_drawings_with(doc, opts, drawings, bake_for_drawings) +} + +/// `doc` with its live geometry effects applied and its symbols' art placed, or `None` when +/// nothing changes. +fn bake_for_drawings(doc: &Document) -> Option { + // Symbols' art is placed without clipping, as the scene places it. + let layers = vectorcraft_effects::WrittenLayers { hidden: true, non_printing: true, hidden_objects: false }; + vectorcraft_effects::bake_document_placing_symbols(doc, false, layers) +} + +/// [`export_drawings`] with `bake` applying the live effects. +fn export_drawings_with( + doc: &Document, + opts: &DxfOptions, + drawings: &[(Rect, bool)], + bake: impl Fn(&Document) -> Option, +) -> Result, String> { if !(opts.scale.is_finite() && SCALE_RANGE.contains(&opts.scale)) { return Err(format!("scale must be a number from {} to {}, not {}", SCALE_RANGE.start(), SCALE_RANGE.end(), opts.scale)); } - let r = opts.region; - if ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) { + if drawings.iter().any(|(r, _)| ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite())) { return Err("the export region is not finite".into()); } - // Symbols' art is placed without clipping, as the scene places it. - let layers = vectorcraft_effects::WrittenLayers { hidden: true, non_printing: true, hidden_objects: false }; - let baked = vectorcraft_effects::bake_document_placing_symbols(doc, false, layers); + if drawings.is_empty() { + return Ok(vec![]); + } + let baked = bake(doc); let doc = baked.as_ref().unwrap_or(doc); - Ok(scene::Scene::new(doc, opts).run()) + Ok(drawings.iter().map(|&(region, crop)| scene::Scene::new(doc, &DxfOptions { region, crop, ..opts.clone() }).run()).collect()) } #[cfg(test)] diff --git a/crates/cad/src/tests.rs b/crates/cad/src/tests.rs index dda09a0696..797223b688 100644 --- a/crates/cad/src/tests.rs +++ b/crates/cad/src/tests.rs @@ -1493,3 +1493,201 @@ fn export_bytes_match_shared_writer_goldens() { assert_eq!(got, expected, "DXF bytes changed versus {}", path.display()); } } + +/// One drawing written by applying the live effects for it alone and walking the result, as each +/// drawing of a multi-drawing export was written before [`export_drawings`]. +fn export_baking_alone(doc: &Document, opts: &DxfOptions) -> DxfOutput { + let baked = crate::bake_for_drawings(doc); + crate::scene::Scene::new(baked.as_ref().unwrap_or(doc), opts).run() +} + +/// A written drawing's bytes, linked images (name and bytes), warnings and setting notes. +type Written = (Vec, Vec<(String, Vec)>, Vec, Vec); + +/// Every field of a written drawing, for comparing two. +fn written(out: &DxfOutput) -> Written { + let images = out.images.iter().map(|i| (i.name.clone(), i.bytes.clone())).collect(); + (out.bytes.clone(), images, out.warnings.clone(), out.setting_notes.clone()) +} + +/// A Transform effect that moves its object `x` pt right. +fn moved_by(mut n: Node, x: f64) -> Node { + n.appearance.effects.push(vectorcraft_doc::Effect { id: "distort.transform".into(), params: serde_json::json!({"moveH": x}), visible: true }); + n +} + +/// A line moved by a Transform effect, an instance of a symbol whose art carries the same effect +/// stained by its fill, a semi-transparent line in a blending mode, and a placed PNG image. +fn drawings_doc() -> Document { + let png = craft_image_codecs::encode( + &craft_image_codecs::Image::from_raw( + 2, + 2, + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + [0u8, 128, 255, 255].repeat(4), + ) + .unwrap(), + craft_image_codecs::Format::Png, + &craft_image_codecs::EncodeOptions::default(), + ) + .unwrap(); + let mut d = doc_with(|d| { + let line = path(d, shapes::line((10.0, 10.0).into(), (20.0, 10.0).into()), Paint::None, Paint::solid(Color::BLACK), 1.0); + let mut instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Moved".into(), xf: Affine::IDENTITY }); + instance.appearance = Appearance::basic(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), Paint::None, 0.0).into(); + let mut faint = path(d, shapes::line((10.0, 90.0).into(), (190.0, 90.0).into()), Paint::None, Paint::solid(Color::BLACK), 1.0); + faint.opacity = 0.5; + faint.blend = vectorcraft_color::BlendMode::Multiply; + let im = ImageObject { + key: "raster-1".into(), + width: 2, + height: 2, + xf: Affine::translate((150.0, 20.0)) * Affine::scale(10.0), + link: None, + placement: Default::default(), + pixels: None, + }; + vec![moved_by(line, 100.0), instance, faint, Node::new(d.alloc_id(), NodeKind::Image(Box::new(im)))] + }); + let art = path(&mut d, shapes::rectangle(Rect::new(10.0, 40.0, 30.0, 60.0)), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Moved".into(), art: Arc::new(moved_by(art, 20.0)) }); + d.images.insert("raster-1".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(png), proxy: None }); + d +} + +#[test] +fn drawings_apply_the_live_effects_once_and_match_drawings_written_alone() { + let d = drawings_doc(); + assert!(crate::bake_for_drawings(&d).is_some(), "the document has live effects to apply"); + // The left and right halves cropped, the whole page uncropped, and a region off the page. + let drawings = [ + (Rect::new(0.0, 0.0, 100.0, 100.0), true), + (Rect::new(100.0, 0.0, 200.0, 100.0), true), + (Rect::new(0.0, 0.0, 200.0, 100.0), false), + (Rect::new(300.0, 0.0, 400.0, 100.0), true), + ]; + // With every option, and with images and hatches left out (which adds setting notes). + let all_in = opts(&d); + for o in [all_in.clone(), DxfOptions { include_images: false, include_hatches: false, ..all_in }] { + let bakes = std::cell::Cell::new(0); + let outs = crate::export_drawings_with(&d, &o, &drawings, |doc| { + bakes.set(bakes.get() + 1); + crate::bake_for_drawings(doc) + }) + .unwrap(); + assert_eq!(bakes.get(), 1, "the live effects are applied once for every drawing"); + assert_eq!(outs.len(), drawings.len()); + for ((region, crop), out) in drawings.iter().zip(&outs) { + let alone = export_baking_alone(&d, &DxfOptions { region: *region, crop: *crop, ..o.clone() }); + assert_eq!(written(out), written(&alone), "the drawing over {region:?}, crop {crop}"); + let one = export(&d, &DxfOptions { region: *region, crop: *crop, ..o.clone() }).unwrap(); + assert_eq!(written(&one), written(&alone), "export over {region:?}, crop {crop}"); + } + let public: Vec<_> = export_drawings(&d, &o, &drawings).unwrap().iter().map(written).collect(); + assert_eq!(public, outs.iter().map(written).collect::>()); + // The halves hold different art, the left half a line with losses, and the region off the + // page nothing. + assert!(!entities(&outs[0]).is_empty() && !entities(&outs[1]).is_empty() && !outs[0].warnings.is_empty()); + assert_ne!(outs[0].bytes, outs[1].bytes); + assert!(entities(&outs[3]).is_empty() && outs[3].images.is_empty()); + if o.include_images { + assert_eq!(outs[2].images.len(), 1); + } else { + assert!(!outs[2].setting_notes.is_empty() && outs[2].images.is_empty()); + } + } +} + +#[test] +fn drawings_are_checked_before_the_live_effects_are_applied() { + let d = drawings_doc(); + let o = opts(&d); + let bakes = std::cell::Cell::new(0); + let count = |doc: &Document| { + bakes.set(bakes.get() + 1); + crate::bake_for_drawings(doc) + }; + let page = (d.artboards[0].rect, false); + let off = (Rect::new(0.0, 0.0, f64::NAN, 100.0), false); + assert_eq!(crate::export_drawings_with(&d, &o, &[page, off], count).unwrap_err(), "the export region is not finite"); + let e = crate::export_drawings_with(&d, &DxfOptions { scale: 0.0, ..o.clone() }, &[page], count).unwrap_err(); + assert!(e.starts_with("scale must be a number"), "{e}"); + assert!(crate::export_drawings_with(&d, &o, &[], count).unwrap().is_empty()); + assert_eq!(bakes.get(), 0, "nothing is applied for drawings that are refused or for none"); +} + +/// The thread's time on the CPU in nanoseconds where Linux reports it, otherwise `None`. +fn thread_cpu_ns() -> Option { + std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok() +} + +/// Time a Use Artboards export of eight artboards whose art has live effects, written drawing by +/// drawing with the effects applied for each (as before [`export_drawings`]) and with +/// [`export_drawings`], alternating, seven times each, and check that both write the same +/// drawings. Prints the median of each in milliseconds of the thread's CPU time (on Linux) and of +/// wall-clock time. +/// Run with `cargo test --release -p vectorcraft-cad --lib dxf_artboards_bake_perf -- --ignored --nocapture`. +#[test] +#[ignore = "manual timing probe; wall-clock performance depends on machine load"] +fn dxf_artboards_bake_perf() { + const BOARDS: usize = 8; + let mut d = Document::new(200.0 * BOARDS as f64, 200.0); + let layer = d.layers[0].id; + let effect = |id: &str, params: serde_json::Value| vectorcraft_doc::Effect { id: id.into(), params, visible: true }; + let mut art = vec![]; + for i in 0..50 { + let (x, y) = (f64::from(i % 10) * 5.0, f64::from(i / 10) * 5.0); + art.push(Arc::new(path(&mut d, shapes::rectangle(Rect::new(x, y, x + 4.0, y + 4.0)), Paint::None, Paint::solid(Color::BLACK), 0.5))); + } + let mut cell = Node::group(d.alloc_id(), art); + cell.appearance.effects.push(effect("distort.zigZag", serde_json::json!({"size": 1.0, "relative": false, "ridges": 4, "points": "smooth"}))); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Cell".into(), art: Arc::new(cell) }); + for b in 0..BOARDS { + let x0 = 200.0 * b as f64; + for i in 0..250 { + let (x, y) = (x0 + f64::from(i % 25) * 8.0, f64::from(i / 25) * 8.0); + let mut n = path(&mut d, shapes::ellipse(Rect::new(x, y, x + 6.0, y + 6.0)), Paint::None, Paint::solid(Color::BLACK), 0.5); + let params = serde_json::json!({"size": 1.0, "relative": false, "detail": 10.0, "points": "smooth", "seed": i}); + n.appearance.effects.push(effect("distort.roughen", params)); + d.insert(Some(layer), usize::MAX, n).unwrap(); + } + for i in 0..20 { + let xf = Affine::translate((x0 + f64::from(i % 5) * 40.0, 100.0 + f64::from(i / 5) * 25.0)); + let instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Cell".into(), xf }); + d.insert(Some(layer), usize::MAX, instance).unwrap(); + } + } + let o = DxfOptions { unit: Unit::Points, ..DxfOptions::default() }; + let drawings: Vec<(Rect, bool)> = (0..BOARDS).map(|b| (Rect::new(200.0 * b as f64, 0.0, 200.0 * (b + 1) as f64, 200.0), true)).collect(); + let before = || drawings.iter().map(|&(region, crop)| export_baking_alone(&d, &DxfOptions { region, crop, ..o.clone() })).collect::>(); + let after = || export_drawings(&d, &o, &drawings).unwrap(); + let time = |f: &dyn Fn() -> Vec| { + let (cpu, wall) = (thread_cpu_ns(), std::time::Instant::now()); + let outs = f(); + let wall = wall.elapsed().as_secs_f64() * 1000.0; + let cpu = cpu.zip(thread_cpu_ns()).map(|(a, b)| (b - a) as f64 / 1e6); + (outs, cpu, wall) + }; + let (mut runs_before, mut runs_after) = (vec![], vec![]); + for _ in 0..7 { + let (a, cpu_a, wall_a) = time(&before); + let (b, cpu_b, wall_b) = time(&after); + assert_eq!(a.len(), BOARDS); + assert_eq!(a.iter().map(written).collect::>(), b.iter().map(written).collect::>(), "both write the same drawings"); + runs_before.push((cpu_a, wall_a)); + runs_after.push((cpu_b, wall_b)); + } + let median = |runs: &[(Option, f64)], cpu: bool| { + let mut v: Vec = runs.iter().filter_map(|r| if cpu { r.0 } else { Some(r.1) }).collect(); + v.sort_by(f64::total_cmp); + v.get(v.len() / 2).copied() + }; + for (name, runs) in [("drawing by drawing", &runs_before), ("export_drawings", &runs_after)] { + println!( + "{name}: {BOARDS} artboards, median CPU {:?} ms, median wall {:?} ms; runs (CPU ms, wall ms) {runs:?}", + median(runs, true), + median(runs, false) + ); + } +} diff --git a/crates/color/src/cms.rs b/crates/color/src/cms.rs index 3ad4820ce1..96640b5508 100644 --- a/crates/color/src/cms.rs +++ b/crates/color/src/cms.rs @@ -347,7 +347,9 @@ pub fn profiles_generation() -> u64 { /// Profile `name` as an ICC file to embed in an export: any RGB or CMYK profile of [`profiles`] /// (by its current or legacy name), or [`GRAY`]. Built-in profiles are written in code from the /// CMS: the RGB spaces from their primaries, the CMYK spaces as lookup tables sampled from their -/// model (both directions, perceptual and relative colorimetric, Lab PCS); a profile the user +/// model (both directions, perceptual and relative colorimetric, Lab PCS, with the model's paper +/// as the media white point; the colorimetric Lab → CMYK table without black-point +/// compensation, the perceptual and saturation ones with it); a profile the user /// loaded is the file it came from. Cached. pub fn icc_bytes(name: &str) -> Result, CmsError> { static CACHE: Mutex)>> = Mutex::new(Vec::new()); @@ -361,8 +363,17 @@ pub fn icc_bytes(name: &str) -> Result, CmsError> { let bytes: Arc<[u8]> = if name == GRAY { icc::encode(&icc::gray_profile(name))? } else if BUILTIN_CMYK.contains(&name) { - let cms = Cms::new(&ColorSettings { cmyk: name.into(), ..ColorSettings::default() })?; - icc::encode(&icc::cmyk_profile(name, |c| cms.cmyk_to_lab(c), |l| cms.lab_to_cmyk(l, Intent::RelativeColorimetric)))? + // The perceptual and saturation tables map the shadows with black-point compensation; the + // colorimetric table is the inverse of the CMYK → Lab table, without it. + let mapped = Cms::new(&ColorSettings { cmyk: name.into(), bpc: true, ..ColorSettings::default() })?; + let cms = Cms::new(&ColorSettings { cmyk: name.into(), bpc: false, ..ColorSettings::default() })?; + let paper = match &cms.cmyk { + CmykSpace::Generic(g) => g.paper_xyz(), + CmykSpace::Device | CmykSpace::Icc(_) => lab::D50, + }; + let to_lab = |c| cms.cmyk_to_lab(c); + let shadows = |l| mapped.lab_to_cmyk(l, Intent::RelativeColorimetric); + icc::encode(&icc::cmyk_profile(name, paper, to_lab, shadows, |l| cms.lab_to_cmyk(l, Intent::RelativeColorimetric)))? } else { icc::builtin_rgb_bytes(name)? } diff --git a/crates/color/src/cms/generic.rs b/crates/color/src/cms/generic.rs index 3d532ac02a..16f251054b 100644 --- a/crates/color/src/cms/generic.rs +++ b/crates/color/src/cms/generic.rs @@ -133,6 +133,11 @@ pub struct GenericCmyk { } impl GenericCmyk { + /// Absolute XYZ (D50) of the paper. + pub fn paper_xyz(&self) -> [f32; 3] { + self.paper_xyz + } + pub fn new(params: GenericCmykParams) -> Self { let paper_xyz = lab_to_xyz(params.paper); let mut prim = [D50; 16]; diff --git a/crates/color/src/cms/icc.rs b/crates/color/src/cms/icc.rs index ffddd6c955..8fc287ae23 100644 --- a/crates/color/src/cms/icc.rs +++ b/crates/color/src/cms/icc.rs @@ -446,11 +446,20 @@ const B2A_GRID: usize = 17; const GAMUT_GRID: usize = 9; /// A CMYK output profile sampled from a conversion: `to_lab` (CMYK → media-relative Lab) in a -/// 9⁴ table, `from_lab` (Lab → CMYK, gamut-mapped) in a 17³ table, Lab PCS (ICC v4 encoding). +/// 9⁴ table, and Lab → CMYK in 17³ tables, Lab PCS (ICC v4 encoding): `mapped` (gamut-mapped, +/// with black-point compensation) for the perceptual and saturation intents, `colorimetric` (the +/// colorimetric inverse of `to_lab`) for the colorimetric intents and the gamut tag. /// It carries every tag ICC.1 requires of an output profile: the tables for all three intents /// and the gamut tag (Windows rejects a CMYK profile without them, so Photos couldn't show a CMYK -/// TIFF that embedded one, #2707). -pub(super) fn cmyk_profile(name: &str, to_lab: impl Fn([f32; 4]) -> lab::Lab, from_lab: impl Fn(lab::Lab) -> [f32; 4]) -> ColorProfile { +/// TIFF that embedded one, #2707). The media white point is `paper` (absolute XYZ, D50), which +/// the ICC-absolute colorimetric intent reproduces. +pub(super) fn cmyk_profile( + name: &str, + paper: [f32; 3], + to_lab: impl Fn([f32; 4]) -> lab::Lab, + mapped: impl Fn(lab::Lab) -> [f32; 4], + colorimetric: impl Fn(lab::Lab) -> [f32; 4], +) -> ColorProfile { let unit = |i: usize, n: usize| i as f32 / (n - 1) as f32; let q = |v: f32| (v.clamp(0.0, 1.0) * 65535.0).round() as u16; let mut a2b = Vec::with_capacity(A2B_GRID.pow(4) * 3); @@ -459,17 +468,21 @@ pub(super) fn cmyk_profile(name: &str, to_lab: impl Fn([f32; 4]) -> lab::Lab, fr let l = to_lab(cmyk); a2b.extend([l.l / 100.0, (l.a + 128.0) / 255.0, (l.b + 128.0) / 255.0].map(q)); } - let mut b2a = Vec::with_capacity(B2A_GRID.pow(3) * 4); - for i in 0..B2A_GRID.pow(3) { - let [l, a, b] = [2, 1, 0].map(|d| unit(i / B2A_GRID.pow(d) % B2A_GRID, B2A_GRID)); - b2a.extend(from_lab(lab::Lab::new(l * 100.0, a * 255.0 - 128.0, b * 255.0 - 128.0)).map(q)); - } + let b2a_of = |from_lab: &dyn Fn(lab::Lab) -> [f32; 4]| { + let mut b2a = Vec::with_capacity(B2A_GRID.pow(3) * 4); + for i in 0..B2A_GRID.pow(3) { + let [l, a, b] = [2, 1, 0].map(|d| unit(i / B2A_GRID.pow(d) % B2A_GRID, B2A_GRID)); + b2a.extend(from_lab(lab::Lab::new(l * 100.0, a * 255.0 - 128.0, b * 255.0 - 128.0)).map(q)); + } + b2a + }; + let (b2a_mapped, b2a) = (b2a_of(&mapped), b2a_of(&colorimetric)); // Gamut: 0 where a colour separates and comes back within a ΔE of 3, else out of gamut. let mut gamut = Vec::with_capacity(GAMUT_GRID.pow(3)); for i in 0..GAMUT_GRID.pow(3) { let [l, a, b] = [2, 1, 0].map(|d| unit(i / GAMUT_GRID.pow(d) % GAMUT_GRID, GAMUT_GRID)); let want = lab::Lab::new(l * 100.0, a * 255.0 - 128.0, b * 255.0 - 128.0); - gamut.push(if lab::delta_e2000(want, to_lab(from_lab(want))) <= 3.0 { 0 } else { u16::MAX }); + gamut.push(if lab::delta_e2000(want, to_lab(colorimetric(want))) <= 3.0 { 0 } else { u16::MAX }); } let identity = |n: usize| vec![ToneReprCurve::Parametric(vec![1.0]); n]; let table = |inputs: usize, outputs: usize, grid: usize, clut: Vec| { @@ -490,6 +503,7 @@ pub(super) fn cmyk_profile(name: &str, to_lab: impl Fn([f32; 4]) -> lab::Lab, fr }) }; let a2b = table(4, 3, A2B_GRID, a2b); + let b2a_mapped = table(3, 4, B2A_GRID, b2a_mapped); let b2a = table(3, 4, B2A_GRID, b2a); let gamut = table(3, 1, GAMUT_GRID, gamut); let mut p = ColorProfile::default(); @@ -498,12 +512,12 @@ pub(super) fn cmyk_profile(name: &str, to_lab: impl Fn([f32; 4]) -> lab::Lab, fr p.pcs = DataColorSpace::Lab; p.rendering_intent = RenderingIntent::RelativeColorimetric; p.white_point = moxcms::WHITE_POINT_D50.to_xyzd(); - p.media_white_point = Some(p.white_point); + p.media_white_point = Some(moxcms::Xyzd::new(f64::from(paper[0]), f64::from(paper[1]), f64::from(paper[2]))); p.lut_a_to_b_perceptual = Some(a2b.clone()); p.lut_a_to_b_saturation = Some(a2b.clone()); p.lut_a_to_b_colorimetric = Some(a2b); - p.lut_b_to_a_perceptual = Some(b2a.clone()); - p.lut_b_to_a_saturation = Some(b2a.clone()); + p.lut_b_to_a_perceptual = Some(b2a_mapped.clone()); + p.lut_b_to_a_saturation = Some(b2a_mapped); p.lut_b_to_a_colorimetric = Some(b2a); p.gamut = Some(gamut); labelled(p, name) diff --git a/crates/color/src/cms/tests_icc.rs b/crates/color/src/cms/tests_icc.rs index bee0f0f9fa..2c1d96638b 100644 --- a/crates/color/src/cms/tests_icc.rs +++ b/crates/color/src/cms/tests_icc.rs @@ -30,11 +30,62 @@ fn cmyk_profiles_convert_like_the_cms() { let de = delta_e2000(lab::srgb_to_lab(want), lab::srgb_to_lab(got)); assert!(de < 2.5, "{name} {cmyk:?}: {want:?} vs {got:?} (ΔE {de})"); } - // And back: an in-gamut colour separates to about the same inks. - let srgb = cms.cmyk_to_srgb([0.1, 0.6, 0.8, 0.0], false); - let back = p.from_srgb(srgb, Intent::RelativeColorimetric).unwrap(); - let again = cms.cmyk_to_srgb([back[0], back[1], back[2], back[3]], false); - assert!(delta_e2000(lab::srgb_to_lab(srgb), lab::srgb_to_lab(again)) < 3.0, "{back:?}"); + // And back: in-gamut colours separate to inks that print them. The Lab → CMYK table is + // the colorimetric inverse of the CMYK → Lab table, with no black-point compensation. + for inks in [ + [0.1, 0.6, 0.8, 0.0], + [0.5, 0.1, 0.3, 0.1], + [0.3, 0.3, 0.3, 0.2], + [0.05, 0.05, 0.4, 0.0], + [0.4, 0.3, 0.3, 0.6], + [0.6, 0.5, 0.5, 0.4], + [0.2, 0.2, 0.2, 0.8], + [0.0, 0.0, 0.0, 0.5], + ] { + let srgb = cms.cmyk_to_srgb(inks, false); + let back = p.from_srgb(srgb, Intent::RelativeColorimetric).unwrap(); + let again = cms.cmyk_to_srgb([back[0], back[1], back[2], back[3]], false); + let de = delta_e2000(lab::srgb_to_lab(srgb), lab::srgb_to_lab(again)); + assert!(de < 1.5, "{name} {inks:?}: {srgb:?} -> {back:?} -> {again:?} (ΔE {de})"); + } + // The perceptual table keeps black-point compensation: source black separates to inks + // that print the press's black point, as the CMS separates it with compensation. + let compensated = Cms::new(&ColorSettings { cmyk: name.into(), bpc: true, ..Default::default() }).unwrap(); + let want = compensated.srgb_to_cmyk([0.0; 3], Intent::RelativeColorimetric); + let got = p.from_srgb([0.0; 3], Intent::Perceptual).unwrap(); + let printed = |inks: &[f32]| cms.cmyk_to_lab([inks[0], inks[1], inks[2], inks[3]]); + let de = delta_e2000(printed(&want), printed(&got)); + assert!(de < 1.5, "{name}: perceptual black {got:?} prints {:?}, want {want:?} ({:?})", printed(&got), printed(&want)); + } +} + +#[test] +fn cmyk_profiles_separate_saturated_inks_back_without_clipping_to_srgb() { + // CMYK → PCS → CMYK through the profile's own colorimetric tables, by way of linear ProPhoto + // RGB, which holds every color these profiles print, so no display gamut clips the inks. + // Inks that print outside sRGB come back to inks that print the same color. + for name in BUILTIN_CMYK { + let p = IccProfile::from_bytes(None, &icc_bytes(name).unwrap()).unwrap(); + let cms = Cms::new(&ColorSettings { cmyk: name.into(), bpc: false, ..Default::default() }).unwrap(); + for inks in + [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [1.0, 1.0, 0.0, 0.0], [0.0, 1.0, 1.0, 0.0], [1.0, 0.0, 1.0, 0.0]] + { + let back = p.to_same_model_of(&p, &inks, Intent::RelativeColorimetric, false).unwrap(); + let de = delta_e2000(cms.cmyk_to_lab(inks), cms.cmyk_to_lab([back[0], back[1], back[2], back[3]])); + // Within the ΔE of 3 that the gamut tag counts as reproduced. + assert!(de <= 3.0, "{name} {inks:?} -> {back:?} (ΔE {de})"); + } + } +} + +#[test] +fn cmyk_profiles_carry_their_paper_as_the_media_white() { + let generic = generic::swop_like(); + let p = parse(&icc_bytes(GENERIC_CMYK).unwrap()); + let white = p.media_white_point.unwrap(); + let paper = lab::lab_to_xyz(generic.paper); + for (got, want) in [white.x, white.y, white.z].iter().zip(paper) { + assert!((*got - f64::from(want)).abs() < 2e-3, "{white:?} vs {paper:?}"); } } @@ -116,9 +167,10 @@ fn black_point_compensation_maps_the_darkest_ink_to_rgb_black() { let rich = [0.75, 0.68, 0.67, 0.9]; let (on, off) = (icc_cmyk(true).cmyk_to_rgb(rich, Intent::RelativeColorimetric), icc_cmyk(false).cmyk_to_rgb(rich, Intent::RelativeColorimetric)); // Without compensation the profile's black is a dark grey; with it, rich black goes most of - // the way to RGB black (not all: it isn't quite the darkest ink the profile prints). + // the way to RGB black (not all: it isn't quite the darkest ink the profile prints, and the + // profile's Lab → CMYK table carries no compensation of its own). assert!(off.iter().all(|v| *v > 0.1), "without: {off:?}"); - assert!(on.iter().zip(off).all(|(a, b)| *a < 0.08 && *a < b * 0.5), "with: {on:?}, without: {off:?}"); + assert!(on.iter().zip(off).all(|(a, b)| *a < 0.09 && *a < b * 0.55), "with: {on:?}, without: {off:?}"); // The screen shows what an sRGB conversion writes, compensated alike. let srgb = |bpc| { let c = icc_cmyk(bpc); diff --git a/crates/doc/src/appearance.rs b/crates/doc/src/appearance.rs index 3bfba32f6a..737e10eb58 100644 --- a/crates/doc/src/appearance.rs +++ b/crates/doc/src/appearance.rs @@ -143,6 +143,11 @@ impl Appearance { pub fn fill_paint(&self) -> Paint { self.fill().map(|f| f.paint.clone()).unwrap_or(Paint::None) } + /// Whether any visible fill has non-None paint. Unlike [`Self::fill`], this + /// includes lower fills in the stack; zero opacity still counts for selecting its geometry. + pub fn has_visible_fill(&self) -> bool { + self.items.iter().any(|item| matches!(item, AppearanceItem::Fill(fill) if fill.visible && !fill.paint.is_none())) + } pub fn stroke_paint(&self) -> Paint { self.stroke().map(|s| s.paint.clone()).unwrap_or(Paint::None) } 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 3b415ef1ed..93baa85ed8 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -82,8 +82,9 @@ impl Default for HitOptions { } } -/// The shapes that an image's own fills and strokes paint, each with its fill rule and the fill or -/// stroke that paints it (none for fills and strokes that paint nothing). Effects are evaluated +/// The shapes that an image's own fills and strokes paint, or the fills and strokes of the art of a +/// symbol instance whose own fill or stroke has a geometry effect, each with its fill rule and the +/// fill or stroke that paints it (none for fills and strokes that paint nothing). Effects are evaluated /// above this crate, so the engine registers one with [`set_image_paint`]. It looks up swatches and /// patterns in the document it is given. pub type ImagePaint = fn(Option<&Document>, &Node) -> Vec<(BezPath, FillRule, AppearanceItem)>; @@ -97,10 +98,58 @@ pub fn set_image_paint(f: ImagePaint) { let _ = IMAGE_PAINT.set(f); } -/// The shapes that the image `n`'s own fills and strokes paint ([`set_image_paint`]), none while -/// nothing is registered. -pub(crate) fn image_paint(doc: Option<&Document>, n: &Node) -> Vec<(BezPath, FillRule, AppearanceItem)> { - IMAGE_PAINT.get().map_or_else(Vec::new, |f| f(doc, n)) +/// The shapes that [`ImagePaint`] gives for one object. +type Painted = Vec<(BezPath, FillRule, AppearanceItem)>; + +/// The shapes that the image or symbol instance `n` paints with its geometry effects +/// ([`set_image_paint`]), none while nothing is registered. The shapes of a symbol instance of +/// `doc` with an effect on a fill or stroke are kept on this thread ([`PAINT_KEPT`]) and measured +/// again when `n`, a symbol of `doc` or its 9-slice guides or natural size, a pattern of `doc`, +/// its swatches or color groups, or the +/// [`LiveInputs`] have changed since, and on every call while `n` or the document's symbols or +/// patterns hold a placed document or the symbols hold an image ([`symbols_hold_images`]). +pub(crate) fn image_paint(doc: Option<&Document>, n: &Node) -> Rc { + let Some(f) = IMAGE_PAINT.get() else { return Rc::default() }; + let row_effects = || n.appearance.items.iter().any(|i| !i.effects().is_empty()); + let Some(d) = doc.filter(|_| matches!(n.kind, NodeKind::SymbolInstance { .. }) && row_effects()) else { + return Rc::new(f(doc, n)); + }; + let inputs = live_inputs(); + if let Some(painted) = kept(&PAINTED, d, n, inputs) { + return painted; + } + #[cfg(test)] + PAINT_EVALUATED.with(|c| c.set(c.get() + 1)); + let painted = Rc::new(f(doc, n)); + if !symbols_hold_images(d) { + let size = painted.iter().fold(0usize, |s, (bp, _, _)| s.saturating_add(1 + bp.elements().len())); + keep(&PAINTED, d, n, inputs, &painted, size, PAINT_KEPT); + } + painted +} + +/// Does the art of a symbol of `doc` hold an image? The shapes its fills and strokes paint can +/// follow its pixels, which change when its file is read again, so [`image_paint`] does not keep +/// the shapes of an instance then. +fn symbols_hold_images(doc: &Document) -> bool { + let mut image = false; + doc.symbols.iter().for_each(|s| s.art.walk(&mut |c| image |= matches!(c.kind, NodeKind::Image(_)))); + image +} + +/// How many symbol instances' shapes [`image_paint`] keeps on each thread: every click and every +/// hover measures each instance whose fill or stroke has a geometry effect. +const PAINT_KEPT: usize = 64; + +thread_local! { + /// The shapes [`image_paint`] keeps, the latest first. + static PAINTED: RefCell>> = const { RefCell::new(Vec::new()) }; +} + +#[cfg(test)] +thread_local! { + /// How many symbol instances [`image_paint`] measured on this thread. + static PAINT_EVALUATED: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// One level of evaluation of a live object in a document, as the canvas draws it: type in an @@ -127,21 +176,72 @@ fn live_inputs() -> u64 { LIVE_ART.get().map_or(0, |(_, inputs)| inputs()) } -/// A live object evaluated by [`live_art`] on this thread: the object, its document's symbols (by -/// name and art), patterns, swatches and color groups and the [`LiveInputs`] as they were, the art -/// and its [`art_size`]. -struct EvaluatedLive { +/// An object evaluated by [`live_art`] or [`image_paint`] on this thread: the object, its +/// document's symbols (by name and art), patterns, swatches and color groups, the document data +/// that symbols' 9-slice guides and natural sizes are kept in, and the [`LiveInputs`] as they +/// were, the result and its size. +struct Evaluated { node: Node, symbols: Vec<(String, Arc)>, patterns: Vec, swatches: crate::Shared>, swatch_groups: crate::Shared>, + unknown: crate::Shared>, inputs: u64, - art: Rc>, + art: Rc, size: usize, } -impl EvaluatedLive { +/// The evaluations kept on this thread in one store, the latest first. +type Store = std::thread::LocalKey>>>; + +/// The evaluation of `n` in `doc` with inputs `inputs` that `store` keeps, moved to the front. +fn kept(store: &'static Store, doc: &Document, n: &Node, inputs: u64) -> Option> { + store.with_borrow_mut(|kept| { + let i = kept.iter().position(|e| e.is_of(doc, n, inputs))?; + let e = kept.remove(i); + let art = e.art.clone(); + kept.insert(0, e); + Some(art) + }) +} + +/// Keep `art`, of size `size`, the evaluation of `n` in `doc` with inputs `inputs`, at the front +/// of `store`, which keeps `most` evaluations whose sizes add up to [`LIVE_KEPT_SIZE`] at most. +/// Nothing is kept when `art` alone is larger, or when `n` or the document's symbols or patterns +/// hold a placed document ([`holds_placed`]). +fn keep(store: &'static Store, doc: &Document, n: &Node, inputs: u64, art: &Rc, size: usize, most: usize) { + if size > LIVE_KEPT_SIZE || holds_placed(doc, n) { + return; + } + let e = Evaluated::new(doc, n, inputs, art, size); + store.with_borrow_mut(|kept| { + kept.insert(0, e); + kept.truncate(most); + let mut total = 0usize; + kept.retain(|e| { + total = total.saturating_add(e.size); + total <= LIVE_KEPT_SIZE + }); + }); +} + +impl Evaluated { + /// `art`, of size `size`, the evaluation of `n` in `doc` with inputs `inputs`, as they are now. + fn new(doc: &Document, n: &Node, inputs: u64, art: &Rc, size: usize) -> Self { + Self { + node: n.clone(), + symbols: doc.symbols.iter().map(|s| (s.name.clone(), s.art.clone())).collect(), + patterns: doc.patterns.clone(), + swatches: doc.swatches.clone(), + swatch_groups: doc.swatch_groups.clone(), + unknown: doc.unknown.clone(), + inputs, + art: art.clone(), + size, + } + } + /// Is this the evaluation of `n` in `doc`, with inputs `inputs`, as they are now? fn is_of(&self, doc: &Document, n: &Node, inputs: u64) -> bool { self.inputs == inputs @@ -151,6 +251,7 @@ impl EvaluatedLive { && self.patterns == doc.patterns && self.swatches == doc.swatches && self.swatch_groups == doc.swatch_groups + && self.unknown == doc.unknown } } @@ -158,8 +259,9 @@ impl EvaluatedLive { /// envelope's stroke band hits it again and again, and an envelope can hold a blend. const LIVE_KEPT: usize = 4; -/// Most [`art_size`] the evaluations [`live_art`] keeps on one thread add up to. Art larger than -/// this is not kept. +/// Most size the evaluations [`live_art`] keeps on one thread add up to ([`art_size`]), and the +/// shapes [`image_paint`] keeps (each shape and its path elements). Art larger than this is not +/// kept. const LIVE_KEPT_SIZE: usize = 250_000; /// The size of `art` for [`LIVE_KEPT_SIZE`]: its objects and the anchors of their paths. @@ -184,52 +286,23 @@ fn holds_placed(doc: &Document, n: &Node) -> bool { thread_local! { /// The evaluations [`live_art`] keeps, the latest first. - static EVALUATED: RefCell> = const { RefCell::new(Vec::new()) }; + static EVALUATED: RefCell>>> = const { RefCell::new(Vec::new()) }; } /// The art live object `n` of `doc` draws ([`set_live_art`]); [`crate::live::expand_live`] while -/// nothing is registered. The art is evaluated again when `n`, a symbol of `doc`, a pattern of -/// `doc`, its swatches or color groups, or the [`LiveInputs`] have changed since, and on every +/// nothing is registered. The art is evaluated again when `n`, a symbol of `doc` or its 9-slice +/// guides or natural size, a pattern of `doc`, its swatches or color groups, or the +/// [`LiveInputs`] have changed since, and on every /// click while it or the document's symbols or patterns hold a placed document ([`holds_placed`]). fn live_art(doc: &Document, n: &Node) -> Rc> { let inputs = live_inputs(); - let kept = EVALUATED.with_borrow_mut(|kept| { - let i = kept.iter().position(|e| e.is_of(doc, n, inputs))?; - let e = kept.remove(i); - let art = e.art.clone(); - kept.insert(0, e); - Some(art) - }); - if let Some(art) = kept { + if let Some(art) = kept(&EVALUATED, doc, n, inputs) { return art; } #[cfg(test)] LIVE_EVALUATED.with(|c| c.set(c.get() + 1)); let art = Rc::new(LIVE_ART.get().map_or_else(|| crate::live::expand_live(n), |(f, _)| f(Some(doc), n))); - let size = art_size(&art); - if size > LIVE_KEPT_SIZE || holds_placed(doc, n) { - return art; - } - let symbols = doc.symbols.iter().map(|s| (s.name.clone(), s.art.clone())).collect(); - let e = EvaluatedLive { - node: n.clone(), - symbols, - patterns: doc.patterns.clone(), - swatches: doc.swatches.clone(), - swatch_groups: doc.swatch_groups.clone(), - inputs, - art: art.clone(), - size, - }; - EVALUATED.with_borrow_mut(|kept| { - kept.insert(0, e); - kept.truncate(LIVE_KEPT); - let mut total = 0usize; - kept.retain(|e| { - total = total.saturating_add(e.size); - total <= LIVE_KEPT_SIZE - }); - }); + keep(&EVALUATED, doc, n, inputs, &art, art_size(&art), LIVE_KEPT); art } @@ -257,7 +330,7 @@ pub fn set_drawn_art(f: DrawnArt) { /// The art of an object found by [`drawn`] (none, or one object), with what it was found from, and /// the box round everything that art can paint. struct EvaluatedDrawn { - of: EvaluatedLive, + of: Evaluated>, reach: Option, } @@ -310,7 +383,8 @@ fn plain(mask: bool, f: impl FnOnce() -> T) -> T { /// nothing is registered, while a [`DrawnOff`] guard lives, for objects whose art is not evaluated /// ([`evaluates`]), and when nothing in `n`, nor the art of a symbol an instance in it shows, has a /// visible effect ([`draws_effects`]). The art is evaluated again when `n`, a symbol of the -/// document, its patterns, swatches or color groups, or the [`LiveInputs`] have changed since, and +/// document or its 9-slice guides or natural size, its patterns, swatches or color groups, or the +/// [`LiveInputs`] have changed since, and /// on every call while it holds a placed document ([`holds_placed`]). When the art kept is full, new /// art replaces as much other art as it needs room for, and art larger than [`LIVE_KEPT_SIZE`] is /// kept alone. @@ -332,16 +406,7 @@ fn drawn(symbols: &SymbolBoxes, n: &Node) -> Option<(Rc>, Option let art = Rc::new(art.into_iter().collect::>()); let size = art_size(&art).saturating_add(art_size(std::slice::from_ref(n))); if !holds_placed(doc, n) { - let of = EvaluatedLive { - node: n.clone(), - symbols: doc.symbols.iter().map(|s| (s.name.clone(), s.art.clone())).collect(), - patterns: doc.patterns.clone(), - swatches: doc.swatches.clone(), - swatch_groups: doc.swatch_groups.clone(), - inputs, - art: art.clone(), - size, - }; + let of = Evaluated::new(doc, n, inputs, &art, size); DRAWN.with_borrow_mut(|(kept, total)| { if let Some(old) = kept.remove(&n.id) { *total = total.saturating_sub(old.of.size); @@ -607,9 +672,11 @@ fn objects_at_repeated(doc: &Document, p: Point, opt: HitOptions, scope: Option< /// [`objects_at_repeated`] after `tops`, the topmost objects under `p` already found. fn objects_at_repeated_after(doc: &Document, p: Point, opt: HitOptions, scope: Option, mut tops: Vec) -> Vec { - // Each round leaves out the objects found so far (and everything inside them). - while let Some(top) = hit_test_skipping(doc, p, opt, &|id| tops.contains(&id), true).map(|h| h.top_object(scope)) { - if tops.contains(&top) { + // Each round leaves out the objects found so far (and everything inside them). `found` holds + // the same ids as `tops`, which keeps their order. + let mut found: HashSet = tops.iter().copied().collect(); + while let Some(top) = hit_test_skipping(doc, p, opt, &|id| found.contains(&id), true).map(|h| h.top_object(scope)) { + if !found.insert(top) { break; } tops.push(top); @@ -1290,8 +1357,9 @@ fn hit_stroke(n: &Node, bp: &vectorcraft_geom::BezPath, rule: vectorcraft_geom:: stroke_contains(bp, 0.0, opt.tol, p).then_some(HitKind::Outline) } -/// Check the body without assembling a `BezPath`. A miss near a joint or cap may still hit a -/// miter or square cap, so the caller falls back to the full stroke check there. +/// Check the body without assembling a `BezPath`. Near an end or joint, the caller uses the +/// full stroke check for non-round caps or joins: Butt and Bevel can reject a radial body hit, +/// while Miter and Square can extend beyond it. fn near_path_body(path: &PathData, p: Point, radius: f64, decoration_reach: f64) -> Option<(bool, bool)> { if !radius.is_finite() || radius < 0.0 || !decoration_reach.is_finite() || decoration_reach < 0.0 { return None; @@ -1349,6 +1417,7 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio } match &n.kind { NodeKind::Path { path, rule, .. } => { + let has_fill = n.appearance.has_visible_fill(); if opt.outline && let Some((hit, needs_full_check)) = near_path_body(path, p, opt.tol, 0.0) { @@ -1361,7 +1430,7 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio } let mut strokes = n.appearance.painted_strokes(); if !opt.outline - && n.appearance.fill().is_none_or(|f| f.paint.is_none()) + && !has_fill && let Some(s) = strokes.next() && strokes.next().is_none() && s.align == StrokeAlign::Center @@ -1376,10 +1445,10 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio path, p, s.width / 2.0 + opt.tol, - if s.join == crate::LineJoin::Miter || s.cap == crate::LineCap::Square { s.reach() + opt.tol } else { 0.0 }, + if s.join != crate::LineJoin::Round || s.cap != crate::LineCap::Round { s.reach() + opt.tol } else { 0.0 }, ) { - if hit { + if hit && !near_decoration { return Some(HitKind::Stroke); } if !near_decoration { @@ -1390,8 +1459,7 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio if let Some(k) = hit_stroke(n, &bp, *rule, p, opt) { return Some(k); } - let filled = !n.appearance.fill_paint().is_none(); - if !opt.outline && !opt.path_only && filled && fill_contains(&bp, *rule, p) { + if !opt.outline && !opt.path_only && has_fill && fill_contains(&bp, *rule, p) { return Some(HitKind::Fill); } None @@ -1412,7 +1480,7 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio if vectorcraft_geom::hit::distance_to_outline(&near, p) <= opt.tol { return Some(HitKind::Outline); } - (!opt.outline && !opt.path_only && fill_contains(&near, *rule, p)).then_some(HitKind::Fill) + (!opt.outline && !opt.path_only && n.appearance.has_visible_fill() && fill_contains(&near, *rule, p)).then_some(HitKind::Fill) } // The type path lies within the bounds: they rule out the rest before it is measured. NodeKind::Text(t) if opt.type_path_only => { @@ -1436,22 +1504,21 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio if opt.outline { return None; } - image_paint(Some(symbols.document()), n).iter().rev().find_map(|(bp, rule, item)| match item { - AppearanceItem::Stroke(s) => s.hits(bp, *rule, p, opt.tol).then_some(HitKind::Stroke), - AppearanceItem::Fill(_) => (!opt.path_only && fill_contains(bp, *rule, p)).then_some(HitKind::Fill), - }) + hit_painted(n, p, opt, symbols) } NodeKind::Text(_) | NodeKind::PlacedDocument(_) => { n.geometric_bounds_with(symbols).filter(|b| b.inflate(opt.tol, opt.tol).contains(p)).map(|_| HitKind::Bounds) } // A symbol instance is hit within its bounds, and outside them where its art paints - // ([`instance_art_hit`]). In the art of another instance walked outside that instance's - // bounds, it is hit only where its own art paints ([`ArtOnly`]). + // ([`instance_art_hit`]) or where the geometry effects of its active fill or stroke reshape + // the art it draws ([`image_paint`]) except in outline mode. In the art of another instance + // walked outside that instance's bounds, it is hit only where its own art paints + // ([`ArtOnly`]). NodeKind::SymbolInstance { .. } => { if !ArtOnly::on() && n.geometric_bounds_with(symbols).is_some_and(|b| b.inflate(opt.tol, opt.tol).contains(p)) { return Some(HitKind::Bounds); } - instance_art_hit(n, p, opt, symbols) + instance_art_hit(n, p, opt, symbols).or_else(|| if opt.outline { None } else { hit_painted(n, p, opt, symbols) }) } // A blend or an envelope is hit within its bounds, and outside them where its evaluated // art paints: a blend's keys and steps on a spine can reach past the keys and the spine, @@ -1478,6 +1545,16 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio } } +/// What a click at `p` hits among the shapes that the fills and strokes of `n` (an image or a +/// symbol instance) paint with their geometry effects ([`image_paint`]), the frontmost first: a +/// stroke along its shape, a fill inside it except with Selection by Path Only. +fn hit_painted(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option { + image_paint(Some(symbols.document()), n).iter().rev().find_map(|(bp, rule, item)| match item { + AppearanceItem::Stroke(s) => s.hits(bp, *rule, p, opt.tol).then_some(HitKind::Stroke), + AppearanceItem::Fill(_) => (!opt.path_only && fill_contains(bp, *rule, p)).then_some(HitKind::Fill), + }) +} + /// Is `p` within `tol` of the type path of `t` (in `n`), what "Type Object Selection by Path /// Only" picks type by: its baselines ([`crate::TextObject::baselines`]), area type's frame and /// type on a path's path, drawn through `n`'s perspective projection if it has one. @@ -2019,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 @@ -2188,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`]). @@ -2219,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/hit/tests.rs b/crates/doc/src/hit/tests.rs index 39efd78795..9d0133ec60 100644 --- a/crates/doc/src/hit/tests.rs +++ b/crates/doc/src/hit/tests.rs @@ -1262,6 +1262,60 @@ fn evaluated_art_is_not_kept_while_a_placed_document_may_show_in_it() { assert_eq!(evaluated(), before + 2); } +/// For instances of the symbol "Painted", a fill that paints the square from (300, 0) to +/// (320, 20); nothing for anything else. +fn painted_far_away(_: Option<&Document>, n: &Node) -> Vec<(BezPath, FillRule, AppearanceItem)> { + match &n.kind { + NodeKind::SymbolInstance { symbol, .. } if symbol == "Painted" => { + let square = shapes::rectangle(Rect::new(300.0, 0.0, 320.0, 20.0)).to_bezpath(); + vec![(square, FillRule::NonZero, AppearanceItem::Fill(crate::FillLayer::new(Paint::solid(Color::rgb(1.0, 0.0, 0.0)))))] + } + _ => vec![], + } +} + +/// Clicks and hovers measure the shapes a symbol instance's fill and stroke effects paint once, +/// and again only after the instance or the symbols change. +#[test] +fn clicks_measure_a_symbol_instances_painted_shapes_once_until_it_changes() { + set_image_paint(painted_far_away); + let mut d = Document::new(1000.0, 1000.0); + let l = d.layers[0].id; + let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::default_art()); + d.symbols.push(crate::Symbol { dynamic: false, name: "Painted".into(), art: Arc::new(art) }); + let inst = d.alloc_id(); + let mut n = Node::new(inst, NodeKind::SymbolInstance { symbol: "Painted".into(), xf: vectorcraft_geom::Affine::IDENTITY }); + n.appearance = Appearance::default_art().into(); + let offset = crate::Effect { id: "path.offsetPath".into(), params: serde_json::json!({"offset": 10}), visible: true }; + n.appearance.items[0].effects_mut().push(offset); + d.insert(Some(l), 0, n).unwrap(); + let measured = || PAINT_EVALUATED.with(std::cell::Cell::get); + let before = measured(); + let at = |d: &Document, x: f64| hit_test(d, Point::new(x, 10.0), HitOptions::default()).map(|h| h.leaf); + assert_eq!(at(&d, 310.0), Some(inst), "a click where the instance's fill paints"); + assert_eq!(at(&d, 500.0), None); + assert_eq!(at(&d, 10.0), Some(inst)); + assert_eq!(measured(), before + 1); + d.node_mut(inst).unwrap().appearance.items[0].effects_mut()[0].params = serde_json::json!({"offset": 12}); + assert_eq!(at(&d, 310.0), Some(inst)); + assert_eq!(measured(), before + 2, "a changed instance is measured again"); + let other = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), Appearance::default_art()); + d.symbols.push(crate::Symbol { dynamic: false, name: "Other".into(), art: Arc::new(other) }); + assert_eq!(at(&d, 310.0), Some(inst)); + assert_eq!(measured(), before + 3, "changed symbols measure it again"); + assert_eq!(at(&d, 310.0), Some(inst)); + assert_eq!(measured(), before + 3); + // An image's pixels change when its file is read again, so with one in a symbol's art every + // click measures the instance. + let xf = vectorcraft_geom::Affine::IDENTITY; + let im = crate::ImageObject { key: "k".into(), width: 10, height: 10, xf, link: None, placement: Default::default(), pixels: None }; + let image = Node::new(d.alloc_id(), NodeKind::Image(Box::new(im))); + d.symbols.push(crate::Symbol { dynamic: false, name: "Photo".into(), art: Arc::new(image) }); + assert_eq!(at(&d, 310.0), Some(inst)); + assert_eq!(at(&d, 310.0), Some(inst)); + assert!(measured() >= before + 5, "each click measures it: {}", measured() - before); +} + /// A kept evaluation is the evaluation of the object only while the fonts and plug-ins /// ([`LiveInputs`]) are as they were. #[test] @@ -1274,19 +1328,32 @@ fn a_kept_evaluation_is_stale_after_the_live_inputs_change() { } /// An evaluation of `n` in `d`, with inputs 7, holding no symbols, patterns or art. -fn kept_evaluation(d: &Document, n: &Node) -> EvaluatedLive { - EvaluatedLive { +fn kept_evaluation(d: &Document, n: &Node) -> Evaluated> { + Evaluated { node: n.clone(), symbols: vec![], patterns: vec![], swatches: d.swatches.clone(), swatch_groups: d.swatch_groups.clone(), + unknown: d.unknown.clone(), inputs: 7, art: std::rc::Rc::new(vec![]), size: 0, } } +/// A kept evaluation is stale once a symbol's 9-slice guides or natural size change: they place +/// the symbol's art, and the document keeps them apart from the symbols. +#[test] +fn a_kept_evaluation_is_stale_after_a_symbols_placement_changes() { + let mut d = Document::new(100.0, 100.0); + let n = Node::path(NodeId(3), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art()); + let e = kept_evaluation(&d, &n); + assert!(e.is_of(&d, &n, 7)); + d.unknown.insert(crate::SYMBOL_SIZES.into(), serde_json::json!({"Logo": [40.0, 20.0]})); + assert!(!e.is_of(&d, &n, 7)); +} + /// A kept evaluation is stale once a swatch changes, in a color group too: a painted live effect's /// pieces name swatches. #[test] @@ -1823,6 +1890,216 @@ fn objects_at_matches_repeated_hits_on_random_documents() { } } +/// [`objects_at_repeated_after`] with each found object looked up in the ordered list itself: the +/// reference the tests below hold the set lookup to, and the base that `select_behind_isolation_timing` times. +fn objects_at_repeated_after_by_list(doc: &Document, p: Point, opt: HitOptions, scope: Option, mut tops: Vec) -> Vec { + while let Some(top) = hit_test_skipping(doc, p, opt, &|id| tops.contains(&id), true).map(|h| h.top_object(scope)) { + if tops.contains(&top) { + break; + } + tops.push(top); + } + tops +} + +/// A layer holding a group of `count` overlapping 50 × 50 squares, member `i` at x = 5 × (`i` mod +/// 10), with a square at x = 0 below the group and above it, and one at x = 100 above it: the +/// document, the group and its members, topmost first. +fn isolated_stack(count: u32) -> (Document, NodeId, Vec) { + let mut d = Document::new(200.0, 200.0); + let l = d.layers[0].id; + let square = |d: &mut Document, x: f64| Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, 0.0, x + 50.0, 50.0)), Appearance::default_art()); + let below = square(&mut d, 0.0); + d.insert(Some(l), usize::MAX, below).unwrap(); + let members: Vec = (0..count).map(|i| square(&mut d, f64::from(i % 10) * 5.0)).collect(); + let mut ids: Vec = members.iter().map(|n| n.id).collect(); + let g = d.alloc_id(); + d.insert(Some(l), usize::MAX, Node::group(g, members.into_iter().map(Arc::new).collect())).unwrap(); + for x in [0.0, 100.0] { + let above = square(&mut d, x); + d.insert(Some(l), usize::MAX, above).unwrap(); + } + ids.reverse(); + (d, g, ids) +} + +/// Select Behind in an isolated group of 40 overlapping squares, with art around the group above +/// and below them: each member once, front to back, over 41 rounds of hit tests, and nothing where +/// only the art around the group lies. +#[test] +fn select_behind_in_isolation_lists_a_large_stack_once() { + let (d, g, ids) = isolated_stack(40); + let at = |x: f64, scope| objects_at(&d, Point::new(x, 25.0), HitOptions::default(), scope); + assert_eq!(at(47.5, Some(g)), ids); + assert_eq!(at(47.5, Some(g)).iter().collect::>().len(), 40, "no object twice"); + assert_eq!(at(47.5, None).len(), 3, "not isolated: the square above, the group and the square below"); + // At x = 17.5 only the members at x = 0 to 20 are hit (the one at 20 on its stroke, within + // the tolerance): `ids[k]` is member 39 - k. + let left: Vec = ids.iter().enumerate().filter(|(k, _)| (39 - k) % 10 <= 4).map(|(_, id)| *id).collect(); + assert_eq!(left.len(), 20); + assert_eq!(at(17.5, Some(g)), left); + assert!(at(125.0, Some(g)).is_empty(), "only the square around the group"); + assert_eq!(at(125.0, None).len(), 1); + let isolated = HitOptions { scope: Some(g), ..HitOptions::default() }; + let p = Point::new(47.5, 25.0); + assert_eq!(objects_at_repeated_after(&d, p, isolated, Some(g), ids[..15].to_vec()), ids, "the objects passed in stay first"); + let (d, g, clip, art) = masked_square(false); + let isolated = HitOptions { scope: Some(g), ..SELECTING }; + for p in [Point::new(140.0, 90.0), Point::new(170.0, 90.0), Point::new(100.0, 90.0)] { + let want = objects_at_repeated_after_by_list(&d, p, isolated, Some(g), vec![]); + assert_eq!(objects_at(&d, p, SELECTING, Some(g)), want, "clip group isolated, {p:?}"); + } + assert_eq!(objects_at(&d, Point::new(170.0, 90.0), SELECTING, Some(g)), vec![art], "the art its mask hides"); + assert!(objects_at(&d, Point::new(140.0, 90.0), SELECTING, Some(g)).contains(&clip), "the mask on its outline"); +} + +/// Documents built at random (nested groups, clipping groups, envelopes in Edit Contents, hidden +/// and locked objects), each object in turn isolated, and each list started with some of the +/// objects already found: the set lookup returns what the ordered-list lookup returns, field for +/// field. +#[test] +fn select_behind_in_isolation_matches_the_list_lookup_on_random_documents() { + let mut seed = 0x2545_f491_u32; + let mut next = move |n: u32| { + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + seed % n + }; + fn fill(d: &mut Document, parent: NodeId, depth: u32, next: &mut impl FnMut(u32) -> u32) { + for _ in 0..2 + next(5) { + let id = d.alloc_id(); + let rect = |next: &mut dyn FnMut(u32) -> u32| { + let (x, y) = (f64::from(next(60)), f64::from(next(60))); + Rect::new(x, y, x + 10.0 + f64::from(next(50)), y + 10.0 + f64::from(next(50))) + }; + let mut n = match next(if depth < 3 { 9 } else { 4 }) { + 4 | 5 => Node::group(id, Vec::new()), + 6 => { + let mut g = Node::group(id, Vec::new()); + g.set_clips(true); + g + } + 7 => { + let content = + (0..2).map(|_| Arc::new(Node::path(d.alloc_id(), shapes::rectangle(rect(next)), Appearance::default_art()))).collect(); + Node::new( + id, + NodeKind::Envelope { + content, + kind: Box::new(crate::live::EnvelopeKind::Warp { + style: "arc".to_string(), + bend: 0.0, + h: 0.0, + v: 0.0, + horizontal: true, + version: 0, + }), + fidelity: 100.0, + editing: next(2) == 0, + options: Default::default(), + frame: Box::new(vectorcraft_geom::Affine::IDENTITY), + }, + ) + } + _ => Node::path(id, shapes::rectangle(rect(next)), if next(4) == 0 { Appearance::default() } else { Appearance::default_art() }), + }; + n.visible = next(8) != 0; + n.locked = next(8) == 0; + let group = matches!(n.kind, NodeKind::Group { .. }); + d.insert(Some(parent), usize::MAX, n).unwrap(); + if group { + fill(d, id, depth + 1, next); + } + } + } + let mut compared = 0; + for round in 0..60 { + let mut d = Document::new(120.0, 120.0); + let layer = d.layers[0].id; + fill(&mut d, layer, 0, &mut next); + let mut scopes = vec![None]; + d.walk(|n| { + if n.id != layer { + scopes.push(Some(n.id)); + } + }); + for _ in 0..6 { + let p = Point::new(f64::from(next(120)), f64::from(next(120))); + let opt = HitOptions { outline: next(5) == 0, path_only: next(5) == 0, clip_outlines: next(2) == 0, ..Default::default() }; + for &scope in &scopes { + let opt = HitOptions { scope, ..opt }; + let want = objects_at_repeated_after_by_list(&d, p, opt, scope, vec![]); + let context = format!("round {round}, {p:?}, {opt:?}"); + assert_eq!(objects_at_repeated_after(&d, p, opt, scope, vec![]), want, "{context}"); + if scope.is_some() { + assert_eq!(objects_at(&d, p, opt, scope), want, "{context}"); + } + for found in 1..want.len() { + let start = want[..found].to_vec(); + assert_eq!(objects_at_repeated_after(&d, p, opt, scope, start.clone()), want, "{context}, {found} found"); + assert_eq!(objects_at_repeated_after_by_list(&d, p, opt, scope, start), want, "{context}, {found} found"); + } + compared += usize::from(!want.is_empty()); + } + } + } + assert!(compared > 500, "only {compared} non-empty lists compared"); +} + +/// Times Select Behind in an isolated group of 200 and of 1,000 overlapping squares, the set lookup +/// against the ordered-list lookup, alternating the two in one process: +/// `cargo test --release -p vectorcraft-doc --lib -- --ignored --nocapture select_behind_isolation_timing`. +#[test] +#[ignore = "a timing, not a check"] +fn select_behind_isolation_timing() { + /// This thread's CPU time in nanoseconds on Linux; the elapsed time since `start` elsewhere. + fn clock(start: std::time::Instant) -> u128 { + let cpu = std::fs::read_to_string("/proc/thread-self/schedstat").ok(); + cpu.and_then(|s| s.split_whitespace().next()?.parse().ok()).unwrap_or_else(|| start.elapsed().as_nanos()) + } + type Lookup = fn(&Document, Point, HitOptions, Option, Vec) -> Vec; + let start = std::time::Instant::now(); + println!("clock: {}", if std::fs::metadata("/proc/thread-self/schedstat").is_ok() { "thread CPU time" } else { "wall clock" }); + let p = Point::new(47.5, 25.0); + for count in [200, 1_000] { + let (d, g, ids) = isolated_stack(count); + let opt = HitOptions { scope: Some(g), ..HitOptions::default() }; + assert_eq!(objects_at_repeated_after(&d, p, opt, Some(g), vec![]), ids); + assert_eq!(objects_at_repeated_after_by_list(&d, p, opt, Some(g), vec![]), ids); + // The time per call of `f`: batches of calls double until one takes at least 100 ms. + let per_call = |f: Lookup| { + let mut calls = 1u32; + loop { + let t = clock(start); + for _ in 0..calls { + std::hint::black_box(f(&d, std::hint::black_box(p), opt, Some(g), vec![])); + } + let spent = clock(start) - t; + if spent >= 100_000_000 || calls >= 1 << 20 { + return (spent as f64 / f64::from(calls), calls); + } + calls *= 2; + } + }; + let (mut old, mut new) = (vec![], vec![]); + for _ in 0..7 { + old.push(per_call(objects_at_repeated_after_by_list)); + new.push(per_call(objects_at_repeated_after)); + } + old.sort_by(|a, b| a.0.total_cmp(&b.0)); + new.sort_by(|a, b| a.0.total_cmp(&b.0)); + let (o, n) = (old[3], new[3]); + println!( + "{count} objects: list lookup {:.2} ms per call ({} calls), set lookup {:.2} ms per call ({} calls), median of 7 runs", + o.0 / 1e6, + o.1, + n.0 / 1e6, + n.1 + ); + } +} + /// Select Behind finds a symbol instance by its symbol's art, as a click does: art from /// (100, 60) to (140, 80), outside the 20 × 20 square around the origin, drawn where it lies by /// one instance and 100 pt lower by an instance in a group. 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/inline.rs b/crates/doc/src/inline.rs index 86c26e14f4..b22f6cbfc7 100644 --- a/crates/doc/src/inline.rs +++ b/crates/doc/src/inline.rs @@ -117,6 +117,29 @@ impl Document { /// symbol that shows itself inline ([`Self::inline_art_bounds`]) is shown as an empty slot. /// Returns the ids of the texts in the layers that changed. pub fn resolve_inline_art_with(&mut self, layout: &mut dyn FnMut(&mut TextObject)) -> Vec { + self.resolve_inline_art_since(None, layout).changed + } + + /// [`Self::resolve_inline_art_with`], given `last`: a document an earlier pass left resolved, + /// with the bounds that pass measured ([`InlinePass::measured`]). When this document has the + /// same symbols, graph designs, pattern tiles and foreign data (`unknown`, which holds the + /// symbols' natural sizes and 9-slice guides) as `last`, and each symbol name measured then + /// still measures the same, the type in the layer trees that are the same nodes as `last`'s + /// already has these bounds: only the other layer trees are checked, in the same order, and + /// the document and the ids returned are those of the full pass. Otherwise, or without `last`, + /// the full pass runs. + pub fn resolve_inline_art_since(&mut self, last: Option<(&Document, &InlineMeasured)>, layout: &mut dyn FnMut(&mut TextObject)) -> InlinePass { + if let Some((last, kept)) = last + && self.same_inline_inputs(last, kept) + { + let measured = Measured(RefCell::new(kept.0.clone())); + let mut changed = vec![]; + let layers = resolve_kids(Some(&last.layers), &self.layers, &|n| measured.get(n, || self.inline_art_bounds(n)), layout, &mut changed); + for (i, layer) in layers { + self.layers[i] = layer; + } + return InlinePass { changed, measured: InlineMeasured(measured.0.into_inner()), partial: true }; + } let mut out = vec![]; let mut unused = vec![]; let graph = InlineGraph::of(self); @@ -147,10 +170,44 @@ impl Document { } } } - out + InlinePass { changed: out, measured: InlineMeasured(measured.0.into_inner()), partial: false } + } + + /// Whether the type in this document's layer trees that are the same nodes as `last`'s already + /// has the bounds a full pass would give it (see [`Self::resolve_inline_art_since`]). + fn same_inline_inputs(&self, last: &Document, kept: &InlineMeasured) -> bool { + self.symbols.len() == last.symbols.len() + && self.symbols.iter().zip(&last.symbols).all(|(a, b)| a.name == b.name && Arc::ptr_eq(&a.art, &b.art)) + && self.graph_designs.len() == last.graph_designs.len() + && self.graph_designs.iter().zip(&last.graph_designs).all(|(a, b)| a.name == b.name && Arc::ptr_eq(&a.art, &b.art)) + && self.patterns.len() == last.patterns.len() + && self + .patterns + .iter() + .zip(&last.patterns) + .all(|(a, b)| a.name == b.name && a.art.len() == b.art.len() && a.art.iter().zip(&b.art).all(|(x, y)| Arc::ptr_eq(x, y))) + && crate::Shared::ptr_eq(&self.unknown, &last.unknown) + && kept.0.iter().all(|(name, b)| self.inline_art_bounds(name) == *b) } } +/// What a pass of [`Document::resolve_inline_art_since`] did. +#[derive(Debug)] +pub struct InlinePass { + /// The ids of the texts in the layers that changed, in the order the full pass finds them. + pub changed: Vec, + /// The bounds the pass gave the inline graphics of each symbol name, for the next pass. + pub measured: InlineMeasured, + /// Whether only the layer trees that differ from the last resolved document's were checked. + pub partial: bool, +} + +/// The art bounds a pass of [`Document::resolve_inline_art_since`] gave the inline graphics of each +/// symbol name it was asked for. A pass that checks only some layer trees keeps the names the +/// pass before it measured, so the names of all the type in the document stay listed. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct InlineMeasured(HashMap>); + /// Whether `t` has inline graphics whose bounds differ from what `bounds` gives their symbols. fn stale_by(t: &TextObject, bounds: &dyn Fn(&str) -> Option) -> bool { t.runs.iter().filter_map(|r| r.inline.as_ref()).any(|a| a.bounds != bounds(&a.symbol)) @@ -185,6 +242,22 @@ fn resolve_tree( layout: &mut dyn FnMut(&mut TextObject), changed: &mut Vec, ) -> bool { + resolve_since(None, n, bounds, layout, changed) +} + +/// [`resolve_tree`], given `old`: the node `n` was before an edit, in a document whose type was +/// resolved with the same `bounds`. The opacity mask art and children of `n` that are the same +/// nodes as `old`'s are skipped: their type already has these bounds. Without `old`, every node +/// of the tree is visited. +fn resolve_since( + old: Option<&Node>, + n: &mut Arc, + bounds: &dyn Fn(&str) -> Option, + layout: &mut dyn FnMut(&mut TextObject), + changed: &mut Vec, +) -> bool { + #[cfg(test)] + tests::VISITS.with(|v| v.set(v.get() + 1)); let mut copied = false; if matches!(&n.kind, NodeKind::Text(t) if stale_by(t, bounds)) { let node = Arc::make_mut(n); @@ -196,17 +269,17 @@ fn resolve_tree( } copied = true; } + let old_mask = old.and_then(|o| o.extras().mask.as_deref()).map(|m| &m.art); let mask = n.extras().mask.as_deref().and_then(|m| { - let mut art = m.art.clone(); - resolve_tree(&mut art, bounds, layout, changed).then_some(art) - }); - let mut kids = vec![]; - for (i, c) in n.children().into_iter().flatten().enumerate() { - let mut c = c.clone(); - if resolve_tree(&mut c, bounds, layout, changed) { - kids.push((i, c)); + if old_mask.is_some_and(|o| Arc::ptr_eq(o, &m.art)) { + return None; } - } + let mut art = m.art.clone(); + let old_art = old_mask.filter(|o| o.id == art.id).map(|o| &**o); + resolve_since(old_art, &mut art, bounds, layout, changed).then_some(art) + }); + let old_kids = old.map(|o| o.children().map_or(&[][..], Vec::as_slice)); + let kids = resolve_kids(old_kids, n.children().map_or(&[][..], Vec::as_slice), bounds, layout, changed); if mask.is_none() && kids.is_empty() { return copied; } @@ -224,6 +297,35 @@ fn resolve_tree( true } +/// Resolves the trees `kids` as [`resolve_since`] does, each with the node of `old` (the same list +/// before an edit) that has its id, found at the same position or else by id, and skips those that +/// are the same nodes as theirs. Without `old`, every tree is visited. Returns the position and new +/// node of each tree that changed. +fn resolve_kids( + old: Option<&[Arc]>, + kids: &[Arc], + bounds: &dyn Fn(&str) -> Option, + layout: &mut dyn FnMut(&mut TextObject), + changed: &mut Vec, +) -> Vec<(usize, Arc)> { + let mut by_id: Option>> = None; + let mut out = vec![]; + for (i, c) in kids.iter().enumerate() { + let o = old.and_then(|old| match old.get(i) { + Some(b) if b.id == c.id => Some(b), + _ => by_id.get_or_insert_with(|| old.iter().map(|b| (b.id, b)).collect()).get(&c.id).copied(), + }); + if o.is_some_and(|o| Arc::ptr_eq(o, c)) { + continue; + } + let mut c = c.clone(); + if resolve_since(o.map(|o| &**o), &mut c, bounds, layout, changed) { + out.push((i, c)); + } + } + out +} + /// The art bounds of each symbol, measured once in a pass of [`Document::resolve_inline_art_with`]. /// A symbol is first asked for after its own type is resolved (the pass goes in /// [`InlineGraph::order`]), so its measurement stays current for the rest of the pass. @@ -436,6 +538,112 @@ impl std::fmt::Debug for InlineCycles { mod tests { use super::*; + thread_local! { + /// How many nodes [`resolve_since`] has visited on this thread. + pub(super) static VISITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + } + + /// The nodes visited since the last call. + fn visits() -> usize { + VISITS.with(|v| v.replace(0)) + } + + /// A copy of `d` resolved by the full pass, and the ids that pass returns. + fn fully_resolved(d: &Document) -> (Document, Vec) { + let mut full = d.clone(); + let ids = full.resolve_inline_art_with(&mut |_| {}); + (full, ids) + } + + /// The children of the layer at `i`, for an edit. + fn layer_kids(d: &mut Document, i: usize) -> &mut Vec> { + match Arc::make_mut(&mut d.layers[i]).children_mut() { + Some(kids) => kids, + None => panic!("layer {i} is a group"), + } + } + + /// 50 groups of 20 squares, symbol `S`, type showing `S` in the first group, and type showing + /// `S` in the opacity mask of the second. + fn many_groups() -> Document { + let mut d = Document::new(500.0, 500.0); + let square = stroked(&mut d, Rect::new(0.0, 0.0, 10.0, 10.0)); + symbol(&mut d, "S", vec![square]); + for _ in 0..50 { + let kids = (0..20).map(|_| stroked(&mut d, Rect::new(0.0, 0.0, 5.0, 5.0))).collect(); + let group = Node::group(d.alloc_id(), kids); + d.layers.push(Arc::new(group)); + } + let t = showing(&mut d, "S"); + layer_kids(&mut d, 0).push(t); + let masked = showing(&mut d, "S"); + Arc::make_mut(&mut d.layers[1]).extras_mut().mask = Some(Box::new(crate::OpacityMask::new((*masked).clone(), true))); + d + } + + #[test] + fn a_pass_after_an_edit_checks_only_the_trees_the_edit_changed() { + let mut d = many_groups(); + let first = d.resolve_inline_art_since(None, &mut |_| {}); + assert!(!first.partial); + assert_eq!(first.changed.len(), 2); + let last = d.clone(); + visits(); + let _ = fully_resolved(&d); + let full_visits = visits(); + // The edit moves a square in the 31st group, adds type showing S to the 41st, and gives the + // second group's opacity mask new type: its 20 squares stay the same nodes. + let moved = stroked(&mut d, Rect::new(1.0, 1.0, 6.0, 6.0)); + layer_kids(&mut d, 30)[5] = moved; + let added = showing(&mut d, "S"); + layer_kids(&mut d, 40).push(added.clone()); + let mask_type = showing(&mut d, "S"); + if let Some(m) = Arc::make_mut(&mut d.layers[1]).extras_if_any().and_then(|e| e.mask.as_deref_mut()) { + m.art = mask_type.clone(); + } + let (want, ids) = fully_resolved(&d); + assert_eq!(ids, [mask_type.id, added.id]); + visits(); + let pass = d.resolve_inline_art_since(Some((&last, &first.measured)), &mut |_| {}); + let partial_visits = visits(); + assert!(pass.partial); + assert_eq!(pass.changed, ids); + assert_eq!(d, want); + // The three changed groups, the mask's new type, the moved square and the added type. + assert_eq!(partial_visits, 6); + assert!(full_visits > 1000, "{full_visits}"); + assert_eq!(pass.measured, first.measured); + } + + #[test] + fn changed_symbols_or_symbol_sizes_take_the_full_pass() { + let mut d = many_groups(); + let mut pass = d.resolve_inline_art_since(None, &mut |_| {}); + // A natural size for S, its art unchanged. + let last = d.clone(); + d.unknown.insert(SYMBOL_SIZES.into(), serde_json::json!({ "S": [40.0, 20.0] })); + let (want, ids) = fully_resolved(&d); + assert_eq!(ids.len(), 2); + pass = d.resolve_inline_art_since(Some((&last, &pass.measured)), &mut |_| {}); + assert!(!pass.partial); + assert_eq!((&d, &pass.changed), (&want, &ids)); + // New art for S. + let last = d.clone(); + let bigger = stroked(&mut d, Rect::new(0.0, 0.0, 30.0, 30.0)); + d.symbols[0].art = Arc::new(Node::group(d.alloc_id(), vec![bigger])); + let (want, ids) = fully_resolved(&d); + assert_eq!(ids.len(), 2); + pass = d.resolve_inline_art_since(Some((&last, &pass.measured)), &mut |_| {}); + assert!(!pass.partial); + assert_eq!((&d, &pass.changed), (&want, &ids)); + // A measurement that no longer holds, with the same symbols and foreign data. + let last = d.clone(); + let stale = InlineMeasured(HashMap::from([("S".to_owned(), Some(Rect::new(0.0, 0.0, 1.0, 1.0)))])); + pass = d.resolve_inline_art_since(Some((&last, &stale)), &mut |_| {}); + assert!(!pass.partial); + assert!(pass.changed.is_empty()); + } + /// The position of each node in `order`. fn positions(order: &[usize]) -> Vec { let mut at = vec![0; order.len()]; diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 18974db32a..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; @@ -31,7 +31,7 @@ mod symbol_nine_slice; pub mod symbol_overrides; mod symbol_pixel_aligned; mod symbol_registration; -pub use inline::{SYMBOL_HALF, SYMBOL_SIZES}; +pub use inline::{InlineMeasured, InlinePass, SYMBOL_HALF, SYMBOL_SIZES}; pub use shared::Shared; pub use symbol_export_type::{SYMBOL_EXPORT_TYPE, SymbolExportType}; pub use symbol_nine_slice::{ @@ -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/live.rs b/crates/doc/src/live.rs index 28fd1dc632..337634db2e 100644 --- a/crates/doc/src/live.rs +++ b/crates/doc/src/live.rs @@ -66,7 +66,8 @@ pub use expand::{ use mesh::grid_eval; pub use mesh::{Coons, GradientMesh, MeshAppearance, MeshPiece, MeshPoint, MeshQuad, default_fidelity, grid_points, nodes_bounds}; pub use warp::{ - WARP_NET, WarpNet, WarpStyle, fit_piece, map_nonlinear, map_nonlinear_within, map_smooth_within, pieces, uses_net, warp_point, warp_version, + WARP_NET, WarpNet, WarpStyle, fit_piece, map_handles_within, map_nonlinear, map_nonlinear_within, map_smooth_within, pieces, uses_net, + warp_point, warp_version, }; #[cfg(test)] diff --git a/crates/doc/src/live/warp.rs b/crates/doc/src/live/warp.rs index dd48e8ef65..a921c7d2ff 100644 --- a/crates/doc/src/live/warp.rs +++ b/crates/doc/src/live/warp.rs @@ -508,6 +508,17 @@ pub fn map_smooth_within(path: &PathData, max_piece: f64, max: usize, f: impl Fn map_pieces_within(path, max_piece, max, &f, |p, h| mapped_handle(&f, p, h)) } +/// [`map_nonlinear_within`] with `handle(point, handle)` supplying each mapped handle position. +pub fn map_handles_within( + path: &PathData, + max_piece: f64, + max: usize, + f: impl Fn(Point) -> Point, + handle: impl Fn(Point, Point) -> Point, +) -> PathData { + map_pieces_within(path, max_piece, max, &f, handle) +} + /// Handle `h` of point `p` mapped through `f`: `f(p)` plus `f`'s derivative at `p` along `h - p` /// (a central difference), so the image curve leaves `f(p)` the way `f` takes the curve. fn mapped_handle(f: &impl Fn(Point) -> Point, p: Point, h: Point) -> Point { @@ -553,7 +564,8 @@ fn map_pieces_within(path: &PathData, max_piece: f64, max: usize, f: &impl Fn(Po let c = seg_cubic(sp, i); let k = pieces(poly_len(&c), max_piece, MAX_PIECES); for j in 0..k { - let sub = c.subsegment((j as f64 / k as f64)..((j + 1) as f64 / k as f64)); + // Evaluating an unchanged curve can overflow even when its control points are finite. + let sub = if k == 1 { c } else { c.subsegment((j as f64 / k as f64)..((j + 1) as f64 / k as f64)) }; if let Some(last) = res.last_mut() { last.h_out = handle(sub.p0, sub.p1); } @@ -613,3 +625,53 @@ pub(super) fn resample(poly: &[Point], m: usize) -> Vec { } out } + +#[cfg(test)] +mod handle_tests { + use super::*; + + #[test] + fn an_unsplit_curve_keeps_its_finite_control_points() { + let start = Point::new(1e308, 0.0); + let end = Point::new(1.03e308, 0.0); + let path = PathData::new(vec![SubPath::new( + vec![Anchor::with_handles(start, start, Point::new(1.01e308, 1.0)), Anchor::with_handles(end, Point::new(1.02e308, 1.0), end)], + false, + )]); + assert_eq!(map_handles_within(&path, 1.0, 2, |p| p, |_, h| h), path); + } + + #[test] + fn rounded_samples_preserve_a_smooth_interior_join() { + let center = Point::new(1e16, 0.0); + let path = PathData::new(vec![SubPath::new( + vec![ + Anchor::corner(center + vectorcraft_geom::kurbo::Vec2::new(-18.0, 0.0)), + Anchor::with_handles( + center, + center + vectorcraft_geom::kurbo::Vec2::new(-6.0, 0.0), + center + vectorcraft_geom::kurbo::Vec2::new(6.0, 0.0), + ), + Anchor::corner(center + vectorcraft_geom::kurbo::Vec2::new(18.0, 0.0)), + ], + false, + )]); + let mapped = map_smooth_within(&path, f64::INFINITY, 3, |p| Point::new(p.x, p.y + (p.x - center.x).powi(2) * 0.1)); + let join = &mapped.subpaths[0].anchors[1]; + let incoming = join.p - join.h_in; + let outgoing = join.h_out - join.p; + assert!(incoming.cross(outgoing).abs() < 1e-9, "{incoming:?} {outgoing:?}"); + assert!(incoming.dot(outgoing) > 0.0); + } + + #[test] + fn a_midpoint_rounded_to_an_endpoint_keeps_the_handle_direction() { + for x in [1e16, 1e16 + 2.0, -1e16] { + for offset in [-6.0, -2.0, 2.0, 6.0] { + let p = Point::new(x, 0.0); + let h = Point::new(x + offset, 0.0); + assert_eq!(mapped_handle(&|point| point, p, h), h); + } + } + } +} 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/node/live_shape.rs b/crates/doc/src/node/live_shape.rs index 9ddc4e1bb6..a384836442 100644 --- a/crates/doc/src/node/live_shape.rs +++ b/crates/doc/src/node/live_shape.rs @@ -179,6 +179,48 @@ impl LiveShape { *xf = Affine::rotate_about((now - angle).to_radians(), centre) * *xf; } } + /// A line's length in the document, from its first end to its second. None for other shapes. + pub fn line_length(&self) -> Option { + let LiveShape::Line { a, b } = self else { return None }; + Some((*b - *a).hypot()) + } + /// A line's angle: the counterclockwise degrees in [0, 360) from the page's horizontal to the + /// direction from its first end to its second (the Rotate field's sense). 0 for a line whose + /// ends meet. None for other shapes. + pub fn line_angle(&self) -> Option { + let LiveShape::Line { a, b } = self else { return None }; + if a == b { + return Some(0.0); + } + // No −0° or 360° from rounding: a line drawn left to right reads 0°. + let a = (-self.angle_deg()).rem_euclid(360.0); + Some(if a > 360.0 - 1e-9 { 0.0 } else { a + 0.0 }) + } + /// Make a line `len` long (0 or more), keeping its first end in place and its direction, or + /// pointing it to the right when its ends meet. + pub fn set_line_length(&mut self, len: f64) { + let LiveShape::Line { a, b } = self else { return }; + if !len.is_finite() || len < 0.0 { + return; + } + let now = (*b - *a).hypot(); + *b = if now > 0.0 { *a + (*b - *a) * (len / now) } else { Point::new(a.x + len, a.y) }; + } + /// Turn a line about its midpoint to `angle` (degrees, as [`LiveShape::line_angle`]). A line + /// whose ends meet stays as it is. + pub fn set_line_angle(&mut self, angle: f64) { + let LiveShape::Line { a, b } = self else { return }; + let half = (*b - *a).hypot() / 2.0; + if !angle.is_finite() || half <= 0.0 { + return; + } + let mid = a.midpoint(*b); + let t = angle.to_radians(); + // The page's y axis points down, so a counterclockwise angle goes up the page. + let (dx, dy) = (half * t.cos(), -half * t.sin()); + *a = Point::new(mid.x - dx, mid.y - dy); + *b = Point::new(mid.x + dx, mid.y + dy); + } /// Make a polygon's sides equal (Make Sides Equal): drop the uneven scale and the shear from /// `xf`, keeping its centre, angle, reflection and [`LiveShape::polygon_radius`]. pub fn make_sides_equal(&mut self) { diff --git a/crates/doc/src/node/ops.rs b/crates/doc/src/node/ops.rs index a616080bce..42978c81b0 100644 --- a/crates/doc/src/node/ops.rs +++ b/crates/doc/src/node/ops.rs @@ -216,8 +216,10 @@ impl Node { /// path give it ([`crate::hit::set_clip_region`]). An image's box takes in /// the shapes its own fills and strokes paint ([`crate::hit::set_image_paint`]). Groups, layers /// without a clipping mask and Intertwine groups take in their members' boxes, grown by their - /// own strokes. Symbol instances are measured as in [`Node::visual_bounds`]. A blend's box - /// takes in where its spine can put its keys and steps. + /// own strokes. Symbol instances are measured as in [`Node::visual_bounds`], taking in the + /// shapes their art paints with the geometry effects of their own fill or stroke + /// ([`crate::hit::set_image_paint`]). A blend's box takes in where its spine can put its keys + /// and steps. pub fn reach_bounds(&self) -> Option { self.reach(None) } @@ -254,14 +256,8 @@ impl Node { .map(|b| b.inflate(o, o)) } NodeKind::Intertwine { children } => children.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.reach(symbols))), - // The frame and each shape the image's own fills and strokes paint, a stroke's grown by - // the farthest it can reach from its shape. - NodeKind::Image(_) => { - crate::hit::image_paint(symbols.map(SymbolBoxes::document), self).iter().fold(self.geometric(symbols), |acc, (bp, _, item)| { - let o = if let crate::AppearanceItem::Stroke(s) = item { s.reach() } else { 0.0 }; - vectorcraft_geom::union_opt(acc, (!bp.elements().is_empty()).then(|| bp.bounding_box().inflate(o, o))) - }) - } + // The frame and each shape the image's own fills and strokes paint. + NodeKind::Image(_) => self.with_own_paint(self.geometric(symbols), symbols), // Keys and steps placed on a spine, turned to it with Align to Path, can reach past the // keys and the spine. NodeKind::Blend { children, spec } => { @@ -272,13 +268,15 @@ impl Node { NodeKind::Layer { children, clip: true, .. } | NodeKind::Group { children, clip: true } => { vectorcraft_geom::union_opt(self.visual(symbols), children.first().and_then(|c| crate::hit::reshaped_clip_box(c))) } - // The live geometry effects of the clipping paths in the art can draw it past its box. + // The live geometry effects of the clipping paths in the art can draw it past its box, + // and the box takes in each shape the art paints with the geometry effects of the + // instance's own fill or stroke. NodeKind::SymbolInstance { symbol, xf } => { let Some((s, art, region)) = symbols.and_then(|s| { let a = s.art(symbol)?; Some((s, a, a.reshaped?)) }) else { - return self.visual(symbols); + return self.with_own_paint(self.visual(symbols), symbols); }; let map = s.document().symbol_slice_map_of(symbol, art.geometric, *xf); let placed = if moves_only(*xf) && map.is_none() { @@ -294,12 +292,22 @@ impl Node { map.map_or_else(|| xf.transform_rect_bbox(all), |m| m.placement_bounds(all)).inflate(grow, grow) }; let o = self.appearance.outset(); - vectorcraft_geom::union_opt(self.visual(symbols), self.projected(Some(placed)).map(|b| b.inflate(o, o))) + self.with_own_paint(vectorcraft_geom::union_opt(self.visual(symbols), self.projected(Some(placed)).map(|b| b.inflate(o, o))), symbols) } _ => self.visual(symbols), } } + /// `start` grown by each shape the node's own fills and strokes paint + /// ([`crate::hit::set_image_paint`]), a stroke's grown by the farthest it can reach from its + /// shape. + fn with_own_paint(&self, start: Option, symbols: Option<&SymbolBoxes>) -> Option { + crate::hit::image_paint(symbols.map(SymbolBoxes::document), self).iter().fold(start, |acc, (bp, _, item)| { + let o = if let crate::AppearanceItem::Stroke(s) = item { s.reach() } else { 0.0 }; + vectorcraft_geom::union_opt(acc, (!bp.elements().is_empty()).then(|| bp.bounding_box().inflate(o, o))) + }) + } + /// Geometric bounds (no stroke), recursively. Clip groups are bounded by their clip path. A /// symbol instance is measured as its transform applied to the 20 × 20 square around the origin /// that symbols made in the app keep their art in ([`Node::geometric_bounds_with`] measures 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/swatches.rs b/crates/doc/src/swatches.rs index 9c25427846..0ee84dc32c 100644 --- a/crates/doc/src/swatches.rs +++ b/crates/doc/src/swatches.rs @@ -187,8 +187,9 @@ impl Document { /// [`Document::map_solid_paints`] limited to the art in the subtrees of `ids` (each paint /// visited once even when an id is inside another). pub fn map_solid_paints_in(&mut self, ids: &[NodeId], f: &mut LinkFn) -> usize { + let listed: HashSet = ids.iter().copied().collect(); let roots: Vec = - ids.iter().copied().filter(|id| !self.ancestry(*id).is_some_and(|a| a[..a.len() - 1].iter().any(|p| ids.contains(p)))).collect(); + ids.iter().copied().filter(|id| !self.ancestry(*id).is_some_and(|a| a[..a.len() - 1].iter().any(|p| listed.contains(p)))).collect(); let mut n = 0; let mut g = relink(f); for id in roots { @@ -844,6 +845,77 @@ mod tests { assert_eq!(colors, [(Color::rgb(1.0, 0.0, 0.0), None)]); } + /// [`Document::map_solid_paints_in`] with each ancestor searched for in `ids` rather than looked up in a set. + fn map_solid_paints_in_by_search(d: &mut Document, ids: &[NodeId], f: &mut LinkFn) -> usize { + let roots: Vec = + ids.iter().copied().filter(|id| !d.ancestry(*id).is_some_and(|a| a[..a.len() - 1].iter().any(|p| ids.contains(p)))).collect(); + let mut n = 0; + let mut g = relink(f); + for id in roots { + let Some(node) = d.node(id) else { continue }; + if let Some((new, count)) = map_node(node, &mut g) + && let Some(slot) = d.node_mut(id) + { + *slot = new; + n += count; + } + } + n + } + + #[test] + fn mapping_within_ids_matches_a_search_of_the_ids() { + // Two layers: the first holds group `outer` (group `inner` with two rectangles, and a + // rectangle) and a rectangle; the second holds a rectangle. Each rectangle has its own color. + let mut d = Document::new(100.0, 100.0); + let first = d.layers[0].id; + let second = d.alloc_id(); + d.insert(None, usize::MAX, Node::layer(second, "Second", crate::LayerColor::Preset(1))).unwrap(); + let rect = |d: &mut Document, i: u8| { + let id = d.alloc_id(); + let r = shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)); + let color = Color::rgb(f32::from(i) / 8.0, 0.0, 0.0); + (id, Arc::new(Node::path(id, r, Appearance::basic(Paint::solid(color), Paint::solid(color), 1.0)))) + }; + let (r1, n1) = rect(&mut d, 1); + let (r2, n2) = rect(&mut d, 2); + let (r3, n3) = rect(&mut d, 3); + let (r4, n4) = rect(&mut d, 4); + let (r5, n5) = rect(&mut d, 5); + let (inner, outer) = (d.alloc_id(), d.alloc_id()); + let outer_node = Node::group(outer, vec![Arc::new(Node::group(inner, vec![n1, n2])), n3]); + d.insert(Some(first), usize::MAX, outer_node).unwrap(); + d.insert(Some(first), usize::MAX, Arc::unwrap_or_clone(n4)).unwrap(); + d.insert(Some(second), usize::MAX, Arc::unwrap_or_clone(n5)).unwrap(); + let missing = NodeId(u64::MAX); + let all = [first, second, outer, inner, r1, r2, r3, r4, r5, missing]; + // Every list of up to three of them: nested ids in both orders, duplicates, a missing id and none. + let mut lists: Vec> = vec![vec![]]; + let mut shorter: Vec> = vec![vec![]]; + for _ in 0..3 { + shorter = shorter.iter().flat_map(|l| all.map(|id| [l.as_slice(), &[id]].concat())).collect(); + lists.extend(shorter.iter().cloned()); + } + assert_eq!(lists.len(), 1 + 10 + 100 + 1000); + for ids in &lists { + // A callback that changes every paint it visits, so a paint visited twice counts twice. + let run = |map: &dyn Fn(&mut Document, &[NodeId], &mut LinkFn) -> usize| { + let mut d = d.clone(); + let mut visits = vec![]; + let n = map(&mut d, ids, &mut |c, s, t| { + visits.push((*c, s.clone(), *t)); + *s = Some(format!("{}", visits.len())); + *t *= 0.5; + true + }); + (n, visits, d.layers) + }; + let by_set = run(&|d, ids, f| d.map_solid_paints_in(ids, f)); + let by_search = run(&|d, ids, f| map_solid_paints_in_by_search(d, ids, f)); + assert_eq!(by_set, by_search, "{ids:?}"); + } + } + /// The colors [`node_colors`] visits, in its order, by a [`Node::walk`] that reads the whole subtree. fn full_walk(n: &Node, f: &mut dyn FnMut(&Color, Option<&str>)) { n.walk(&mut |m| { 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/bake.rs b/crates/effects/src/bake.rs index 274f9bdcc4..36418ac913 100644 --- a/crates/effects/src/bake.rs +++ b/crates/effects/src/bake.rs @@ -28,7 +28,8 @@ use vectorcraft_geom::{Affine, FillRule, PathData, Rect, Vec2}; use crate::distort::{transform_move, transform_offsets}; use crate::group::{has_own_paint, paints}; use crate::reshape::{ - as_art, clipping_text_outline, dressed, geometry_effects, glyph_outlines, outline_nested_text, paint_type_clip, reshape_leaves, + as_art, clip_region_path, clipping_text_outline, dressed, geometry_effects, glyph_outlines, knockout_inside, outline_nested_text, + paint_type_clip, reshape_leaves, }; use crate::{ GeomContext, adjust_in_document, apply_geometry_carrying, crop_marks_art, evaluate_container, has_adjustment, has_crop_marks, has_geometry, @@ -502,13 +503,7 @@ fn clip_group_with_type_clip(d: &mut Document, n: &Node) -> Option { { return None; } - let (bp, rule) = crate::clip_outline(first)?; - let mut clip = Node::path(first.id, PathData::from_bezpath(&bp), Appearance::default()); - if let NodeKind::Path { rule: r, clipping, .. } = &mut clip.kind { - (*r, *clipping) = (rule, true); - } - clip.name = first.name.clone(); - clip.visible = first.visible; + let clip = clip_region_path(first)?; let paint = first.clip_paint(); // The type's fills and strokes as art: baked with the type's id, as the renderer draws them, // then given ids of their own. @@ -532,7 +527,8 @@ fn clip_group_with_type_clip(d: &mut Document, n: &Node) -> Option { return Some(m); }; // `n` keeps its id, name and transparency, and holds the clip group and the strokes over it. - let inner = Node::new(d.alloc_id(), NodeKind::Group { children: members, clip: true }); + let mut inner = Node::new(d.alloc_id(), NodeKind::Group { children: members, clip: true }); + knockout_inside(&mut m, &mut inner); match &mut m.kind { NodeKind::Group { children, clip } | NodeKind::Layer { children, clip, .. } => { *children = vec![Arc::new(inner), stroke]; diff --git a/crates/effects/src/bake/tests.rs b/crates/effects/src/bake/tests.rs index deb705752f..70bdc7731b 100644 --- a/crates/effects/src/bake/tests.rs +++ b/crates/effects/src/bake/tests.rs @@ -776,7 +776,7 @@ fn type_outlined_next_to_type_that_stays_type_keeps_its_look() { let mut shadowed = type_node(55); shadowed.opacity = 0.5; shadowed.appearance.effects.push(fx("stylize.dropShadow", json!({}))); - // Type that clips a group is outlined as the plain outlines it clips by. + // Type that clips a group is outlined as a plain path of the region it clips by. let square = Node::path(NodeId(57), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::default_art()); let clip = Node::new(NodeId(58), NodeKind::Group { children: vec![Arc::new(type_node(56)), Arc::new(square)], clip: true }); g.children_mut().unwrap().extend([Arc::new(shadowed), Arc::new(clip)]); @@ -789,7 +789,10 @@ fn type_outlined_next_to_type_that_stays_type_keeps_its_look() { let b = o.geometric_bounds().unwrap(); assert!(b.x0 < 30.0 && b.x1 > 220.0, "{b:?}"); let clipped = d.node(NodeId(58)).and_then(|n| n.children()).and_then(|c| c.first()).unwrap(); - assert!(matches!(clipped.kind, NodeKind::Group { .. }) && clipped.opacity == 1.0, "{clipped:?}"); + assert!(matches!(clipped.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) && clipped.opacity == 1.0, "{clipped:?}"); + // The region is copied with the type. + let b = clipped.geometric_bounds().unwrap(); + assert!(b.x0 < 30.0 && b.x1 > 220.0, "{b:?}"); } #[test] diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index ea727b804c..568aa583b1 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( @@ -277,7 +277,13 @@ pub fn effect_catalog() -> Vec { "{h: amount (10), v: amount (10), relative: bool (true: % of size), anchors: bool (true), in: bool (true), out: bool (true), seed: int (0)}", json!({"h": 10.0, "v": 10.0, "relative": true, "anchors": true, "in": true, "out": true, "seed": 0}), ), - g("distort.twist", "Twist…", DT, "{angle: deg (-3600..3600, 10)}", json!({"angle": 10.0})), + g( + "distort.twist", + "Twist…", + DT, + "{angle: deg (-3600..3600, 10)} Outer-circle anchors stay fixed; their handles follow the inward tangent.", + json!({"angle": 10.0}), + ), g( "distort.zigZag", "Zig Zag…", diff --git a/crates/effects/src/distort.rs b/crates/effects/src/distort.rs index 7a03a2f3aa..3fa1f3d152 100644 --- a/crates/effects/src/distort.rs +++ b/crates/effects/src/distort.rs @@ -6,7 +6,7 @@ use vectorcraft_geom::{Affine, Anchor, ParamCurve, PathData, Point, Rect, SubPat use vectorcraft_pathops::addons::pathtools::insert_at; use crate::util::{ - catmull_rom, fit_piece, flag, map_nonlinear_within, map_smooth_within, mean_size, noise, normal_at, num, pieces, seed, seg_cubic, smooth_points, + catmull_rom, fit_piece, flag, map_handles_within, map_nonlinear_within, mean_size, noise, normal_at, num, pieces, seed, seg_cubic, smooth_points, }; fn diag(b: Rect) -> f64 { @@ -328,7 +328,7 @@ pub fn tweak(path: &PathData, b: Rect, p: &Value) -> PathData { /// Twist: rotation that is strongest at the centre and fades to zero at the bounding circle, /// clockwise on the page for a positive `angle`, making at most `max` anchors. Its handles follow -/// the rotation's derivative ([`map_smooth_within`]), so the pieces join without kinks (#7069). +/// the rotation's directional derivative, including each side of the outer circle. pub fn twist(path: &PathData, b: Rect, angle: f64, max: usize) -> PathData { let ang = angle.clamp(-3600.0, 3600.0).to_radians(); if ang == 0.0 { @@ -336,16 +336,46 @@ pub fn twist(path: &PathData, b: Rect, angle: f64, max: usize) -> PathData { } let c = b.center(); let r = diag(b) / 2.0; + let half = Vec2::new(b.width() * 0.5, b.height() * 0.5); + let boundary = move |p: Point, length: f64| { + if length == r { + return true; + } + if !r.is_finite() || (length - r).abs() > 8.0 * f64::EPSILON * r { + return false; + } + // A bounds-relative distance identifies boundary points affected by center rounding. + (Vec2::new(p.x - b.x0, p.y - b.y0) - half).hypot() == r + }; let f = move |q: Point| { let d = q - c; - let t = (1.0 - d.hypot() / r).max(0.0); + let length = d.hypot(); + let t = (1.0 - length / r).max(0.0); // y runs down, so a positive turn is clockwise on the page. let a = ang * t; + if a == 0.0 { + return q; + } let (s, co) = a.sin_cos(); c + Vec2::new(d.x * co - d.y * s, d.x * s + d.y * co) }; let piece = (r / 8.0).min(r / (1.0 + ang.abs() * 2.0)); - map_smooth_within(path, piece, max, f) + map_handles_within(path, piece, max, f, |p, h| { + let v = h - p; + if !v.hypot().is_finite() { + return f(p); + } + let d = p - c; + let length = d.hypot(); + let radial = if length > 0.0 { (d / length).dot(v) } else { 0.0 }; + // The clamped rotation has different inward and outward derivatives at the circle. + let inside = if boundary(p, length) { radial < 0.0 } else { length < r }; + let gradient = if inside { -ang / r * radial } else { 0.0 }; + let tangent = if gradient == 0.0 { v } else { v + Vec2::new(-d.y, d.x) * gradient }; + let a = ang * (1.0 - length / r).max(0.0); + let (s, co) = a.sin_cos(); + f(p) + Vec2::new(tangent.x * co - tangent.y * s, tangent.x * s + tangent.y * co) + }) } const ZIGZAG_ARCLEN_ACCURACY: f64 = 1e-4; diff --git a/crates/effects/src/group.rs b/crates/effects/src/group.rs index 9531159e01..e52a85e125 100644 --- a/crates/effects/src/group.rs +++ b/crates/effects/src/group.rs @@ -110,13 +110,15 @@ fn leaves(doc: Option<&Document>, n: &Node, hook: Option, nodes: &S // Every path of the outline art, at any depth, is drawn inside the object's opacity // and blend mode. A symbol's art comes with the live objects and the instances of // other symbols inside it given as their art, and the type inside it outlined, so the - // art has nothing left for `hook` to give. + // art has nothing left for `hook` to give. Its fills and strokes carry the geometry + // effects of the instance's active fill and stroke, as the canvas draws them. if let Some(h) = hook && let Some(art) = h(n) { let art = match &n.kind { NodeKind::SymbolInstance { symbol, .. } if nodes.charge(&art) => { - let mut art = crate::reshape::symbol_art_with(&art, h, nodes, symbol); + let mut art = instance_art(doc, &art, h, nodes, symbol); + crate::reshape::add_instance_row_effects(doc, n, &mut art); crate::reshape::outline_nested_text(doc, &mut art, false); transparency_into_members(&mut art); art @@ -134,6 +136,19 @@ fn leaves(doc: Option<&Document>, n: &Node, hook: Option, nodes: &S } } +/// `art`, the art `hook` gave an instance of the symbol named `symbol`, with the live objects and +/// the instances of other symbols inside it given as their art +/// ([`crate::reshape::symbol_art_with`]). The art of each of those instances carries the geometry +/// effects of its own active fill and stroke ([`crate::reshape::add_instance_row_effects`]). +fn instance_art(doc: Option<&Document>, art: &Node, hook: OutlineHook, nodes: &SymbolNodes, symbol: &str) -> Node { + let drawn = |m: &Node| { + let mut a = hook(m)?; + crate::reshape::add_instance_row_effects(doc, m, &mut a); + Some(a) + }; + crate::reshape::symbol_art_with(art, &drawn, nodes, symbol) +} + /// `l`, a path drawn inside `n`: its opacity multiplied by `n`'s, and `n`'s blend mode when it is /// not Normal. fn within(l: &mut Node, n: &Node) { @@ -221,13 +236,15 @@ fn reshaped_art(doc: Option<&Document>, n: &Node, hook: Option, nod } }, // A symbol instance with a warp: its symbol's art placed by the instance, with the type - // inside it outlined, reshaped as one piece, as the renderer draws it. + // inside it outlined, reshaped as one piece, as the renderer draws it. The fills and strokes + // of the art then carry the geometry effects of the instance's active fill and stroke. NodeKind::SymbolInstance { symbol, .. } if !fx.is_empty() => { let h = hook?; let art = h(n).filter(|art| nodes.charge(art))?; - let mut art = crate::reshape::symbol_art_with(&art, h, nodes, symbol); + let mut art = instance_art(doc, &art, h, nodes, symbol); crate::reshape::outline_nested_text(doc, &mut art, false); members_as_drawn(doc, &mut art); + crate::reshape::add_instance_row_effects(doc, n, &mut art); let carry = crate::reshape::reshape_leaves_carrying(&mut art, &fx, &n.appearance.effects, doc); // The art's own fills and strokes follow the effects as its members do. if carry.moves(&art.appearance) { @@ -703,6 +720,11 @@ pub fn member_shapes(doc: Option<&Document>, n: &Node) -> Vec<(PathData, FillRul } } fn members(doc: Option<&Document>, n: &Node, out: &mut Vec<(PathData, FillRule)>) { + // A clip group whose clipping type's strokes paint around it is outlined as that clip + // group: the strokes outside the clip add nothing. + if let Some(inner) = crate::reshape::painted_clip_inner(n) { + return members(doc, inner, out); + } // A clip group shows its members only inside its clipping path: its outline is that // region, not the clipped members' own shapes, which may reach far outside it (#7289). if n.clips() { @@ -884,14 +906,18 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option { m.appearance.effects = crate::raster::without_geometry(&m.appearance.effects); m.appearance.effects.retain(|e| !is_pathfinder(&e.id)); if paint { - let shapes = member_shapes(doc, &m); - let bounds = m.geometric_bounds(); + // A clip group whose clipping type paints strokes is now a group of a clip group and those + // strokes ([`crate::reshape::paint_type_clip`]): its own fills and strokes paint inside + // that clip group. Such groups among the members are measured as their clip groups. + let wrapped = n.clips() && crate::reshape::painted_clip_inner(&m).is_some(); + let (shapes, bounds) = (member_shapes(doc, &m), crate::reshape::clip_bounds(&m)); let art = |items: &[AppearanceItem]| -> Vec> { items.iter().filter_map(|i| item_art(n.id, i, &shapes, bounds)).map(Arc::new).collect() }; let (below, above) = m.appearance.split_contents(); let (below, above) = (art(below), art(above)); - let at = usize::from(m.clips()); - if let Some(ch) = m.children_mut() { + let at = usize::from(wrapped || m.clips()); + let target = if wrapped { m.children_mut().and_then(|ch| ch.first_mut()).map(Arc::make_mut) } else { Some(&mut m) }; + if let Some(ch) = target.and_then(Node::children_mut) { let at = at.min(ch.len()); ch.splice(at..at, below); ch.extend(above); 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/reshape.rs b/crates/effects/src/reshape.rs index 50ecc6b549..00bf169b93 100644 --- a/crates/effects/src/reshape.rs +++ b/crates/effects/src/reshape.rs @@ -387,7 +387,7 @@ fn row_effects_of(fx: &[Effect]) -> Vec { /// of a symbol whose art (in `doc`) holds an instance of `n`'s symbol, at any depth, keeps its /// appearance, so the effects never pass round a symbol that holds itself. Without `doc`, no /// instance in the art takes them. -fn add_instance_row_effects(doc: Option<&Document>, n: &Node, art: &mut Node) { +pub(crate) fn add_instance_row_effects(doc: Option<&Document>, n: &Node, art: &mut Node) { let NodeKind::SymbolInstance { symbol, .. } = &n.kind else { return }; let fill = active_fill(n).map_or(vec![], |f| row_effects_of(&f.effects)); let stroke = active_stroke(n).map_or(vec![], |s| row_effects_of(&s.effects)); @@ -613,32 +613,101 @@ fn traced_opaque_area(bytes: &[u8]) -> Traced { /// rule and the fill or stroke that paints it: the paths (or compound paths) that [`reshape`] /// makes along its frame or, for those whose first effect is Outline Object, along the outline of /// its opaque area ([`opaque_area`]), with each fill's or stroke's geometry effects applied as the -/// renderer applies them. Empty for anything but an image with such fills or strokes. The swatches -/// and patterns that live-effect plug-ins painting their pieces name are looked up in `doc`, and -/// the image's pixels in `doc` when the image does not hold them. +/// renderer applies them. For a symbol instance whose active fill or stroke has a visible geometry +/// effect ([`has_item_geometry`]), the shapes that the fills and strokes of the art it draws paint +/// ([`instance_paint`]). Empty for anything else. The swatches and patterns that live-effect +/// plug-ins painting their pieces name are looked up in `doc`, and the image's pixels in `doc` when +/// the image does not hold them. pub fn image_paint(doc: Option<&Document>, n: &Node) -> Vec<(BezPath, FillRule, AppearanceItem)> { - if !matches!(n.kind, NodeKind::Image(_)) || !has_item_geometry(n) { - return vec![]; - } - let Some(art) = reshape(doc, n, None) else { return vec![] }; let mut out = vec![]; - art.walk(&mut |c| { - let (NodeKind::Path { rule, .. } | NodeKind::Compound { rule, .. }) = &c.kind else { return }; - let Some(g) = c.stroke_path() else { return }; - let ctx = GeomContext { doc, ..GeomContext::of(c) }; - for item in c.appearance.items.iter().filter(|i| crate::paints(i)) { - let fx = item.effects(); - let shape = if crate::has_geometry(fx) && !g.elements().is_empty() { - crate::apply_geometry_bez(fx, &g, g.bounding_box(), &ctx.item(item)) - } else { - g.clone() - }; - out.push((shape, *rule, item.clone())); - } - }); + if matches!(n.kind, NodeKind::SymbolInstance { .. }) { + let mut budget = SYMBOL_ART_MAX_NODES; + instance_paint(doc, n, 1, &mut budget, &mut out); + return out; + } + if !matches!(n.kind, NodeKind::Image(_)) || !has_item_geometry(n) { + return out; + } + let Some(art) = reshape(doc, n, None) else { return out }; + art.walk(&mut |c| push_painted(doc, c, &mut out)); out } +/// The shapes that the fills and strokes of path or compound path `c` paint, each with the +/// geometry effects of that fill or stroke applied ([`image_paint`]); nothing for other objects. +fn push_painted(doc: Option<&Document>, c: &Node, out: &mut Vec<(BezPath, FillRule, AppearanceItem)>) { + let (NodeKind::Path { rule, .. } | NodeKind::Compound { rule, .. }) = &c.kind else { return }; + let Some(g) = c.stroke_path() else { return }; + let ctx = GeomContext { doc, ..GeomContext::of(c) }; + for item in c.appearance.items.iter().filter(|i| crate::paints(i)) { + let fx = item.effects(); + let shape = if crate::has_geometry(fx) && !g.elements().is_empty() { + crate::apply_geometry_bez(fx, &g, g.bounding_box(), &ctx.item(item)) + } else { + g.clone() + }; + out.push((shape, *rule, item.clone())); + } +} + +/// The shapes that symbol instance `n`, `depth` instances deep, paints with the geometry effects of +/// its active fill and stroke ([`has_item_geometry`]): the paths of the art [`reshape`] makes of it, +/// each with its own geometry effects and those of each fill and stroke applied +/// ([`crate::bake_type_appearance`], [`push_painted`]), the paths that the own fills and strokes of +/// the groups and layers in the art paint and the results of their Pathfinder effects +/// ([`crate::evaluate_container`]), the shapes that the own fills and strokes of the images in the +/// art paint ([`image_paint`]), and the instances in that art that took those effects, in turn. +/// Hidden objects, clipping paths, guides, the members of clip groups and the original shapes of +/// Shaper groups add nothing, and neither does an instance more than +/// [`vectorcraft_doc::depth::MAX_DEPTH`] deep or whose symbol's art would take the objects measured +/// so far past `budget`. +fn instance_paint(doc: Option<&Document>, n: &Node, depth: usize, budget: &mut u64, out: &mut Vec<(BezPath, FillRule, AppearanceItem)>) { + let NodeKind::SymbolInstance { symbol, .. } = &n.kind else { return }; + if depth >= vectorcraft_doc::depth::MAX_DEPTH || !has_item_geometry(n) { + return; + } + let Some(sym) = doc.and_then(|d| d.symbols.iter().find(|s| s.name == *symbol)) else { return }; + let count = sym.art.count() as u64; + if count > *budget { + return; + } + *budget -= count; + let Some(art) = reshape(doc, n, Some(&vectorcraft_doc::symbol_overrides::dynamic_art(&sym.art, n))) else { return }; + painted_in(doc, &art, depth, budget, out); +} + +/// [`instance_paint`] of the objects in `n`, art of an instance `depth` instances deep. +fn painted_in(doc: Option<&Document>, n: &Node, depth: usize, budget: &mut u64, out: &mut Vec<(BezPath, FillRule, AppearanceItem)>) { + if !n.visible { + return; + } + match &n.kind { + NodeKind::Path { clipping: false, guide: false, .. } | NodeKind::Compound { .. } => match crate::bake_type_appearance(doc, n) { + // One path for each fill and stroke, its effects applied. + Some(pieces) => painted_in(doc, &pieces, depth, budget, out), + None => push_painted(doc, n, out), + }, + NodeKind::Path { .. } => {} + NodeKind::Image(_) => out.extend(image_paint(doc, n)), + NodeKind::SymbolInstance { .. } => instance_paint(doc, n, depth + 1, budget, out), + _ if n.clips() => {} + _ => { + // A Pathfinder effect paints its result, not the members it combines. + let evaluated = (crate::has_container_appearance(n) || crate::has_pathfinder(n)).then(|| crate::evaluate_container(doc, n)).flatten(); + let g = evaluated.as_ref().unwrap_or(n); + if g.clips() { + return; + } + // A Shaper group's first member holds its original shapes, which are not drawn. The + // group's own fills and strokes can be painted before it, so it is found by its id. + let sources = n.extras().shaper.is_some().then(|| n.children().and_then(|c| c.first()).map(|c| c.id)).flatten(); + for c in g.children().into_iter().flatten().filter(|c| Some(c.id) != sources) { + painted_in(doc, c, depth, budget, out); + } + } + } +} + /// The glyph outlines of type `t` in text space with its underline and strikethrough bars: one /// path per run, and all of them as one. pub(crate) fn glyph_outlines(t: &vectorcraft_doc::TextObject) -> (Vec, kurbo::BezPath) { @@ -954,6 +1023,74 @@ pub(crate) fn clipping_text_outline(t: &Node) -> Option { Some(Node { visible: t.visible, ..o }) } +/// Clipping path `clip` of a clip group as a clipping path of the region it clips to +/// ([`crate::clip_outline`]), with its id, name and visibility. For type that paints, the geometry +/// effects of its fills and strokes reshape what they paint and leave that region as it is. +/// `None` when it has nothing to clip by. +pub(crate) fn clip_region_path(clip: &Node) -> Option { + let (bp, rule) = crate::clip_outline(clip)?; + let mut p = Node::path(clip.id, PathData::from_bezpath(&bp), Appearance::default()); + if let NodeKind::Path { rule: r, clipping, .. } = &mut p.kind { + (*r, *clipping) = (rule, true); + } + p.name = clip.name.clone(); + p.visible = clip.visible; + Some(p) +} + +/// Knockout Group for clip group `m` turned into a group around `inner`, a clip group of its +/// members, and its clipping path's strokes: `inner` takes `m`'s setting, so the clipped art knocks +/// out as before, and `m` is set Off so the strokes paint over it, as the renderer draws them. A +/// neutral `m` stays neutral, so both take the setting of the groups around them. +pub(crate) fn knockout_inside(m: &mut Node, inner: &mut Node) { + inner.knockout = m.knockout; + if m.knockout != vectorcraft_doc::Knockout::Neutral { + m.knockout = vectorcraft_doc::Knockout::Off; + } +} + +/// The clip group in `n` when `n` is a group or layer that [`paint_type_clip`] made of a clip +/// group and its clipping type's strokes: a group that does not clip whose first member is a clip +/// group with `n`'s id and whose second member has the id of that clip group's clipping path. The +/// clip group's region is what `n` stands for, as the clip group it was made from: the strokes +/// paint outside it and add nothing to its outline ([`crate::member_shapes`]) or its bounds +/// ([`clip_bounds`]). +pub(crate) fn painted_clip_inner(n: &Node) -> Option<&Node> { + if n.clips() || !matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) { + return None; + } + let [inner, stroke, ..] = n.children()?.as_slice() else { return None }; + let clip = inner.children()?.first()?; + (inner.clips() && inner.id == n.id && stroke.id == clip.id && !stroke.clips()).then_some(&**inner) +} + +/// The geometric bounds of `n` ([`Node::geometric_bounds`]) with each group or layer in it that +/// [`painted_clip_inner`] finds measured as its clip group, so the strokes of a clipping type +/// outside the clip do not widen them. +pub(crate) fn clip_bounds(n: &Node) -> Option { + fn holds(n: &Node) -> bool { + painted_clip_inner(n).is_some() || n.children().into_iter().flatten().any(|c| holds(c)) + } + fn unwrap(n: &mut Node) { + if let Some(inner) = painted_clip_inner(n) { + let mut inner = inner.clone(); + inner.visible = n.visible; + *n = inner; + } + for c in n.children_mut().into_iter().flatten() { + if holds(c) { + unwrap(Arc::make_mut(c)); + } + } + } + if !holds(n) { + return n.geometric_bounds(); + } + let mut probe = n.clone(); + unwrap(&mut probe); + probe.geometric_bounds() +} + /// Replace type anywhere inside `n` by its outlines, as art that keeps the type's look /// ([`as_art`]). Type in a clip group's clipping path (all of `n` when `clipping` is set) becomes /// its outlines with its visibility and effects ([`clipping_text_outline`]), and its fills and @@ -981,32 +1118,41 @@ pub(crate) fn outline_nested_text(doc: Option<&Document>, n: &mut Node, clipping } /// When `n` is a clip group or clipping layer whose clipping path is type that paints -/// ([`Node::clip_paint`]), make it the art the canvas draws for it: the type's outlines clip -/// ([`clipping_text_outline`]), its fills as art ([`as_art`]) paint behind the clipped art inside -/// the clip, and its strokes as art paint over it, outside the clip, in a group that `n` becomes -/// (keeping its id, name and transparency) with the clip group inside. The other members stay as -/// they are. Hidden type paints nothing. +/// ([`Node::clip_paint`]), make it the art the canvas draws for it: a path of the region the type +/// clips to clips ([`clip_region_path`]), its fills as art ([`as_art`]) paint behind the clipped +/// art inside the clip, and its strokes as art paint over it, outside the clip. Each part is the +/// type's art with only those fills or strokes, their own geometry effects applied. With strokes, +/// `n` becomes a group (keeping its id, name, visibility and transparency) that holds a clip group +/// of the clipping path, the fills and the other members, with `n`'s id, then the strokes; a +/// clipping layer keeps its ruler guides last. [`knockout_inside`] sets the Knockout Group of both, +/// and [`painted_clip_inner`] finds that clip group. The other members stay as they are. Hidden +/// type paints nothing. pub(crate) fn paint_type_clip(doc: Option<&Document>, n: &mut Node) { - let Some((first, rest)) = n.children().and_then(|ch| ch.split_first()) else { return }; - if !n.clips() || !matches!(first.kind, NodeKind::Text(_)) || !first.visible { + let Some(first) = n.children().and_then(|ch| ch.first()).filter(|_| n.clips()) else { return }; + if !matches!(first.kind, NodeKind::Text(_)) || !first.visible { return; } let paint = first.clip_paint(); if paint.fill.is_none() && paint.stroke.is_none() { return; } - let Some(clip) = clipping_text_outline(first) else { return }; + let Some(clip) = clip_region_path(first) else { return }; let art = |part: Option| part.and_then(|p| as_art(doc, &p, None)).map(Arc::new); - let members: Vec> = std::iter::once(Arc::new(clip)).chain(art(paint.fill)).chain(rest.iter().cloned()).collect(); - let stroke = art(paint.stroke); + let (fill, stroke) = (art(paint.fill), art(paint.stroke)); let id = n.id; - match (&mut n.kind, stroke) { - (NodeKind::Group { children, .. } | NodeKind::Layer { children, .. }, None) => *children = members, - (NodeKind::Group { children, clip } | NodeKind::Layer { children, clip, .. }, Some(stroke)) => { - *children = vec![Arc::new(Node::new(id, NodeKind::Group { children: members, clip: true })), stroke]; - *clip = false; - } - _ => {} + let Some(ch) = n.children_mut() else { return }; + let Some(slot) = ch.first_mut() else { return }; + *slot = Arc::new(clip); + if let Some(fill) = fill { + ch.insert(1, fill); + } + let Some(stroke) = stroke else { return }; + let guides = ch.split_off(Node::guide_run_start(ch)); + let mut inner = Node::new(id, NodeKind::Group { children: std::mem::take(ch), clip: true }); + knockout_inside(n, &mut inner); + if let NodeKind::Group { children, clip } | NodeKind::Layer { children, clip, .. } = &mut n.kind { + *children = [Arc::new(inner), stroke].into_iter().chain(guides).collect(); + *clip = false; } } @@ -1822,7 +1968,7 @@ impl Step<'_> { if !groups.is_empty() { carry_groups(art, groups, after, &|from, to| crate::Carry::of(&e.id, params, bounds, from, to, seed)); } - let drawn = warped.as_deref().map_or_else(|| art.geometric_bounds(), |w| w.bounds(art)); + let drawn = warped.as_deref().map_or_else(|| clip_bounds(art), |w| w.bounds(art)); let whole = (follows && !held).then(|| crate::Carry::of(&e.id, params, bounds, Some(bounds), drawn, seed)); Ran { kept: !kept_ids.is_empty(), took, masks, short, whole } } @@ -3247,6 +3393,9 @@ fn group_marks( NodeKind::Image(_) => (images.map_or_else(|| n.geometric_bounds(), |w| w.image_bounds(n)), false), NodeKind::Group { children, clip } | NodeKind::Layer { children, clip, .. } if !n.extras().type_outlines => { let layer = matches!(n.kind, NodeKind::Layer { .. }); + // A clip group whose clipping type's strokes paint around it is measured as that clip + // group: the strokes outside the clip do not widen it ([`clip_bounds`]). + let clip = *clip || painted_clip_inner(n).is_some(); let skip = children.len().saturating_sub(n.editing_children().len()); let (mut bounds, mut held) = (None, false); for (i, c) in children.iter().enumerate() { @@ -3257,7 +3406,7 @@ fn group_marks( } at.pop(); // Only members measured in the bounds hold the group's gradients in place. - let counts = if *clip { i == 0 } else { i >= skip && (c.visible || !layer) }; + let counts = if clip { i == 0 } else { i >= skip && (c.visible || !layer) }; if counts { bounds = vectorcraft_geom::union_opt(bounds, b); held |= h; @@ -3473,16 +3622,17 @@ impl WarpedImages { /// The geometric bounds of `art` as it draws after the effects so far: each image this table /// lists measured by the pieces the warps and moves it took would cut it into, when the art - /// has room for them ([`cut_warped_images`]). + /// has room for them ([`cut_warped_images`]). The strokes of clipping type outside its clip + /// are left out ([`clip_bounds`]). pub(crate) fn bounds(&self, art: &Node) -> Option { if self.images.is_empty() || !self.fits(art, crate::distort::MAX_COPY_OBJECTS) { - return art.geometric_bounds(); + return clip_bounds(art); } // The pieces the images would be cut into now: each group of pieces is shown or hidden as // its image is, and hidden objects are left out of a layer's bounds. let mut probe = art.clone(); restore_warped_images(&mut probe, self, true); - probe.geometric_bounds() + clip_bounds(&probe) } /// The geometric bounds of image `n`: when this table lists it, measured by the pieces the diff --git a/crates/effects/src/revolve.rs b/crates/effects/src/revolve.rs index acd6cf7c94..43e60a0022 100644 --- a/crates/effects/src/revolve.rs +++ b/crates/effects/src/revolve.rs @@ -6,7 +6,7 @@ use serde_json::Value; use vectorcraft_doc::color::{Color, Paint}; use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, FillLayer, Node, NodeId, NodeKind}; use vectorcraft_geom::{FillRule, PathData, PathEl, Point, Rect, Vec2}; -use vectorcraft_three_d::{Edge, Revolve, SolidFaces}; +use vectorcraft_three_d::{Edge, PlanarFace, Revolve, SolidFaces}; use crate::solids::wireframe::{WireFace, wireframe_params}; use crate::solids::{ @@ -168,7 +168,7 @@ pub(crate) fn validate_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value) // With no member to carry them, the graphics' art must still fit its limits. None => { crate::solids::graphics::validate_symbols(doc, p)?; - crate::solids::graphics::validate_surface_symbols(doc, p)?; + crate::solids::graphics::validate_surface_symbols(doc, p, PlanarFace::Front)?; } } } @@ -201,10 +201,10 @@ fn check_graphics(doc: Option<&Document>, id: &str, path: &PathData, b: Rect, op let graphics = crate::solids::mapped_graphics(p); let Some(doc) = doc.filter(|_| id == REVOLVE && !graphics.is_empty()) else { return Ok(()) }; crate::solids::graphics::validate_symbols(doc, p)?; - crate::solids::graphics::validate_surface_symbols(doc, p)?; + crate::solids::graphics::validate_surface_symbols(doc, p, PlanarFace::Front)?; let faces = vectorcraft_three_d::revolve(path, b, options)?; let mut used = *copies; - match crate::solids::graphics::surface_parts(Some(doc), NodeId(0), &graphics, &faces, &|_, c| Paint::solid(c), &mut used) { + match crate::solids::graphics::surface_parts(Some(doc), NodeId(0), (&graphics, PlanarFace::Front), &faces, &|_, c| Paint::solid(c), &mut used) { Some(_) => { *copies = used; Ok(()) @@ -523,7 +523,7 @@ fn surface( let mut parts = if graphics.is_empty() { vec![] } else { - match crate::solids::graphics::surface_parts(doc, n.id, &graphics, &faces, &shade, &mut used) { + match crate::solids::graphics::surface_parts(doc, n.id, (&graphics, PlanarFace::Front), &faces, &shade, &mut used) { Some(parts) => { copies.graphics = used; parts diff --git a/crates/effects/src/revolve/tests_graphics.rs b/crates/effects/src/revolve/tests_graphics.rs index e21a88a26e..efe469e039 100644 --- a/crates/effects/src/revolve/tests_graphics.rs +++ b/crates/effects/src/revolve/tests_graphics.rs @@ -520,7 +520,8 @@ fn the_copies_of_a_graphics_paint_have_a_budget_of_their_own() { let faces = vectorcraft_three_d::revolve(path, path.bounds().unwrap(), options_of(REVOLVE, &p)).unwrap(); let parts_of = |symbol: &str, copies: &mut usize| { let graphics = crate::solids::mapped_graphics(&json!({"graphics": [{"symbol": symbol}]})); - crate::solids::graphics::surface_parts(Some(&d), NodeId(0), &graphics, &faces, &|_, c| Paint::solid(c), copies).map(|p| p.concat().len()) + crate::solids::graphics::surface_parts(Some(&d), NodeId(0), (&graphics, PlanarFace::Front), &faces, &|_, c| Paint::solid(c), copies) + .map(|p| p.concat().len()) }; // Each opaque part copies the paint into its fill and its seam stroke; a part with // transparent stops takes no seam stroke and copies it once. diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index 2f8d0bf7bd..2bda4dc126 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,14 @@ 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. + // on the back cap and on Extrude & Bevel's side are dropped. if (to == ROTATE || to == crate::REVOLVE) && let Some(Value::Array(list)) = out.get_mut(GRAPHICS) { - list.retain(|g| g.get("face").and_then(Value::as_str) != Some(PlanarFace::Back.id())); + list.retain(|g| { + let face = g.get("face").and_then(Value::as_str); + face != Some(PlanarFace::Back.id()) && face != Some(PlanarFace::Side.id()) + }); } Value::Object(out) } @@ -177,6 +180,7 @@ pub fn extrude_options(p: &Value) -> Extrude { both_sides: flag(p, "bevelBothSides", false), }), hidden: false, + map_surface: false, } } @@ -253,6 +257,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. @@ -339,7 +393,8 @@ fn validate_solid_for(doc: Option<&Document>, n: &Node, id: &str, p: &Value, at: reshape_members(n, before, &mut shapes); 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)?; - return check_solids(id, p, &shapes); + check_solids(id, p, &shapes)?; + return check_side_graphics(doc, n, id, p, &shapes); } let (path, rule) = object_profile(n, label)?; let anchors = || format!("{label} requires a shape with at least two anchors"); @@ -356,7 +411,8 @@ fn validate_solid_for(doc: Option<&Document>, n: &Node, id: &str, p: &Value, at: let b = path.bounds().ok_or_else(anchors)?; let shapes = [Profile { path, rule, items, opacity: 1.0, scopes: vec![] }]; check_profiles(id, p, &shapes, b)?; - check_solids(id, p, &shapes) + check_solids(id, p, &shapes)?; + check_side_graphics(doc, n, id, p, &shapes) } /// Does 3D effect `id` with parameters `p` cast a shadow: is it Extrude & Bevel, Inflate or Rotate @@ -370,6 +426,30 @@ fn visible(item: &AppearanceItem, member: f32) -> bool { paint_of(item, member).1 > 0.0 } +/// 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, &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 @@ -414,7 +494,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) + let built = built_solids_cast(id, p, &parts, bounds, MAX_OBJECT_FACES, true, None) .map(|r| r.map(|solid| solid.and_then(|(_, faces)| faces))) .collect::, String>>()?; cast_built(id, p, shapes, built).map(|_| ()) @@ -688,6 +768,30 @@ fn surface(n: &Node, facets: Vec, paint: &Paint, opacity: f32, blend: Ble group } +/// `surface`, a plain group of one face for each facet ([`surface`]), with each face followed by +/// the parts of the side's graphics that `parts` holds for its facet ([`graphics::surface_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_side_parts(id: NodeId, mut surface: Node, parts: Vec>>) -> Node { + if parts.iter().all(Vec::is_empty) { + return surface; + } + let NodeKind::Group { children, clip: false } = &mut surface.kind else { return surface }; + if children.len() != parts.len() { + return surface; + } + for (child, extra) in children.iter_mut().zip(parts) { + if extra.is_empty() { + continue; + } + let mut list = Vec::with_capacity(extra.len() + 1); + list.push(child.clone()); + list.extend(extra); + *child = Arc::new(Node::group(id, list)); + } + surface +} + /// The bounds of every facet of `facets` together (`Rect::ZERO` when none has any). pub(crate) fn facets_bounds(facets: &[Facet]) -> Rect { facets.iter().filter_map(|f| f.path().bounds()).reduce(|a, c| a.union(c)).unwrap_or(Rect::ZERO) @@ -802,7 +906,7 @@ fn built_solids<'a>( bounds: Rect, limit: usize, ) -> impl Iterator>, String>> + 'a { - built_solids_cast(id, p, parts, bounds, limit, false).map(|r| r.map(|s| s.map(|(f, _)| f))) + built_solids_cast(id, p, parts, bounds, limit, 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. @@ -813,7 +917,9 @@ type CastingSolid = (Vec, Option); 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`]). +/// is cast from, from the same build ([`SolidFaces`]). 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`]). fn built_solids_cast<'a>( id: &'a str, p: &'a Value, @@ -821,6 +927,7 @@ fn built_solids_cast<'a>( bounds: Rect, limit: usize, cast: 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>> { @@ -834,7 +941,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; } @@ -846,6 +953,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 { @@ -1098,6 +1206,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)?)) @@ -1776,6 +1886,12 @@ fn seen_ends(f: &[Facet]) -> impl Iterator { /// solid built also keeps the faces its shadow is cast from, from the same build, in the order the /// solids are built ([`cast_built`]); `None` for a stroke's solid left out of the art. fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile], cast: bool) -> Option { + surfaces_with(doc, n, fx, shapes, cast, &mut false) +} + +/// [`surfaces_for`], setting `side_dropped` when 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, fx: &Effect, shapes: &[Profile], cast: bool, side_dropped: &mut bool) -> Option { let b = union_bounds(shapes)?; let p = crate::merged_params(&fx.id, &fx.params); let classic = fx.id == CLASSIC_EXTRUDE || fx.id == CLASSIC_ROTATE; @@ -1818,9 +1934,13 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile 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![]; - for ((item, opacity, _, _, scopes, member), f) in parts.iter().zip(built_solids_cast(&fx.id, &p, &parts, bounds, MAX_OBJECT_FACES, cast)) { + let made = built_solids_cast(&fx.id, &p, &parts, bounds, MAX_OBJECT_FACES, cast, 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)) => { @@ -1830,8 +1950,12 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile solids.push((item, *opacity, *scopes, f, *member)); built.push(faces); } - // A stroke's outline past the limits is left out; the fill's solid still draws. - Ok(None) => built.push(None), + // A stroke's outline past the limits is left out; the fill's solid still draws, and + // the side's graphics on that outline are not drawn. + Ok(None) => { + built.push(None); + *side_dropped |= 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; // commands validate the same evaluator and report its errors. @@ -1915,6 +2039,9 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile // ([`in_one_order`], [`underlaid_surface`]). 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 side_graphics = carrier.map(|_| mapped_graphics(&p)).unwrap_or_default(); + // The paint copies of the side's graphics, apart from those of the surfaces, as on Revolve. + let mut graphic_copies = 0usize; let surfaces: Vec = solids .into_iter() .map(|(item, member, scopes, f, shape)| { @@ -1922,10 +2049,22 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile 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 carrier's pieces draw the parts of the side's graphics that fall on them; past + // the graphics' limits the solid draws without them. + let parts = if side_graphics.is_empty() || !f.iter().any(|f| f.surface.is_some()) { + vec![] + } else { + 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); + *side_dropped |= parts.is_none(); + parts.unwrap_or_default() + }; + let drawn = parts.iter().any(|p| !p.is_empty()); let art = if classic { classic::surface(n, f, &paint, opacity, blend, &p) } else { - surface(n, f, &paint, opacity, blend, colored, split && shared.get(shape).copied().unwrap_or(false)) + let faces = drawn || (split && shared.get(shape).copied().unwrap_or(false)); + with_side_parts(n.id, surface(n, f, &paint, opacity, blend, colored, faces), parts) }; (depths, art, scopes, ends) }) @@ -2239,8 +2378,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())?; @@ -2264,6 +2413,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; } @@ -2289,10 +2444,19 @@ fn frame_of(doc: Option<&Document>, n: &Node, item: Option, pick: &Pick<' let plane = vectorcraft_three_d::plane_face_map(b, view); return Some(graphics::GraphicFrame::new(b, plane, None)); } - let (_, bounds) = solid_parts(&shapes, b); + let (parts, bounds) = solid_parts(&shapes, b); 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 7ef2fe4e28..bf4a71ace7 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. use std::sync::Arc; @@ -110,7 +113,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) { @@ -139,7 +142,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 @@ -148,8 +151,8 @@ impl MappedGraphic { } } -/// The 3D effects that take graphics: Extrude & Bevel (its caps), Rotate (the plane) and Revolve -/// (its swept side). +/// The 3D effects that take graphics: Extrude & Bevel (its caps and its side), Rotate (the plane) +/// and Revolve (its swept side). pub fn takes_graphics(id: &str) -> bool { id == super::EXTRUDE || id == super::ROTATE || id == crate::REVOLVE } @@ -165,7 +168,7 @@ pub fn mapped_graphics(p: &Value) -> Vec { /// Are the graphics in parameters `p` of 3D effect `id` valid? Only Extrude & Bevel, Rotate and /// Revolve take graphics; a plane has only a front, and Revolve's graphics go on its side, named -/// the front. +/// 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(()), @@ -183,10 +186,10 @@ 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()); } } @@ -598,14 +601,14 @@ struct Unrolled { place: Affine, } -/// The areas of `graphics` (those of the front: Revolve's side) placed on the unrolled side -/// surface, 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]) -> Option> { +/// The areas of `graphics` on `face` (the front, for Revolve's side, or Extrude & Bevel's side) +/// placed on the unrolled side surface, 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; - for g in graphics.iter().filter(|g| g.face == PlanarFace::Front) { + for g in graphics.iter().filter(|g| g.face == face) { let Some(symbol) = doc.symbols.iter().find(|s| s.name == g.symbol) else { continue }; let Ok(art) = pieces_of(doc, symbol) else { continue }; let Some(bounds) = art.iter().filter_map(|p| p.path.bounds()).reduce(|a, b| a.union(b)) else { continue }; @@ -682,38 +685,96 @@ fn straight_pieces(path: &BezPath, points: &mut usize) -> Option> (*points <= MAX_ELEMENTS).then_some(polygons) } -/// Do the graphics in Revolve parameters `p` fit the limits with the symbols of `doc`? Their art, -/// cut into straight pieces on the side surface, may take up to [`MAX_ELEMENTS`] points together. -pub(crate) fn validate_surface_symbols(doc: &Document, p: &Value) -> Result<(), String> { +/// Do the graphics on `face` in parameters `p` (the front of Revolve, Extrude & Bevel's side) fit +/// the limits with the symbols of `doc`? Their art, cut into straight pieces on the side 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.is_empty() || unrolled(doc, &list).is_some() { + if !list.iter().any(|g| g.face == face) || unrolled(doc, &list, face).is_some() { return Ok(()); } Err("The graphics are too complex: simplify the symbols' art".into()) } -/// The parts of `graphics` that fall on each of `faces`, a revolved 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 swept side 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 -/// [`MAX_ELEMENTS`] points together before they are cut at the faces, [`MAX_SURFACE_POINTS`] -/// after, [`MAX_SURFACE_CUTS`] points cut, or when the copies of their paints in the parts take -/// `copies`, the bytes of the copies of the object's graphics so far, past Revolve's budget for -/// them: commands refuse such graphics, and a loaded file draws the surface without them. -pub(crate) fn surface_parts( +/// A face of a side surface that graphics are drawn on ([`surface_parts`]): a face of Revolve's +/// swept side, or a piece of Extrude & Bevel's walls and bevels. +pub(crate) trait SurfaceFace { + /// Where the face lies on the side unrolled, when it is a face of the side that shows its + /// outside to the viewer. + fn outer_cell(&self) -> Option<&vectorcraft_three_d::SurfaceCell>; + /// The outline the face's parts are cut to, when it is not the polygon of its cell's corners: + /// its curved outline, when its edges along an end are curved, or the outline of a piece cut + /// from a larger face. + fn curved(&self) -> Option>; + fn rgb_light(&self) -> Option; + fn light(&self) -> [f64; 3]; + fn outline_path(&self) -> PathData; +} + +impl SurfaceFace for vectorcraft_three_d::Face { + fn outer_cell(&self) -> Option<&vectorcraft_three_d::SurfaceCell> { + self.surface.as_ref().filter(|c| c.outward && !self.cap) + } + fn curved(&self) -> Option> { + self.outline.as_ref().map(std::borrow::Cow::Borrowed) + } + fn rgb_light(&self) -> Option { + self.rgb_gradient + } + fn light(&self) -> [f64; 3] { + self.illumination + } + fn outline_path(&self) -> PathData { + self.path() + } +} + +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(std::borrow::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(|| std::borrow::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() + } +} + +/// The parts of the graphics on `face` of `graphics` (the front of Revolve, Extrude & Bevel's side) +/// that fall on each of `faces`, a side 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 side 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 [`MAX_ELEMENTS`] points together before they are +/// cut at the faces, [`MAX_SURFACE_POINTS`] after, [`MAX_SURFACE_CUTS`] points cut, or when the +/// copies of their paints in the parts take `copies`, the bytes of the copies of the object's +/// graphics so far, past Revolve's budget for them: commands refuse such graphics, and a loaded +/// file draws the surface without them. +pub(crate) fn surface_parts( doc: Option<&Document>, id: NodeId, - graphics: &[MappedGraphic], - faces: &[vectorcraft_three_d::Face], - shade: &dyn Fn(&vectorcraft_three_d::Face, vectorcraft_doc::color::Color) -> Paint, + (graphics, face): (&[MappedGraphic], PlanarFace), + faces: &[F], + shade: &dyn Fn(&F, vectorcraft_doc::color::Color) -> Paint, copies: &mut usize, ) -> Option>>> { let mut out: Vec>> = vec![vec![]; faces.len()]; let Some(doc) = doc else { return Some(out) }; - let pieces = unrolled(doc, graphics)?; + let pieces = unrolled(doc, graphics, face)?; let Some(all) = pieces.iter().map(|p| p.bounds).reduce(|a, b| a.union(b)) else { return Some(out) }; // Each piece listed in the buckets of the surface's x its bounds reach across. let width = (all.width() / SURFACE_BUCKETS as f64).max(1e-9); @@ -729,11 +790,12 @@ pub(crate) fn surface_parts( let mut cut_points = 0usize; let mut triangle_id = 0usize; for (face, parts) in faces.iter().zip(out.iter_mut()) { - let Some(cell) = face.surface.as_ref().filter(|c| c.outward && !face.cap) else { continue }; + let Some(cell) = face.outer_cell() else { continue }; if cell.uv.len() != cell.page.len() || !(3..=4).contains(&cell.uv.len()) { continue; } let triangles: &[[usize; 3]] = if cell.uv.len() == 3 { &[[0, 1, 2]] } else { &[[0, 1, 2], [0, 2, 3]] }; + let curved = face.curved(); for corners in triangles { triangle_id += 1; let pick = |of: &[Point]| corners.iter().map(|k| of.get(*k).copied()).collect::>>(); @@ -744,7 +806,7 @@ pub(crate) fn surface_parts( // where the graphic runs past the end of the profile. A four-cornered face is cut into // two triangles along its diagonal from corner 0 to corner 2: each takes the part of // the outline on its own side of it. - let window = if face.outline.is_some() { grown(window, 3.0) } else { window }; + let window = if curved.is_some() { grown(window, 3.0) } else { window }; // The pieces are looked up over the whole of the window they are cut to. let Some(reach) = window.iter().map(|p| Rect::from_points(*p, *p)).reduce(|a, b| a.union(b)) else { continue }; if reach.x1 < all.x0 || reach.x0 > all.x1 || reach.y1 < all.y0 || reach.y0 > all.y1 { @@ -771,7 +833,7 @@ pub(crate) fn surface_parts( } near.sort_unstable(); let own = corners.iter().find(|k| **k != 0 && **k != 2).and_then(|k| cell.page.get(*k)).filter(|_| triangles.len() == 2); - let rim = face.outline.as_ref().map(|outline| match (own, cell.page.first(), cell.page.get(2)) { + let rim = curved.as_deref().map(|outline| match (own, cell.page.first(), cell.page.get(2)) { (Some(&toward), Some(&a), Some(&b)) => { let side = side_of(a, b, toward); vectorcraft_pathops::boolean(outline, FillRule::NonZero, &side, FillRule::NonZero, vectorcraft_pathops::BoolOp::Intersect) @@ -834,21 +896,21 @@ pub(crate) fn surface_parts( /// The node of the part `path` (on the page, filled under `rule`) of `piece`, which `map` takes /// from the unrolled surface onto `face`. -fn surface_piece( +fn surface_piece( id: NodeId, piece: &Unrolled, (path, rule): (BezPath, FillRule), map: Affine, - face: &vectorcraft_three_d::Face, - shade: &dyn Fn(&vectorcraft_three_d::Face, vectorcraft_doc::color::Color) -> Paint, + face: &F, + shade: &dyn Fn(&F, vectorcraft_doc::color::Color) -> Paint, ) -> Node { let gradient_map = map * piece.place; // Under several lights a face's light varies across it in each channel: a solid color draws // as the face's own lit art in that color, clipped to the part. An opaque part also draws that // art clipped to a band of the seam stroke's width around its edges, as the other parts take // a stroke over their seams. - if let (Some(c), Some(light)) = (piece.paint.color().filter(|_| matches!(piece.paint, Paint::Solid { .. })), face.rgb_gradient) { - let lit = Arc::new(crate::lighting::rgb_gradient_art(id, &face.path(), &Paint::solid(c), light)); + if let (Some(c), Some(light)) = (piece.paint.color().filter(|_| matches!(piece.paint, Paint::Solid { .. })), face.rgb_light()) { + let lit = Arc::new(crate::lighting::rgb_gradient_art(id, &face.outline_path(), &Paint::solid(c), light)); let clipped = |area: &BezPath, rule: FillRule| { let mut clip = Node::path(id, PathData::from_bezpath(area), Appearance::default()); if let NodeKind::Path { rule: r, .. } = &mut clip.kind { @@ -881,7 +943,7 @@ fn surface_piece( match solid { Some(c) => f.paint = shade(face, c), None => { - vectorcraft_doc::recolor::map_paint(&mut f.paint, &|c| crate::lighting::shade(c, face.illumination)); + vectorcraft_doc::recolor::map_paint(&mut f.paint, &|c| crate::lighting::shade(c, face.light())); } } } @@ -996,23 +1058,106 @@ 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) and the maps of its front and back faces, when it has them. -#[derive(Clone, Copy, Debug, PartialEq)] +/// offsets are from their center), the maps of its front and back faces, when it has them, and +/// the visible part of its side unrolled, when it has graphics there. +#[derive(Clone, Debug, PartialEq)] pub struct GraphicFrame { pub bounds: Rect, front: Option, back: Option, + side: Option, +} + +/// 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 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 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 !inside(&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) + } } impl GraphicFrame { pub(super) fn new(bounds: Rect, front: Option, back: Option) -> Self { - Self { bounds, front, back } + Self { bounds, front, back, side: 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 } } 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, } } @@ -1023,23 +1168,34 @@ 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. + /// 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. 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)); + } 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`. + /// 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. pub fn offset_at(&self, face: PlanarFace, page: Point) -> Option<(f64, f64)> { - let art = self.map(face)?.to_art(page)?; + let art = match face { + PlanarFace::Side => self.side.as_ref()?.map(page, true)?, + _ => self.map(face)?.to_art(page)?, + }; let c = self.bounds.center(); let (x, y) = match face { PlanarFace::Front => (art.x - c.x, art.y - c.y), PlanarFace::Back => (c.x - art.x, art.y - c.y), + PlanarFace::Side => (art.x, art.y), }; (x.abs() <= MAX_OFFSET && y.abs() <= MAX_OFFSET).then_some((x, y)) } @@ -1047,11 +1203,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) @@ -1135,3 +1297,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.rs b/crates/effects/src/solids/tests.rs index 378299d514..b77903714e 100644 --- a/crates/effects/src/solids/tests.rs +++ b/crates/effects/src/solids/tests.rs @@ -774,6 +774,7 @@ fn a_stroke_face_through_a_fill_wall_is_cut_where_their_depths_meet() { side: true, away: false, end: None, + surface: None, plane: Some(DepthPlane { normal, offset, center: Point::ZERO, eye: None }), }; let wall = facet(0.0, [0.0, 0.0, 1.0], 0.0); diff --git a/crates/effects/src/solids/tests_graphics.rs b/crates/effects/src/solids/tests_graphics.rs index fe89dd1f84..92113017f9 100644 --- a/crates/effects/src/solids/tests_graphics.rs +++ b/crates/effects/src/solids/tests_graphics.rs @@ -531,12 +531,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"}]), @@ -546,10 +547,12 @@ fn graphics_are_checked() { assert!(check(EXTRUDE, bad.clone()).is_err(), "{bad}"); } assert!(check(ROTATE, json!([{"symbol": "Mark", "face": "back"}])).is_err()); + assert!(check(ROTATE, json!([{"symbol": "Mark", "face": "side"}])).is_err()); assert!(check(INFLATE, json!([{"symbol": "Mark"}])).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); @@ -569,10 +572,13 @@ 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"]); // 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..d216ff7d0d --- /dev/null +++ b/crates/effects/src/solids/tests_graphics_side.rs @@ -0,0 +1,255 @@ +//! 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 }), + 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 2d82d571c8..a2d8d03ad9 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).map(|r| r.unwrap().and_then(|(_, faces)| faces)).collect(); + built_solids_cast(id, &p, &parts, bounds, MAX_OBJECT_FACES, true, 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/effects/src/tests.rs b/crates/effects/src/tests.rs index 52b38f986d..2a34fb1d07 100644 --- a/crates/effects/src/tests.rs +++ b/crates/effects/src/tests.rs @@ -1708,6 +1708,115 @@ fn twist_joins_its_pieces_smoothly() { } } +#[test] +fn twist_boundary_handles_follow_the_inward_tangent() { + let line = PathData::single(SubPath::polyline(&[Point::new(40.0, 30.0), Point::new(60.0, 30.0)], false)); + let bounds = Rect::new(40.0, 30.0, 60.0, 30.0); + for angle in [90.0_f64, 400.0, -720.0] { + let out = apply_geometry(&[fx("distort.twist", json!({"angle": angle}))], &line, bounds); + let anchors = &out.subpaths[0].anchors; + let start = anchors.first().unwrap(); + let end = anchors.last().unwrap(); + assert_eq!(start.p, Point::new(40.0, 30.0)); + assert_eq!(end.p, Point::new(60.0, 30.0)); + for (actual, expected) in [ + (start.h_out - start.p, vectorcraft_geom::Vec2::new(1.0, -angle.to_radians())), + (end.h_in - end.p, vectorcraft_geom::Vec2::new(-1.0, angle.to_radians())), + ] { + assert!(actual.hypot() > 1e-9); + let error = (actual.x * expected.y - actual.y * expected.x).atan2(actual.dot(expected)).to_degrees().abs(); + assert!(error < 0.05, "{angle} degrees: boundary tangent differs by {error} degrees"); + } + } +} + +#[test] +fn twist_large_coordinate_joins_preserve_boundary_sides() { + use vectorcraft_geom::Anchor; + + let center = 1e16; + for offset in [32.0, 64.0] { + let p = Point::new(center + offset, 0.0); + let line = PathData::single(SubPath::new( + vec![ + Anchor::corner(Point::new(p.x - 18.0, 0.0)), + Anchor::with_handles(p, Point::new(p.x - 6.0, 0.0), Point::new(p.x + 6.0, 0.0)), + Anchor::corner(Point::new(p.x + 18.0, 0.0)), + ], + false, + )); + let out = crate::distort::twist(&line, Rect::new(center - 64.0, 0.0, center + 64.0, 0.0), 90.0, 3); + let join = &out.subpaths[0].anchors[1]; + if offset == 64.0 { + assert_eq!(join.h_out, Point::new(p.x + 6.0, 0.0)); + let actual = join.h_in - join.p; + let expected = vectorcraft_geom::Vec2::new(-1.0, std::f64::consts::FRAC_PI_2); + let error = actual.cross(expected).atan2(actual.dot(expected)).abs(); + assert!(error < 1e-9, "{actual:?}"); + } else { + let incoming = join.p - join.h_in; + let outgoing = join.h_out - join.p; + assert!(incoming.cross(outgoing).abs() < 1e-9, "{incoming:?} {outgoing:?}"); + assert!(incoming.dot(outgoing) > 0.0); + } + } +} + +#[test] +fn twist_fractional_boundary_handles_use_each_sides_derivative() { + use vectorcraft_geom::Anchor; + + for (bounds, step) in [(Rect::new(40.1, 30.0, 60.3, 30.0), 1.0), (Rect::new(-60.3, 30.0, -40.1, 30.0), 1.0)] { + for x in [bounds.x0, bounds.x1] { + for angle in [90.0_f64, 400.0, -720.0] { + let p = Point::new(x, 30.0); + let line = PathData::single(SubPath::new( + vec![ + Anchor::corner(Point::new(x - 3.0 * step, 30.0)), + Anchor::with_handles(p, Point::new(x - step, 30.0), Point::new(x + step, 30.0)), + Anchor::corner(Point::new(x + 3.0 * step, 30.0)), + ], + false, + )); + let out = crate::distort::twist(&line, bounds, angle, 3); + assert!( + out.subpaths[0].anchors.iter().all(|a| a.p.is_finite() && a.h_in.is_finite() && a.h_out.is_finite()), + "x={x} angle={angle}: {:?}", + out.subpaths[0].anchors + ); + let join = &out.subpaths[0].anchors[1]; + assert!(join.p.distance(p) < 1e-10, "{:?}", join.p); + let a = angle.to_radians(); + let expected = if x == bounds.x0 { [(-1.0, 0.0), (1.0, -a)] } else { [(-1.0, a), (1.0, 0.0)] }; + for (actual, (dx, dy)) in [join.h_in - join.p, join.h_out - join.p].into_iter().zip(expected) { + let expected = vectorcraft_geom::Vec2::new(dx, dy); + let error = actual.cross(expected).atan2(actual.dot(expected)).abs(); + assert!(error < 1e-9, "x={x} angle={angle}: {actual:?}, join={join:?}, source={:?}", line.subpaths[0].anchors[1]); + } + } + } + } + let bounds = Rect::new(1e16, 30.0, 1e16 + 18.0, 30.0); + let center = bounds.center(); + let line = PathData::single(SubPath::polyline(&[Point::new(center.x - 4.0, center.y), center, Point::new(center.x + 4.0, center.y)], false)); + let out = crate::distort::twist(&line, bounds, 90.0, 3); + assert_eq!(out.subpaths[0].anchors[1].p, center); + let bounds = Rect::new(0.0, 30.0, 2e16, 30.0); + let p = Point::new(bounds.x1 - 8.0, 30.0); + let line = PathData::single(SubPath::new( + vec![ + Anchor::corner(Point::new(p.x - 12.0, p.y)), + Anchor::with_handles(p, Point::new(p.x - 4.0, p.y), Point::new(p.x + 4.0, p.y)), + Anchor::corner(Point::new(p.x + 12.0, p.y)), + ], + false, + )); + let out = crate::distort::twist(&line, bounds, 90.0, 3); + let join = &out.subpaths[0].anchors[1]; + assert!(join.p.y - p.y > 10.0, "{:?}", join.p); + assert!(join.h_out.y - join.p.y < -4.0, "{join:?}"); +} + #[test] fn twist_fixes_the_outer_circle_and_rotates_inside() { let out = run("distort.twist", json!({"angle": 0}), &square()); diff --git a/crates/effects/src/tests/clipfx.rs b/crates/effects/src/tests/clipfx.rs index 57566fbb28..d13c59f229 100644 --- a/crates/effects/src/tests/clipfx.rs +++ b/crates/effects/src/tests/clipfx.rs @@ -543,3 +543,337 @@ fn raster_and_hidden_effects_leave_the_clip_as_it_is() { assert_eq!(bounds(&clipping_path(1, effects)), Rect::new(50.0, 50.0, 150.0, 150.0)); } } + +fn blue() -> Paint { + Paint::solid(Color::rgb(0.0, 0.0, 1.0)) +} + +fn green() -> Paint { + Paint::solid(Color::rgb(0.0, 1.0, 0.0)) +} + +/// "IIII" at 40 pt from (5, 60) in a test font built from the bundled Source Sans 3 +/// ([`vectorcraft_text::test_fonts::height_font`]), its characters filled blue when `fill` and +/// stroked green 2 pt wide when `stroke`. +fn painted_type(id: u64, fill: bool, stroke: bool) -> Node { + use vectorcraft_doc::text::{CharStyle, TextObject}; + use vectorcraft_text::test_fonts::{HEIGHT_FAMILY, height_font}; + static FONT: std::sync::Once = std::sync::Once::new(); + FONT.call_once(|| { + vectorcraft_text::FontDb::global().add_font(height_font(true).expect("the test font builds")); + }); + let style = CharStyle { + font_family: HEIGHT_FAMILY.into(), + size: 40.0, + fill: if fill { blue() } else { Paint::None }, + stroke: if stroke { green() } else { Paint::None }, + stroke_width: 2.0, + ..Default::default() + }; + Node::new(NodeId(id), NodeKind::Text(Box::new(TextObject::point(vectorcraft_geom::Point::new(5.0, 60.0), "IIII", style)))) +} + +/// Does `n` or an object in it have a blue fill (`fill`) or a green stroke? +fn paints(n: &Node, fill: bool) -> bool { + use vectorcraft_doc::AppearanceItem; + let own = n.appearance.items.iter().any(|i| match i { + AppearanceItem::Fill(f) => fill && f.paint == blue(), + AppearanceItem::Stroke(s) => !fill && s.paint == green() && s.width > 0.0, + }); + own || n.children().into_iter().flatten().any(|c| paints(c, fill)) +} + +/// What the first clip group in `n` paints: the bounds of the region it clips to, the bounds of +/// the blue fill art right after its clipping path (behind the clipped art), the bounds of the +/// green stroke art right after the clip group (over it, outside the clip), and whether a green +/// stroke paints inside the clip group. +type Painted = (Rect, Option, Option, bool); + +fn painted_clip(n: &Node) -> Option { + let ch = n.children()?; + for (i, c) in ch.iter().enumerate() { + if let NodeKind::Group { children, clip: true } = &c.kind { + let region = clip_outline(children.first()?)?.0.bounding_box(); + let fill = children.get(1).filter(|f| paints(f, true)).and_then(|f| f.geometric_bounds()); + let stroke = ch.get(i + 1).filter(|s| paints(s, false)).and_then(|s| s.geometric_bounds()); + let inside = children.iter().skip(1).any(|m| paints(m, false)); + return Some((region, fill, stroke, inside)); + } + if let Some(found) = painted_clip(c) { + return Some(found); + } + } + None +} + +fn near_rect(a: Rect, b: Rect) -> bool { + (a.x0 - b.x0).abs() < 0.5 && (a.y0 - b.y0).abs() < 0.5 && (a.x1 - b.x1).abs() < 0.5 && (a.y1 - b.y1).abs() < 0.5 +} + +#[test] +fn painted_clipping_type_survives_enclosing_geometry_effect() { + // Type that paints a fill, a stroke, both or neither clips a red square, in a group whose + // Transform (moving everything 10 pt down, beside other type that stays type in the export) or + // Offset Path reshapes its members: the canvas and the export keep the type's fill as art + // behind the square inside the clip and its stroke as art over the clip group, both reshaped + // with the clip. + let plain = clip_outline(&painted_type(3, false, false)).expect("the type clips").0.bounding_box(); + assert!(plain.width() > 10.0 && plain.height() > 10.0, "the type has glyph outlines: {plain:?}"); + let effects = [fx("distort.transform", json!({"moveV": 10})), fx("path.offsetPath", json!({"offset": 1}))]; + for effect in effects { + for (fill, stroke) in [(true, false), (false, true), (true, true), (false, false)] { + let clipped = clip_group(2, painted_type(3, fill, stroke)); + let mut outer = Node::group(NodeId(1), vec![Arc::new(clipped), Arc::new(painted_type(5, true, false))]); + outer.appearance.effects.push(effect.clone()); + let canvas = crate::evaluate_container(None, &outer).unwrap(); + let mut d = Document::new(400.0, 400.0); + let layer = d.layers[0].id; + d.insert(Some(layer), 0, outer).unwrap(); + let baked = bake_document(&d).unwrap(); + let exported = baked.layers.iter().find_map(|l| painted_clip(l)); + for (what, found) in [("canvas", painted_clip(&canvas)), ("export", exported)] { + let case = format!("{what}, {}, fill {fill}, stroke {stroke}", effect.id); + let (region, fills, strokes, inside) = found.unwrap_or_else(|| panic!("{case}: no clip group")); + if effect.id == "distort.transform" { + assert!((region.y0 - plain.y0 - 10.0).abs() < 0.5 && (region.x0 - plain.x0).abs() < 0.5, "{case}: {region:?} from {plain:?}"); + } else { + let grown = Rect::new(plain.x0 - 1.0, plain.y0 - 1.0, plain.x1 + 1.0, plain.y1 + 1.0); + assert!(near_rect(region, grown), "{case}: {region:?} is {plain:?} offset by 1 pt"); + } + assert_eq!(fills.is_some(), fill, "{case}: fill art {fills:?}"); + assert_eq!(strokes.is_some(), stroke, "{case}: stroke art {strokes:?}"); + assert!(!inside, "{case}: the stroke paints outside the clip"); + for art in fills.into_iter().chain(strokes) { + assert!(near_rect(art, region), "{case}: the paint {art:?} follows the clip {region:?}"); + } + } + } + } +} + +/// The group in `n` that holds a clip group and then the green stroke art of its clipping type, +/// with that clip group. +fn stroke_wrapper(n: &Node) -> Option<(&Node, &Node)> { + let ch = n.children()?; + if let [inner, stroke, ..] = ch.as_slice() + && matches!(inner.kind, NodeKind::Group { clip: true, .. }) + && !n.clips() + && paints(stroke, false) + { + return Some((n, inner)); + } + ch.iter().find_map(|c| stroke_wrapper(c)) +} + +#[test] +fn clipping_type_strokes_paint_over_a_knockout_clip_group() { + // A clip group set to Knockout Group On, Off or neutral, clipped by type that strokes: its + // clipped art knocks out as the clip group says, and the type's stroke paints over it without + // knocking it out, as the canvas draws the live clip group. The type is reshaped by a group's + // Transform around it, or by its own Offset Path. + use vectorcraft_doc::Knockout; + for (knockout, around) in [(Knockout::On, Knockout::Off), (Knockout::Off, Knockout::Off), (Knockout::Neutral, Knockout::Neutral)] { + for own in [false, true] { + let mut ty = painted_type(3, true, true); + if own { + ty.appearance.effects.push(fx("path.offsetPath", json!({"offset": 1}))); + } + let mut clipped = clip_group(2, ty); + clipped.knockout = knockout; + let mut outer = Node::group(NodeId(1), vec![Arc::new(clipped)]); + if !own { + outer.appearance.effects.push(fx("distort.transform", json!({"moveV": 10}))); + } + let mut d = Document::new(400.0, 400.0); + let layer = d.layers[0].id; + d.insert(Some(layer), 0, outer.clone()).unwrap(); + let baked = bake_document(&d).unwrap(); + let canvas = if own { None } else { crate::evaluate_container(None, &outer) }; + let exported = baked.layers.iter().find_map(|l| stroke_wrapper(l)); + for (what, found) in [("canvas", canvas.as_ref().and_then(stroke_wrapper)), ("export", exported)] { + if own && what == "canvas" { + continue; + } + let case = format!("{what}, own effect {own}, knockout {knockout:?}"); + let (wrapper, inner) = found.unwrap_or_else(|| panic!("{case}: no group around the clip")); + assert_eq!(inner.knockout, knockout, "{case}: the clipped art knocks out as before"); + assert_eq!(wrapper.knockout, around, "{case}: the stroke does not knock out the clipped art"); + } + } + } +} + +#[test] +fn a_clip_groups_own_fill_stays_in_the_clip_when_its_clipping_type_strokes() { + // A clip group with a yellow fill of its own and an Offset Path effect, clipped by type that + // strokes: the group's fill still paints inside the clip, and the type's stroke over it. + let yellow = Paint::solid(Color::rgb(1.0, 1.0, 0.0)); + let mut group = clip_group(2, painted_type(3, false, true)); + group.appearance = + Appearance { effects: vec![fx("path.offsetPath", json!({"offset": 0}))], ..Appearance::basic(yellow.clone(), Paint::None, 0.0) }.into(); + let canvas = crate::evaluate_container(None, &group).unwrap(); + let (_, _, strokes, inside) = painted_clip(&Node::group(NodeId(9), vec![Arc::new(canvas.clone())])).unwrap(); + assert!(strokes.is_some() && !inside, "{canvas:?}"); + let NodeKind::Group { children, clip: false } = &canvas.kind else { panic!("not a group around the clip: {canvas:?}") }; + let NodeKind::Group { children: clipped, clip: true } = &children[0].kind else { panic!("no clip group first: {children:?}") }; + let yellow_in = |n: &Node| n.appearance.items.iter().any(|i| matches!(i, vectorcraft_doc::AppearanceItem::Fill(f) if f.paint == yellow)); + assert!(clipped.iter().skip(1).any(|c| yellow_in(c)), "the group's fill paints inside the clip: {clipped:?}"); + assert!(!children.iter().skip(1).any(|c| yellow_in(c)), "{children:?}"); +} + +#[test] +fn a_clip_groups_own_gradient_spans_the_clip_when_its_clipping_type_strokes() { + // A clip group with an unplaced linear gradient fill of its own and an Offset Path effect, + // clipped by type with a stroke whose Transform effect moves it 60 pt right: the gradient + // spans the region the clipping path clips to. + use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop}; + let stops = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::WHITE)]; + let unplaced = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops)))); + let mut ty = painted_type(3, false, false); + ty.appearance = Appearance::basic(Paint::None, green(), 2.0).into(); + for item in &mut ty.appearance.items { + if let vectorcraft_doc::AppearanceItem::Stroke(s) = item { + s.effects.push(fx("distort.transform", json!({"moveH": 60}))); + } + } + let mut group = clip_group(2, ty); + group.appearance = + Appearance { effects: vec![fx("path.offsetPath", json!({"offset": 0}))], ..Appearance::basic(unplaced, Paint::None, 0.0) }.into(); + let canvas = crate::evaluate_container(None, &group).unwrap(); + let NodeKind::Group { children, clip: false } = &canvas.kind else { panic!("not a group around the clip: {canvas:?}") }; + let NodeKind::Group { children: clipped, clip: true } = &children[0].kind else { panic!("no clip group first: {children:?}") }; + let region = clip_outline(&clipped[0]).expect("the type clips").0.bounding_box(); + let fill = clipped.iter().skip(1).find_map(|c| match c.appearance.fill_paint() { + Paint::Gradient(g) => g.geom, + _ => None, + }); + let geom = fill.unwrap_or_else(|| panic!("no gradient fill inside the clip: {clipped:?}")); + let (left, right) = (geom.start.x.min(geom.end.x), geom.start.x.max(geom.end.x)); + assert!((left - region.x0).abs() < 0.5 && (right - region.x1).abs() < 0.5, "the gradient {geom:?} spans the clip {region:?}"); +} + +#[test] +fn a_groups_own_fill_paints_only_the_clip_of_clipping_type_whose_stroke_moves() { + // A group with a fill of its own (solid, or an unplaced linear gradient) and a Transform effect + // (moving everything 10 pt down, or scaling it to half its width around its middle) holds a + // clip group clipped by type whose stroke has a Transform effect moving it 60 pt right, + // outside the clip. On the canvas and in the export, the clip region is the type's glyphs + // reshaped by the group's effect, and the group's fill paints that region alone, its gradient + // spanning it: the moved stroke adds nothing to the region, the fill or the box the group's + // effect scales around. + use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop}; + let yellow = Paint::solid(Color::rgb(1.0, 1.0, 0.0)); + let stops = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::WHITE)]; + let unplaced = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops)))); + let mut ty = painted_type(3, false, false); + ty.appearance = Appearance::basic(Paint::None, green(), 2.0).into(); + for item in &mut ty.appearance.items { + if let vectorcraft_doc::AppearanceItem::Stroke(s) = item { + s.effects.push(fx("distort.transform", json!({"moveH": 60}))); + } + } + let live = clip_outline(&ty).expect("the type clips").0.bounding_box(); + let moved = Rect::new(live.x0, live.y0 + 10.0, live.x1, live.y1 + 10.0); + // Scaled to half its width around the middle of the clip, which the stroke does not move. + let (mid, quarter) = ((live.x0 + live.x1) / 2.0, live.width() / 4.0); + let narrowed = Rect::new(mid - quarter, live.y0, mid + quarter, live.y1); + // The group's own fill art: every object outside the clip groups whose own fill is `paint`. + fn own_fills<'a>(n: &'a Node, paint: &Paint, out: &mut Vec<&'a Node>) { + let mine = n.appearance.items.iter().any(|i| match (i, paint) { + (vectorcraft_doc::AppearanceItem::Fill(f), Paint::Gradient(_)) => matches!(f.paint, Paint::Gradient(_)), + (vectorcraft_doc::AppearanceItem::Fill(f), p) => f.paint == *p, + _ => false, + }); + if mine { + out.push(n); + } + for c in n.children().into_iter().flatten().filter(|c| !c.clips()) { + own_fills(c, paint, out); + } + } + let cases = [(json!({"moveV": 10}), moved), (json!({"scaleH": 50, "scaleV": 100}), narrowed)]; + for ((params, region), paint) in cases.iter().flat_map(|c| [yellow.clone(), unplaced.clone()].map(|p| (c.clone(), p))) { + let mut outer = Node::group(NodeId(1), vec![Arc::new(clip_group(2, ty.clone()))]); + outer.appearance = + Appearance { effects: vec![fx("distort.transform", params.clone())], ..Appearance::basic(paint.clone(), Paint::None, 0.0) }.into(); + let canvas = crate::evaluate_container(None, &outer).unwrap(); + let mut d = Document::new(400.0, 400.0); + let layer = d.layers[0].id; + d.insert(Some(layer), 0, outer).unwrap(); + let baked = bake_document(&d).unwrap(); + let exported = baked.layers[0].children().and_then(|ch| ch.first()).cloned().expect("the export holds the group"); + for (what, art) in [("canvas", &canvas), ("export", &*exported)] { + let case = format!("{what}, {params}, {}", if matches!(paint, Paint::Gradient(_)) { "gradient" } else { "solid" }); + let (clip, _, strokes, _) = painted_clip(art).unwrap_or_else(|| panic!("{case}: no clip group in {art:?}")); + assert!(near_rect(clip, region), "{case}: the clip {clip:?} is the type's glyphs reshaped {region:?}"); + let strokes = strokes.unwrap_or_else(|| panic!("{case}: no stroke art")); + assert!(strokes.x1 > region.x1 + 25.0, "{case}: the stroke {strokes:?} moves outside the clip {region:?}"); + let mut fills = vec![]; + own_fills(art, &paint, &mut fills); + assert!(!fills.is_empty(), "{case}: no fill art of the group in {art:?}"); + let painted = fills.iter().filter_map(|f| f.geometric_bounds()).reduce(|a, b| a.union(b)).unwrap(); + assert!(near_rect(painted, region), "{case}: the group's fill {painted:?} paints the clip {region:?}"); + if let Paint::Gradient(_) = paint { + for fill in fills { + let geom = match fill.appearance.fill_paint() { + Paint::Gradient(g) => g.geom, + _ => None, + }; + let geom = geom.unwrap_or_else(|| panic!("{case}: the gradient is not placed: {fill:?}")); + let (left, right) = (geom.start.x.min(geom.end.x), geom.start.x.max(geom.end.x)); + assert!( + (left - region.x0).abs() < 0.5 && (right - region.x1).abs() < 0.5, + "{case}: the gradient {geom:?} spans the clip {region:?}" + ); + } + } + } + } +} + +#[test] +fn a_clip_groups_placed_gradient_follows_free_distort_by_the_clip_when_its_clipping_type_strokes() { + // A clip group with a placed linear gradient fill of its own, in a group with Free Distort, + // clipped by type whose stroke has a Transform effect moving it 60 pt right, outside the clip: + // the gradient moves and scales from the clip's bounds, as for the same clip group whose type + // does not stroke. The moved stroke adds nothing to those bounds. + use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop}; + let stops = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::WHITE)]; + let ramp = GradientPaint::new(Gradient::new(GradientKind::Linear, stops)); + let geom = GradientGeom { start: (10.0, 45.0).into(), end: (30.0, 45.0).into(), aspect: 1.0, focal: None }; + let placed = Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..ramp })); + fn placed_geom(n: &Node) -> Option { + if let Paint::Gradient(g) = n.appearance.fill_paint() + && g.geom.is_some() + { + return g.geom; + } + n.children().into_iter().flatten().find_map(|c| placed_geom(c)) + } + let ends = |stroke: bool| { + let mut ty = painted_type(3, false, false); + if stroke { + ty.appearance = Appearance::basic(Paint::None, green(), 2.0).into(); + for item in &mut ty.appearance.items { + if let vectorcraft_doc::AppearanceItem::Stroke(s) = item { + s.effects.push(fx("distort.transform", json!({"moveH": 60}))); + } + } + } + let mut group = clip_group(2, ty); + group.appearance = Appearance::basic(placed.clone(), Paint::None, 0.0).into(); + let mut outer = Node::group(NodeId(1), vec![Arc::new(group)]); + let corners = json!({"corners": [[1.0 / 3.0, 0.0], [4.0 / 3.0, 0.0], [1.0, 1.0], [0.0, 1.0]]}); + outer.appearance.effects.push(fx("distort.freeDistort", corners)); + let canvas = crate::evaluate_container(None, &outer).unwrap(); + if stroke { + assert!(stroke_wrapper(&canvas).is_some(), "the type's stroke paints around the clip: {canvas:?}"); + } + placed_geom(&canvas).unwrap_or_else(|| panic!("no placed gradient: {canvas:?}")) + }; + let (plain, stroked) = (ends(false), ends(true)); + assert!( + plain.start.distance(stroked.start) < 0.5 && plain.end.distance(stroked.end) < 0.5, + "the gradient {stroked:?} follows the clip as {plain:?} does" + ); +} diff --git a/crates/effects/src/util.rs b/crates/effects/src/util.rs index de203b4955..6b79d19999 100644 --- a/crates/effects/src/util.rs +++ b/crates/effects/src/util.rs @@ -71,7 +71,7 @@ pub fn seg_cubic(sp: &SubPath, i: usize) -> CubicBez { /// Non-linear path mapping (shared with live envelopes in `vectorcraft-doc`), and the split of /// segments into pieces within an anchor budget. -pub use vectorcraft_doc::live::{fit_piece, map_nonlinear_within, map_smooth_within, pieces}; +pub use vectorcraft_doc::live::{fit_piece, map_handles_within, map_nonlinear_within, pieces}; /// About how many lines the renderer flattens `path` into at 1 px/pt: one for a straight /// segment, and for a curve the count Wang's formula gives at vello's tolerance of 0.25 px, diff --git a/crates/engine/examples/layer_select_bench.rs b/crates/engine/examples/layer_select_bench.rs new file mode 100644 index 0000000000..256cada3af --- /dev/null +++ b/crates/engine/examples/layer_select_bench.rs @@ -0,0 +1,154 @@ +//! `cargo run --release -p vectorcraft-engine --example layer_select_bench` prints the time of a +//! Shift-click in the Layers panel's selection column (`layer.selectAll {id, add: true}`) on a layer of +//! 2,000, 20,000 and 50,000 rectangles, with all of its art selected (the click removes it) and with +//! every other object selected (the click adds the rest). Each case is timed one id at a time (`old`, +//! the loop the command used before, copied here) and in one pass (`new`), side by side in one +//! process: first the whole command, then the selection step alone. Each case checks that both give +//! the same selection and reply before it is timed. +//! `ITERS` sets the runs per case (default 7); each row is the median wall time in ms, followed by +//! every run of `old` and of `new`. +// Example (dev tool): unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::collections::HashSet; +use std::hint::black_box; +use std::time::Instant; + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Appearance, Document, Node, NodeId, Selection}; +use vectorcraft_engine::Session; +use vectorcraft_geom::{Anchor, PathData, Point, SubPath}; + +fn iters() -> usize { + std::env::var("ITERS").ok().and_then(|v| v.parse().ok()).unwrap_or(7).max(1) +} + +fn median(ms: &[f64]) -> f64 { + let mut ms = ms.to_vec(); + ms.sort_by(f64::total_cmp); + ms[ms.len() / 2] +} + +/// A document whose first layer holds `n` 10 pt squares in a row → (document, layer, squares). +fn squares(n: usize) -> (Document, NodeId, Vec) { + let mut doc = Document::new(1600.0, 1200.0); + let layer = doc.layers[0].id; + let ids = (0..n) + .map(|i| { + let (x, y) = ((i % 100) as f64 * 12.0, (i / 100) as f64 * 12.0); + let corners = [(x, y), (x + 10.0, y), (x + 10.0, y + 10.0), (x, y + 10.0)]; + let path = PathData::single(SubPath::new(corners.iter().map(|&(x, y)| Anchor::corner(Point::new(x, y))).collect(), true)); + let id = doc.alloc_id(); + doc.insert(Some(layer), usize::MAX, Node::path(id, path, Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 1.0))).unwrap(); + id + }) + .collect(); + (doc, layer, ids) +} + +/// `layer.selectAll {id: layer, add: true}` before the change: the layer's art checked, removed or +/// added one id at a time with [`Selection::contains`], [`Selection::remove`] and [`Selection::add`]. +fn old_command(s: &mut Session, layer: NodeId) -> Value { + let st = s.doc().unwrap(); + let ids = st.doc.node(layer).unwrap().layer_art(true); + let all_selected = !ids.is_empty() && ids.iter().all(|i| st.selection.contains(*i)); + let rows = st.layer_rows.clone(); + s.select(|_, sel| old_step(sel, &ids, all_selected)).unwrap(); + let st = s.doc_mut().unwrap(); + st.layer_rows = rows; + json!({ "selected": st.selection.objects.iter().map(|i| i.0).collect::>() }) +} + +fn old_step(sel: &mut Selection, ids: &[NodeId], all_selected: bool) { + for i in ids { + if all_selected { sel.remove(*i) } else { sel.add(*i) } + } +} + +fn new_command(s: &mut Session, layer: NodeId) -> Value { + s.execute("layer.selectAll", &json!({"id": layer.0, "add": true})).unwrap() +} + +/// Every run of `old` and of `new`, run in turn, each from `prepare`'s state. +fn time(mut prepare: impl FnMut() -> S, old: impl Fn(&mut S), new: impl Fn(&mut S)) -> (Vec, Vec) { + let run = |s: &mut S, f: &dyn Fn(&mut S)| { + let t = Instant::now(); + f(s); + t.elapsed().as_secs_f64() * 1000.0 + }; + let (mut olds, mut news) = (Vec::new(), Vec::new()); + for _ in 0..iters() { + let mut s = prepare(); + olds.push(run(&mut s, &old)); + black_box(&s); + let mut s = prepare(); + news.push(run(&mut s, &new)); + black_box(&s); + } + (olds, news) +} + +fn row(name: &str, (old, new): (Vec, Vec)) { + let (o, n) = (median(&old), median(&new)); + let list = |ms: &[f64]| ms.iter().map(|m| format!("{m:.2}")).collect::>().join(" "); + println!(" {name:<40} {o:>12.3} ms {n:>12.3} ms {:>9.1}x", o / n.max(1e-9)); + println!(" old runs: {}", list(&old)); + println!(" new runs: {}", list(&new)); +} + +fn main() { + println!(" {:<40} {:>15} {:>15} {:>10}", "case", "old", "new", "speedup"); + for n in [2_000usize, 20_000, 50_000] { + println!("{n} objects"); + let (doc, layer, ids) = squares(n); + let mut s = Session::new(); + s.add_document(doc, None); + let mut all = Selection::default(); + all.set(ids.iter().copied()); + let mut half = Selection::default(); + half.set(ids.iter().copied().step_by(2)); + for (name, start) in [("all selected (removes)", &all), ("half selected (adds)", &half)] { + let reset = |s: &mut Session| { + let st = s.doc_mut().unwrap(); + st.selection = start.clone(); + st.layer_rows.clear(); + }; + // Both ways give the same selection and reply. + reset(&mut s); + let old_reply = old_command(&mut s, layer); + let old_sel = s.doc().unwrap().selection.clone(); + reset(&mut s); + let new_reply = new_command(&mut s, layer); + assert_eq!(s.doc().unwrap().selection, old_sel, "{name}: the same selection"); + assert_eq!(new_reply, old_reply, "{name}: the same reply"); + + let (mut olds, mut news) = (Vec::new(), Vec::new()); + for _ in 0..iters() { + for (f, ms) in [(old_command as fn(&mut Session, NodeId) -> Value, &mut olds), (new_command, &mut news)] { + reset(&mut s); + let t = Instant::now(); + black_box(f(&mut s, layer)); + ms.push(t.elapsed().as_secs_f64() * 1000.0); + } + } + row(&format!("command, {name}"), (olds, news)); + // The selection step alone, on a copy of the starting selection. + let art = s.doc().unwrap().doc.node(layer).unwrap().layer_art(true); + let selected: HashSet = start.objects.iter().copied().collect(); + let all_selected = art.iter().all(|i| selected.contains(i)); + let new_step = |sel: &mut Selection| { + if all_selected { + sel.remove_all(art.iter().copied()); + } else { + sel.add_all(art.iter().copied()); + } + }; + let (mut a, mut b) = (start.clone(), start.clone()); + old_step(&mut a, &art, all_selected); + new_step(&mut b); + assert_eq!(a, b, "{name}: the same selection step"); + row(&format!("selection step, {name}"), time(|| start.clone(), |sel| old_step(sel, &art, all_selected), new_step)); + } + } +} diff --git a/crates/engine/examples/link_colors_bench.rs b/crates/engine/examples/link_colors_bench.rs new file mode 100644 index 0000000000..d403339706 --- /dev/null +++ b/crates/engine/examples/link_colors_bench.rs @@ -0,0 +1,217 @@ +//! `cargo run --release -p vectorcraft-engine --example link_colors_bench` prints the time +//! `Document::map_solid_paints_in` takes to link the paints of selected objects to swatches, as Add Used +//! Colors and New Color Group do for the selection with global swatches, on synthetic documents: 2,000 and +//! 20,000 rectangles in one layer, and 5,000 rectangles in 1,000 groups of groups, selected with and +//! without the groups that hold them. The fills and strokes use 50 colors, each with a swatch to link to. +//! For each it times two ways of finding the selected objects that no other selected object holds: a +//! search of the id list for each ancestor of each id, and a lookup of each ancestor in a set of the ids +//! (as `map_solid_paints_in` does). Both then link the same paints in the same loop. It checks that both +//! give the same count, visit the same paints in the same order and leave the same document as +//! `map_solid_paints_in` before it times them. +//! `ITERS` sets the runs per row (default 7); the two ways run in alternating order, each run links 10 +//! fresh copies of the document, and each row is the median time of one call. On Linux the times are the CPU time of the main thread, which runs +//! everything, in ms; elsewhere they are wall times. +// Example (dev tool): unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::collections::{HashMap, HashSet}; +use std::hint::black_box; +use std::sync::Arc; +use std::time::Instant; + +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::swatches::{LinkFn, map_node_solid_paints}; +use vectorcraft_doc::{Appearance, Document, Node, NodeId}; +use vectorcraft_geom::{Rect, shapes}; + +/// The colors the rectangles use, each with a swatch to link to. +const COLORS: usize = 50; + +/// The calls in each timed run; a row gives the time of one call. +const REPS: usize = 10; + +/// A way of finding the ids that no other listed id holds. +type Roots = fn(&Document, &[NodeId]) -> Vec; + +/// A way of applying a link function to the paints of the listed ids, returning the count changed. +type Map<'a> = dyn FnMut(&mut Document, &[NodeId], &mut LinkFn) -> usize + 'a; + +fn iters() -> usize { + std::env::var("ITERS").ok().and_then(|v| v.parse().ok()).unwrap_or(7).max(1) +} + +fn median(mut ms: Vec) -> f64 { + ms.sort_by(f64::total_cmp); + ms[ms.len() / 2] +} + +/// The CPU time of the calling thread in ns, from `/proc/thread-self/schedstat` (Linux only). +fn thread_cpu_ns() -> Option { + std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok() +} + +/// The time `f` takes, in ms: CPU time where the system reports it, wall time otherwise. +fn measure(f: impl FnOnce()) -> f64 { + match thread_cpu_ns() { + Some(start) => { + f(); + thread_cpu_ns().map_or(f64::NAN, |end| end.saturating_sub(start) as f64 / 1e6) + } + None => { + let t = Instant::now(); + f(); + t.elapsed().as_secs_f64() * 1000.0 + } + } +} + +/// Color `i` of [`COLORS`]: each has its own red value. +fn color(i: usize) -> Color { + Color::rgb(i as f32 / COLORS as f32, 0.5, 0.25) +} + +/// The bits of a color's red value, which tell the colors of [`color`] apart; `u32::MAX` for other color models. +fn red_bits(c: &Color) -> u32 { + match c { + Color::Rgb { r, .. } => r.to_bits(), + _ => u32::MAX, + } +} + +/// The ids in the order given, less those with an ancestor in the list: a search of the list for each ancestor. +fn roots_by_search(d: &Document, ids: &[NodeId]) -> Vec { + ids.iter().copied().filter(|id| !d.ancestry(*id).is_some_and(|a| a[..a.len() - 1].iter().any(|p| ids.contains(p)))).collect() +} + +/// [`roots_by_search`] with each ancestor looked up in a set of the ids. +fn roots_by_set(d: &Document, ids: &[NodeId]) -> Vec { + let listed: HashSet = ids.iter().copied().collect(); + ids.iter().copied().filter(|id| !d.ancestry(*id).is_some_and(|a| a[..a.len() - 1].iter().any(|p| listed.contains(p)))).collect() +} + +/// `f` applied to the paints of the subtrees of the ids `roots` finds, each node holding a changed +/// paint put in place: the work of `map_solid_paints_in`. +fn map_in(d: &mut Document, ids: &[NodeId], roots: Roots, f: &mut LinkFn) -> usize { + let mut n = 0; + for id in roots(d, ids) { + let Some(mut node) = d.node(id).cloned() else { continue }; + let count = map_node_solid_paints(&mut node, f); + if count > 0 + && let Some(slot) = d.node_mut(id) + { + *slot = node; + n += count; + } + } + n +} + +/// Link every paint whose color has a swatch to that swatch, as Add Used Colors does for global +/// swatches, recording each paint visited. Returns the count and the visits. +fn link(d: &mut Document, ids: &[NodeId], map: &mut Map) -> (usize, Vec<(Color, Option)>) { + let names: HashMap = (0..COLORS).map(|i| (red_bits(&color(i)), format!("Swatch {i}"))).collect(); + let mut visits = vec![]; + let n = map(d, ids, &mut |c, s, _| { + visits.push((*c, s.clone())); + match names.get(&red_bits(c)) { + Some(name) if s.is_none() => { + *s = Some(name.clone()); + true + } + _ => false, + } + }); + (n, visits) +} + +fn rect(d: &mut Document, i: usize) -> Arc { + let id = d.alloc_id(); + let (x, y) = ((i % 100) as f64 * 12.0, (i / 100) as f64 * 12.0); + let r = shapes::rectangle(Rect::new(x, y, x + 10.0, y + 10.0)); + let a = Appearance::basic(Paint::solid(color(i % COLORS)), Paint::solid(color((i + 7) % COLORS)), 1.0); + Arc::new(Node::path(id, r, a)) +} + +/// `n` rectangles in the first layer, all selected. +fn flat(n: usize) -> (Document, Vec) { + let mut d = Document::new(1600.0, 1200.0); + let l = d.layers[0].id; + let mut ids = vec![]; + for i in 0..n { + let node = rect(&mut d, i); + ids.push(node.id); + d.insert(Some(l), usize::MAX, Arc::unwrap_or_clone(node)).unwrap(); + } + (d, ids) +} + +/// 1,000 groups in the first layer, each holding a group of 5 rectangles: the rectangles, and with +/// `groups` the two groups above each of them too, listed first. +fn nested(groups: bool) -> (Document, Vec) { + let mut d = Document::new(1600.0, 1200.0); + let l = d.layers[0].id; + let (mut outer_ids, mut leaves) = (vec![], vec![]); + for g in 0..1_000 { + let rects: Vec> = (0..5).map(|i| rect(&mut d, g * 5 + i)).collect(); + leaves.extend(rects.iter().map(|r| r.id)); + let inner = Node::group(d.alloc_id(), rects); + let outer = Node::group(d.alloc_id(), vec![Arc::new(inner.clone())]); + if groups { + outer_ids.extend([outer.id, inner.id]); + } + d.insert(Some(l), usize::MAX, outer).unwrap(); + } + outer_ids.extend(leaves); + (d, outer_ids) +} + +fn bench(name: &str, (doc, ids): (Document, Vec)) { + let mut shipped = doc.clone(); + let want = link(&mut shipped, &ids, &mut |d, ids, f| d.map_solid_paints_in(ids, f)); + for roots in [roots_by_search as Roots, roots_by_set] { + let mut d = doc.clone(); + let got = link(&mut d, &ids, &mut |d, ids, f| map_in(d, ids, roots, f)); + assert_eq!(got, want, "{name}: the same count and visits"); + assert_eq!(d.layers, shipped.layers, "{name}: the same document"); + } + let (mut old, mut new, mut real) = (vec![], vec![], vec![]); + let timed = |map: &mut Map| { + let mut docs = vec![doc.clone(); REPS]; + measure(|| { + for d in &mut docs { + black_box(link(d, black_box(&ids), &mut *map)); + } + }) / REPS as f64 + }; + for i in 0..iters() { + let run = |roots: Roots, out: &mut Vec| out.push(timed(&mut |d, ids, f| map_in(d, ids, roots, f))); + if i % 2 == 0 { + run(roots_by_search, &mut old); + run(roots_by_set, &mut new); + } else { + run(roots_by_set, &mut new); + run(roots_by_search, &mut old); + } + real.push(timed(&mut |d, ids, f| d.map_solid_paints_in(ids, f))); + } + let (old, new, real) = (median(old), median(new), median(real)); + println!(" {name:<46} {:>7} {:>7} {old:>12.3} {new:>12.3} {real:>12.3} {:>8.1}x", ids.len(), want.0, old / new); +} + +fn main() { + let unit = if thread_cpu_ns().is_some() { "CPU ms" } else { "wall ms" }; + println!( + " {:<46} {:>7} {:>7} {:>12} {:>12} {:>12} {:>9}", + "document", + "ids", + "linked", + format!("search, {unit}"), + format!("set, {unit}"), + format!("shipped, {unit}"), + "speedup" + ); + bench("2,000 rectangles in one layer", flat(2_000)); + bench("20,000 rectangles in one layer", flat(20_000)); + bench("5,000 rectangles in 1,000 groups of groups", nested(false)); + bench("the same with the 2,000 groups listed first", nested(true)); +} diff --git a/crates/engine/examples/stroke_targets_bench.rs b/crates/engine/examples/stroke_targets_bench.rs new file mode 100644 index 0000000000..b576968e49 --- /dev/null +++ b/crates/engine/examples/stroke_targets_bench.rs @@ -0,0 +1,146 @@ +//! `cargo run --release -p vectorcraft-engine --example stroke_targets_bench` prints the time `stroke.set` +//! takes to list its targets on documents of 2,000, 10,000 and 20,000 rectangles, all in one group. For +//! each size it times, on the same leaves, the merge that checks each leaf against the growing list and +//! the merge that checks it against a set, checks that the two lists are equal, and then times the whole +//! `stroke.set {weight: 3}` command twice: once with the group named and once with every rectangle named. +//! The whole-command rows include the document copy the command makes for undo; each run is undone +//! before the next, outside the timed part. +//! On Linux each row is the thread's CPU time, read from `/proc/thread-self/schedstat`; elsewhere +//! it is wall time, and the first line says which. `ITERS` sets the runs per row (default 7); each +//! row is the median in ms. A run of the two merge rows repeats the merge 1,000,000 / paths times +//! and gives the time of one. +// Example (dev tool): unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::collections::HashSet; +use std::hint::black_box; +use std::time::Instant; + +use serde_json::{Value, json}; +use vectorcraft_color::Color; +use vectorcraft_doc::{Document, NodeId}; +use vectorcraft_engine::Session; +use vectorcraft_geom::Rect; +use vectorcraft_testkit::fixtures::DocBuilder; + +fn iters() -> usize { + std::env::var("ITERS").ok().and_then(|v| v.parse().ok()).unwrap_or(7).max(1) +} + +/// The thread's CPU time in ns, or `None` where `/proc/thread-self/schedstat` cannot be read. +fn cpu_ns() -> Option { + std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok() +} + +/// The time `f` takes in ms: CPU time when [`cpu_ns`] reads, wall time otherwise. +fn ms(f: impl FnOnce()) -> f64 { + let (cpu, wall) = (cpu_ns(), Instant::now()); + f(); + match (cpu, cpu_ns()) { + (Some(a), Some(b)) => (b - a) as f64 / 1e6, + _ => wall.elapsed().as_secs_f64() * 1000.0, + } +} + +fn median(mut v: Vec) -> f64 { + v.sort_by(f64::total_cmp); + v[v.len() / 2] +} + +/// `n` 10 pt squares in one group, and the squares' ids in stacking order. +fn document(n: usize) -> (Document, NodeId, Vec) { + let mut b = DocBuilder::new(4000.0, 4000.0); + let kids: Vec<_> = (0..n) + .map(|i| { + let (x, y) = ((i % 200) as f64 * 12.0, (i / 200) as f64 * 12.0); + b.rect_node(Rect::new(x, y, x + 10.0, y + 10.0), Color::rgb(0.2, 0.4, 0.6)) + }) + .collect(); + let leaves = kids.iter().map(|k| k.id).collect(); + let group = b.group(kids, false); + (b.build(), group, leaves) +} + +/// The merge that checks each leaf against the growing list. +fn listed(mut out: Vec, leaves: Vec) -> Vec { + for id in leaves { + if !out.contains(&id) { + out.push(id); + } + } + out +} + +/// The merge that checks each leaf against a set seeded with `out`. +fn with_set(mut out: Vec, leaves: Vec) -> Vec { + let mut seen: HashSet = out.iter().copied().collect(); + for id in leaves { + if seen.insert(id) { + out.push(id); + } + } + out +} + +fn row(name: &str, ms: f64) { + println!(" {name:<52} {ms:>10.3} ms"); +} + +/// The median time of `stroke.set {weight: 3}` on `ids`, each run undone outside the timed part. +fn whole_command(s: &mut Session, ids: &[NodeId], n: usize) -> f64 { + let p: Value = json!({"ids": ids.iter().map(|id| id.0).collect::>(), "weight": 3}); + let runs = (0..iters()) + .map(|_| { + let mut r = Value::Null; + let t = ms(|| r = black_box(s.execute("stroke.set", &p).unwrap())); + assert_eq!(r["objects"], n, "{r}"); + s.execute("edit.undo", &json!({})).unwrap(); + t + }) + .collect(); + median(runs) +} + +fn bench(n: usize) { + println!("{n} paths in one group"); + let (doc, group, leaves) = document(n); + + // Each run merges `reps` times, on copies made before the clock starts, and gives the time of one. + let reps = (1_000_000 / n).max(1); + let time = |f: fn(Vec, Vec) -> Vec| -> (f64, Vec) { + let mut last = Vec::new(); + let runs = (0..iters()) + .map(|_| { + let mut work: Vec> = (0..reps).map(|_| leaves.clone()).collect(); + let mut done = Vec::with_capacity(reps); + let t = ms(|| { + for input in &mut work { + done.push(f(Vec::new(), black_box(std::mem::take(input)))); + } + }); + last = done.pop().unwrap(); + t / reps as f64 + }) + .collect(); + (median(runs), last) + }; + let (old, a) = time(listed); + let (new, b) = time(with_set); + assert_eq!(a, b, "both merges give the same list"); + assert_eq!(a, leaves); + row("target merge, list search", old); + row("target merge, set", new); + println!(" {:<52} {:>10.1}x", "ratio", old / new); + + let mut s = Session::new(); + s.add_document(doc, None); + row("stroke.set, whole command, the group named", whole_command(&mut s, &[group], n)); + row("stroke.set, whole command, every path named", whole_command(&mut s, &leaves, n)); +} + +fn main() { + println!("{}", if cpu_ns().is_some() { "thread CPU time, median of runs" } else { "wall time, median of runs" }); + for n in [2_000, 10_000, 20_000] { + bench(n); + } +} diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index d2e551e867..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 @@ -826,9 +837,11 @@ pub use addons::{fold_source, print_hidden}; /// Document Info's category titles and the Objects category's count labels. pub use docinfo::{CATEGORIES, OBJECT_LABELS}; pub use docmenu::guide_indexes; -pub(crate) use edit::{settle_interaction, typing_in_progress}; +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/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs index 88c601b16b..18374f8302 100644 --- a/crates/engine/src/cmd/colormgmt.rs +++ b/crates/engine/src/cmd/colormgmt.rs @@ -121,7 +121,7 @@ pub fn specs() -> Vec { "Separations Preview", [], None, - "{on?: bool, plates?: [names], toggle?: plate, only?: plate} Separations Preview: show the chosen plates (one plate = greyscale ink coverage) → {on, plates: [{name, spot, visible, rgb}]}", + "{on?: bool, plates?: [names], toggle?: plate, only?: plate, soloToggle?: plate (only that plate, or every plate when it is the only one shown)} Separations Preview: show the chosen plates (one plate = grayscale ink coverage) → {on, plates: [{name, spot, visible, rgb}]}", always, separations ), @@ -1055,6 +1055,13 @@ fn separations(s: &mut Session, p: &Value) -> Result { if let Some(n) = text_param(p, "only", C)? { v.separations = Some(vec![check(n)?]); } + // The panel's Alt-click on a plate's eye: that plate alone, or every plate when it already + // shows alone among the active document's plates. + if let Some(n) = text_param(p, "soloToggle", C)? { + let n = check(n)?; + let alone = v.separations.as_ref().is_some_and(|vis| all.iter().filter(|a| vis.contains(a)).eq([&n])); + v.separations = Some(if alone { all.clone() } else { vec![n] }); + } if let Some(n) = text_param(p, "toggle", C)? { let n = check(n)?; let vis = v.separations.get_or_insert_with(|| all.clone()); diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 013b373d19..803057885a 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -62,7 +62,7 @@ pub fn specs() -> Vec { "Circle Through Points", [], None, - "{points?: [[x, y], [x, y], [x, y]] (left out: the three selected anchor points, where a path selected whole counts all its anchors and selected segments' ends do not count)} → {id, cx, cy, radius}: a circle with the current paint whose edge passes through the three points, not pixel-aligned even while Align New Objects to Pixel Grid is on; two points that are the same or three on one line are an error, and nothing is drawn", + "{points?: [[x, y], [x, y]] or [[x, y], [x, y], [x, y]] (two: the ends of a diameter; left out: the two or three selected anchor points, where a path selected whole counts all its anchors and selected segments' ends do not count)} → {id, cx, cy, radius}: a circle with the current paint whose edge passes through the points, not pixel-aligned even while Align New Objects to Pixel Grid is on; two points that are the same, three on one line, or a circle reaching past the canvas are an error, and nothing is drawn", has_doc, circle_through_points ), @@ -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 ), @@ -413,16 +413,16 @@ fn ellipse(s: &mut Session, p: &Value) -> Result { add_art_turned(s, "Ellipse", path_kind(live.to_path(), Some(live)), rotation) } -/// A live ellipse whose edge passes through three points: `points`, or the three selected anchor -/// points ([`selected_anchor_points`]). One undo step, named as an Ellipse tool drag is. +/// A live ellipse whose edge passes through two or three points: `points`, or the two or three +/// selected anchor points ([`selected_anchor_points`]). Two points are the ends of a diameter. One +/// undo step, named as an Ellipse tool drag is. fn circle_through_points(s: &mut Session, p: &Value) -> Result { const C: &str = "shape.circleThroughPoints"; let points = match p.get("points").filter(|v| !v.is_null()) { - Some(v) => three_points(v).ok_or_else(|| bad(C, "`points` must be three [x, y] pairs of numbers"))?, - None => selected_anchor_points(s)?.ok_or_else(|| bad(C, "direct-select three anchor points, or give `points`"))?, + Some(v) => two_or_three_points(v).ok_or_else(|| bad(C, "`points` must be two or three [x, y] pairs of numbers"))?, + None => selected_anchor_points(s)?.ok_or_else(|| bad(C, "direct-select two or three anchor points, or give `points`"))?, }; - let [a, b, c] = points; - let (center, radius) = shapes::circle_through(a, b, c) + let (center, radius) = shapes::circle_through_points(&points) .ok_or_else(|| bad(C, "no circle passes through these points: two are the same or all three lie on one line"))?; let r = Rect::new(center.x - radius, center.y - radius, center.x + radius, center.y + radius); let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: Affine::translate(r.origin().to_vec2()) }; @@ -434,24 +434,25 @@ fn circle_through_points(s: &mut Session, p: &Value) -> Result { Ok(out) } -/// The three points `[[x, y], [x, y], [x, y]]` holds, each pair two finite numbers. -fn three_points(v: &Value) -> Option<[Point; 3]> { +/// The two or three points `[[x, y], [x, y]]` or `[[x, y], [x, y], [x, y]]` holds, each pair two +/// finite numbers. +fn two_or_three_points(v: &Value) -> Option> { let pair = |v: &Value| match v.as_array().map(Vec::as_slice) { Some([x, y]) => x.as_f64().zip(y.as_f64()).filter(|(x, y)| x.is_finite() && y.is_finite()).map(|(x, y)| Point::new(x, y)), _ => None, }; - match v.as_array().map(Vec::as_slice) { - Some([a, b, c]) => Some([pair(a)?, pair(b)?, pair(c)?]), + match v.as_array() { + Some(pairs) if matches!(pairs.len(), 2 | 3) => pairs.iter().map(pair).collect(), _ => None, } } -/// The positions of the selected anchor points, when there are exactly three. They are counted as +/// The positions of the selected anchor points, when there are two or three. They are counted as /// the other anchor commands count them ([`super::path::anchor_targets`]): a selected path with /// anchors picked by Direct Selection gives those, and a path selected whole gives all of its own. /// A selected segment's ends are not selected anchor points, so a selection with segments gives /// none; so does a selection holding an object that is not a path, or an anchor that is gone. -fn selected_anchor_points(s: &Session) -> Result> { +fn selected_anchor_points(s: &Session) -> Result>> { let st = s.doc()?; if st.selection.segments.values().any(|set| !set.is_empty()) { return Ok(None); @@ -472,10 +473,7 @@ fn selected_anchor_points(s: &Session) -> Result> { return Ok(None); } } - Ok(match points.as_slice() { - &[a, b, c] => Some([a, b, c]), - _ => None, - }) + Ok(matches!(points.len(), 2 | 3).then_some(points)) } /// The whole-number count `p` gives for `key` (`5` or `5.0`), or `default` when it is left out or @@ -942,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(), @@ -970,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}; @@ -991,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 }; @@ -1019,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(); @@ -1039,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/distortcmds.rs b/crates/engine/src/cmd/distortcmds.rs index 1e78f210e6..dc36e24380 100644 --- a/crates/engine/src/cmd/distortcmds.rs +++ b/crates/engine/src/cmd/distortcmds.rs @@ -16,7 +16,7 @@ use vectorcraft_tools::distort::{PinSet, arap, collect_points, mesh_for, project use super::edit::{duplicate_in, outermost, refuse_symbol_part, selected_roots}; use super::{ CommandSpec, Result, Session, bad, check_numbers, check_switches, cmd, f64_or, f64_req, finite_numbers, has_doc, has_selection, matrix_param, - named_id, named_ids, number_or, object_param, ok, point_indices, point_param, str_param, switch_or, targets, + named_id, named_ids, number_or, object_param, ok, point_indices, point_param, str_param, switch_or, targets, text_param, u64_req, }; use crate::EngineError; @@ -35,7 +35,7 @@ pub fn specs() -> Vec { "Width Point", [], None, - "{id, t: 0..1 (fraction of the path length), left, right: side widths in pt, index?: width point to edit or move, adjustAdjoining?: bool (the nearest points either side change their widths in proportion, using the sampled widths for a new point)} → {index}. Without index a point already at t is replaced; a point moved onto another one's t joins it as a discontinuous point (on the side it came from), so the width steps there. Creates a uniform profile first if needed", + "{id, t: 0..1 (fraction of the path length), left, right: side widths in pt, index?: width point to edit or move, adjustAdjoining?: bool (the nearest points either side change their widths in proportion, using the sampled widths for a new point), outIndex?, outLeft, outRight: the outgoing half of the discontinuous point whose incoming half is index, single?: \"incoming\" | \"outgoing\"} → {index}. Without index a point already at t is replaced; a point moved onto another one's t joins it as a discontinuous point (on the side it came from), so the width steps there. With outIndex both halves change in one step and keep their place (t must be theirs); adjustAdjoining then changes the nearest point before from the incoming half and the nearest point after from the outgoing half. single keeps only that half's widths, leaving one continuous point. Creates a uniform profile first if needed", has_doc, width_point_set ), @@ -214,6 +214,15 @@ fn uniform() -> WidthProfile { /// Width points closer than this (in t) are at the same place: a discontinuous point. const SAME_T: f64 = 1e-6; +/// The outgoing half of the discontinuous width point whose incoming half is point `a`: point `a` +/// and the next one are the two halves when they are the only points within 1e-6 (in t) of `a`'s +/// place. None when `a` is out of range or not such an incoming half. +pub fn width_point_pair(points: &[(f64, f64, f64)], a: usize) -> Option { + let t = points.get(a)?.0; + let at: Vec = (0..points.len()).filter(|i| (points[*i].0 - t).abs() <= SAME_T).collect(); + (at == [a, a + 1]).then_some(a + 1) +} + /// The stroke of `id` that width point commands edit (a compound path's for its members). fn stroke_mut(d: &mut Document, id: NodeId) -> Result<&mut vectorcraft_doc::StrokeLayer> { let id = stroke_owner(d, id); @@ -265,9 +274,9 @@ fn place(points: &mut Vec<(f64, f64, f64)>, mut pt: (f64, f64, f64), from_below: } /// Adjust Adjoining Width Points: point `i` changes from `old` to `new` widths, and the nearest -/// points at other positions either side change in proportion (by the same amount from zero). -fn adjust_adjoining(points: &mut [(f64, f64, f64)], i: usize, old: (f64, f64, f64), new: (f64, f64, f64)) { - let t = points[i].0; +/// points farther than [`SAME_T`] from place `t` on the sides `sides` names (before, after) +/// change in proportion (by the same amount from zero). +fn adjust_adjoining(points: &mut [(f64, f64, f64)], i: usize, t: f64, old: (f64, f64, f64), new: (f64, f64, f64), sides: [bool; 2]) { let scale = |v: f64, o: f64, n: f64| { let width = if o > 1e-9 { let product = v * n; @@ -284,8 +293,8 @@ fn adjust_adjoining(points: &mut [(f64, f64, f64)], i: usize, old: (f64, f64, f6 }; width.max(0.0) }; - let before = (0..i).rev().find(|j| (points[*j].0 - t).abs() > SAME_T); - let after = (i + 1..points.len()).find(|j| (points[*j].0 - t).abs() > SAME_T); + let before = (0..i).rev().find(|j| (points[*j].0 - t).abs() > SAME_T).filter(|_| sides[0]); + let after = (i + 1..points.len()).find(|j| (points[*j].0 - t).abs() > SAME_T).filter(|_| sides[1]); for j in before.into_iter().chain(after) { let q = &mut points[j]; (q.1, q.2) = (scale(q.1, old.1, new.1), scale(q.2, old.2, new.2)); @@ -303,6 +312,46 @@ fn same_points(a: Option<&WidthProfile>, b: Option<&WidthProfile>) -> bool { } } +/// Set both halves of the discontinuous point whose incoming half is `i` and outgoing half `j` to +/// the widths of `inc` and `out` (their places are ignored: the point keeps its place). With +/// `single` (`true` for the outgoing half) only that half's widths remain, as one continuous point. +/// With `adjust`, the nearest point before changes with the incoming half and the nearest point after +/// with the outgoing half, once each. → the index of the point (its incoming half). +fn set_pair( + points: &mut Vec<(f64, f64, f64)>, + (i, inc): (usize, (f64, f64, f64)), + (j, out): (usize, (f64, f64, f64)), + adjust: bool, + single: Option, +) -> Result { + const C: &str = "stroke.widthPoint.set"; + if width_point_pair(points, i) != Some(j) { + return Err(bad(C, "`index` and `outIndex` must be the two halves of one discontinuous width point")); + } + let at = points[i].0; + let (old_in, old_out) = (points[i], points[j]); + if (old_in.0 - inc.0).abs() > SAME_T { + return Err(bad(C, "a discontinuous width point keeps its place")); + } + let (new_in, new_out) = match single { + None => ((old_in.0, inc.1, inc.2), (old_out.0, out.1, out.2)), + Some(false) => ((old_in.0, inc.1, inc.2), (old_in.0, inc.1, inc.2)), + Some(true) => ((old_in.0, out.1, out.2), (old_in.0, out.1, out.2)), + }; + // Both halves measure their neighbors from the point's place, so a point within SAME_T of the + // outgoing half but not of that place is the point after the pair. + if adjust { + adjust_adjoining(points, i, at, old_in, new_in, [true, false]); + adjust_adjoining(points, j, at, old_out, new_out, [false, true]); + } + points[i] = new_in; + points[j] = new_out; + if single.is_some() { + points.remove(j); + } + Ok(i) +} + fn width_point_set(s: &mut Session, p: &Value) -> Result { const C: &str = "stroke.widthPoint.set"; let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?; @@ -312,6 +361,25 @@ fn width_point_set(s: &mut Session, p: &Value) -> Result { return Err(bad(C, "left/right must be non-negative widths")); } let adjust = switch_or(p, "adjustAdjoining", false, C)?; + let single = match text_param(p, "single", C)? { + None => None, + Some(side @ ("incoming" | "outgoing")) => Some(side == "outgoing"), + Some(_) => return Err(bad(C, "`single` must be `incoming` or `outgoing`")), + }; + // The outgoing half of a discontinuous point: its index and side widths (points). + // `single`, `outLeft` or `outRight` without `outIndex` is refused as a missing `outIndex`. + let out_widths = ["outLeft", "outRight"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())); + let out = match p.get("outIndex") { + None | Some(Value::Null) if single.is_none() && !out_widths => None, + _ => { + let j = usize::try_from(u64_req(p, "outIndex", C)?).map_err(|_| bad(C, "no such width point"))?; + let (l, r) = (f64_req(p, "outLeft", C)?, f64_req(p, "outRight", C)?); + if !(l.is_finite() && r.is_finite()) || l < 0.0 || r < 0.0 || l.max(r) > 1.0e5 { + return Err(bad(C, "left/right must be non-negative widths")); + } + Some((j, l, r)) + } + }; // When the profile comes out as it was, within a rounding error (1e-9), the document and its undo // history stay as they are. let mut pos = 0; @@ -324,11 +392,19 @@ fn width_point_set(s: &mut Session, p: &Value) -> Result { return Err(bad(C, "width factors must be finite")); } let mut prof = st.profile.take().unwrap_or_else(uniform); - pos = match point_index(p, &prof, C)? { - Some(i) => { + pos = match (point_index(p, &prof, C)?, out) { + (None, Some(_)) => return Err(bad(C, "missing index")), + (Some(i), Some((j, l, r))) => { + let out = (t, l / half, r / half); + if !out.1.is_finite() || !out.2.is_finite() { + return Err(bad(C, "width factors must be finite")); + } + set_pair(&mut prof.points, (i, pt), (j, out), adjust, single)? + } + (Some(i), None) => { let old = prof.points[i]; if adjust { - adjust_adjoining(&mut prof.points, i, old, pt); + adjust_adjoining(&mut prof.points, i, old.0, old, pt, [true, true]); } if (old.0 - t).abs() <= SAME_T { // Widths only: it keeps its place (and its side of a discontinuous point). @@ -339,12 +415,12 @@ fn width_point_set(s: &mut Session, p: &Value) -> Result { place(&mut prof.points, pt, old.0 < t) } } - None => { + (None, None) => { let old = adjust.then(|| prof.at(t)); prof.points.retain(|q| (q.0 - t).abs() > SAME_T); let i = place(&mut prof.points, pt, true); if let Some((left, right)) = old { - adjust_adjoining(&mut prof.points, i, (t, left, right), pt); + adjust_adjoining(&mut prof.points, i, pt.0, (t, left, right), pt, [true, true]); } i } 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/draw2/commands.rs b/crates/engine/src/cmd/draw2/commands.rs index e368473c4f..c44aa1b24a 100644 --- a/crates/engine/src/cmd/draw2/commands.rs +++ b/crates/engine/src/cmd/draw2/commands.rs @@ -11,7 +11,7 @@ pub fn specs() -> Vec { "Pencil", [], None, - "{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise, 0..360: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks. A pressure, tilt or rotation outside its range, or a point array of more than six numbers, is an error), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\" (default) | \"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end?: \"end\" (default) | \"start\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it. Any other style, extend end or connect end is an error, and nothing changes", + "{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise, 0..360: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks. A pressure, tilt or rotation outside its range, or a point array of more than six numbers, is an error), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\" (default) | \"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end?: \"end\" (default) | \"start\"}, connect?: {id, end: \"start\"|\"end\"} (only with extend), redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it. Any other style, extend end or connect end, connect without extend, and a connect that names no other path with an open end are errors, a stroke of one point included, and nothing changes", has_doc, freehand ), diff --git a/crates/engine/src/cmd/draw2/freehand.rs b/crates/engine/src/cmd/draw2/freehand.rs index 467bb091b3..607abf8f03 100644 --- a/crates/engine/src/cmd/draw2/freehand.rs +++ b/crates/engine/src/cmd/draw2/freehand.rs @@ -213,7 +213,11 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s let label = if brush || brush_name.is_some() { "Paintbrush" } else { "Pencil" }; let keep_selected = switch_or(p, "keepSelected", true, C)?; let filled = switch_or(p, "fill", false, C)?; - if let Some(ext) = p.get("extend").filter(|v| !v.is_null()) { + let extend = p.get("extend").filter(|v| !v.is_null()); + if extend.is_none() && p.get("connect").is_some_and(|v| !v.is_null()) { + return Err(bad(C, "connect needs extend")); + } + if let Some(ext) = extend { let id = object_param(ext, "id", C)?.ok_or_else(|| bad(C, "extend needs id"))?; let at_start = match ext.get("end").filter(|v| !v.is_null()).map(Value::as_str) { None | Some(Some("end")) => false, @@ -238,26 +242,9 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s }; let Some(p0) = pts.first_mut() else { return Err(bad(C, "needs points")) }; *p0 = end; - if pts.len() < 2 { - // No stroke to add: the brush alone changes, when it is not the path's already, and the - // path is selected or deselected as a longer continuation leaves it. - if let Some(name) = brush_name - && s.doc()?.doc.node(target).and_then(|n| n.appearance.stroke()).is_some_and(|st| st.brush.as_deref() != Some(name)) - { - s.edit("Paintbrush", |d, sel| { - set_brush(d, target, name); - if keep_selected { - sel.set([id]); - } else { - sel.remove(id); - } - Ok(()) - })?; - } - return Ok(json!({ "id": id.0 })); - } // A stroke that ends on an open end of another path connects the two: (that path, its last // open subpath, that subpath starting at the end the stroke ends on, it ends at its end). + // It is checked before a stroke of one point returns, so a bad `connect` is refused there too. let connect = match p.get("connect").filter(|v| !v.is_null()) { Some(cn) => { let other = object_param(cn, "id", C)?.ok_or_else(|| bad(C, "connect needs id"))?; @@ -280,6 +267,24 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s } None => None, }; + if pts.len() < 2 { + // No stroke to add: the brush alone changes, when it is not the path's already, and the + // path is selected or deselected as a longer continuation leaves it. + if let Some(name) = brush_name + && s.doc()?.doc.node(target).and_then(|n| n.appearance.stroke()).is_some_and(|st| st.brush.as_deref() != Some(name)) + { + s.edit("Paintbrush", |d, sel| { + set_brush(d, target, name); + if keep_selected { + sel.set([id]); + } else { + sel.remove(id); + } + Ok(()) + })?; + } + return Ok(json!({ "id": id.0 })); + } // `closed`, when given, says whether the stroke closes the path: the Pencil and the // Paintbrush send it, by their Close Paths When Ends Are Within and Alt at the release. // Left out, an extending stroke that ends within four Fidelities of the path's other end diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index fbf5deb568..3b47fedb41 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -6,6 +6,7 @@ use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_doc::{Document, Node, NodeId, NodeKind, RulerMode, Unit}; use vectorcraft_geom::{Affine, Point, Vec2}; +use vectorcraft_tools::distort::perspective::{PerspectiveGrid, Plane}; use super::clipboard::SwatchChoices; use super::{ @@ -713,6 +714,85 @@ pub(crate) fn settle_interaction(s: &mut Session) -> Result<()> { Ok(()) } +/// The document state that commands also change without an undo step: the perspective grid's view +/// options (whether it shows, Lock Grid, Lock Station Point, Snap to Grid and Show Rulers), its +/// active plane, the grid preferences, the export settings, and the current brush and symbol. Each +/// undo and redo step keeps it as the document on its other side had it +/// ([`crate::HistoryEntry::unrecorded`]). +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct Unrecorded { + grid: vectorcraft_doc::GridPrefs, + export_settings: serde_json::Map, + brush: Option, + symbol: Option, + options: [bool; 5], + plane: Plane, +} + +impl Unrecorded { + pub(crate) fn of(d: &Document) -> Self { + let g = PerspectiveGrid::current(d); + Unrecorded { + grid: d.grid.clone(), + export_settings: d.export_settings.clone(), + brush: d.unknown.get(vectorcraft_brush::CURRENT_KEY).cloned(), + symbol: d.unknown.get(super::brushsym::CURRENT_SYMBOL).cloned(), + options: [g.visible, g.locked, g.lock_station, g.snap, g.rulers], + plane: g.plane, + } + } +} + +/// Undo and redo bring back `d`; `step` is that state as the document on the step's other side had +/// it. A part the step did not change (`d` has it as `step` does) stays as it is in `now`, the +/// document before the undo or redo, since it changed after the step without an undo step. A part +/// the step changed comes back with `d`. A current brush or symbol that `d` does not hold also +/// comes back with `d`. The point Automatic Plane Positioning holds comes back with `d`, and is let go when the +/// active plane kept is not the one it holds. +fn keep_unrecorded(now: &Document, step: &Unrecorded, d: &mut Arc) { + fn pick(back: &T, step: &T, now: &T) -> T { + if back == step { now.clone() } else { back.clone() } + } + let back = Unrecorded::of(d); + let cur = Unrecorded::of(now); + let mut want = Unrecorded { + grid: pick(&back.grid, &step.grid, &cur.grid), + export_settings: pick(&back.export_settings, &step.export_settings, &cur.export_settings), + brush: pick(&back.brush, &step.brush, &cur.brush), + symbol: pick(&back.symbol, &step.symbol, &cur.symbol), + options: std::array::from_fn(|i| pick(&back.options[i], &step.options[i], &cur.options[i])), + plane: pick(&back.plane, &step.plane, &cur.plane), + }; + if want.brush != back.brush && want.brush.as_ref().and_then(Value::as_str).is_some_and(|n| vectorcraft_brush::find(d, n).is_none()) { + want.brush = back.brush.clone(); + } + if want.symbol != back.symbol && want.symbol.as_ref().and_then(Value::as_str).is_some_and(|n| !d.symbols.iter().any(|s| s.name == n)) { + want.symbol = back.symbol.clone(); + } + if want == back { + return; + } + let m = Arc::make_mut(d); + for (key, v) in [(vectorcraft_brush::CURRENT_KEY, &want.brush), (super::brushsym::CURRENT_SYMBOL, &want.symbol)] { + match v { + Some(v) => m.unknown.insert(key.into(), v.clone()), + None => m.unknown.remove(key), + }; + } + if (want.options, want.plane) != (back.options, back.plane) { + let mut g = PerspectiveGrid::current(m); + [g.visible, g.locked, g.lock_station, g.snap, g.rulers] = want.options; + if g.plane != want.plane { + g.plane = want.plane; + g.inferred = None; + } + g.keep_positioning_valid(); + super::distortcmds::store_grid(m, &g); + } + m.grid = want.grid; + m.export_settings = want.export_settings; +} + fn undo(s: &mut Session, _: &Value) -> Result { settle_interaction(s)?; let menu = s.menu.clone(); @@ -723,6 +803,7 @@ fn undo(s: &mut Session, _: &Value) -> Result { let editing = st.doc.mask_edit.map(|m| m.layer); let editing_symbol = st.doc.symbol_edit.clone(); let doc = std::mem::replace(&mut st.doc, e.doc); + keep_unrecorded(&doc, &e.unrecorded, &mut st.doc); let selection = std::mem::replace(&mut st.selection, Arc::unwrap_or_clone(e.selection)); let selection = shared_selection(selection, st.history.redo.last()); let mut turned = crate::HistoryEntry::turned(e.label, doc, selection, &st.doc, costs); @@ -758,6 +839,7 @@ fn redo(s: &mut Session, _: &Value) -> Result { let editing = st.doc.mask_edit.map(|m| m.layer); let editing_symbol = st.doc.symbol_edit.clone(); let doc = std::mem::replace(&mut st.doc, e.doc); + keep_unrecorded(&doc, &e.unrecorded, &mut st.doc); let selection = std::mem::replace(&mut st.selection, Arc::unwrap_or_clone(e.selection)); let selection = shared_selection(selection, st.history.undo.last()); let mut turned = crate::HistoryEntry::turned(e.label, doc, selection, &st.doc, costs); @@ -1076,8 +1158,10 @@ fn cut(s: &mut Session, p: &Value) -> Result { /// Select every surviving piece while retaining intentional compound-path structure. /// `roots` contains the copied targets: whole-object roots are removed in full, while partial paths /// lose only the copied geometry. An exhausted partial path is removed, along with its compound -/// parent if now empty; layers remain. Returns JSON `null` on success, replacing direct-selection -/// references with surviving object IDs. +/// parent if now empty; a compound left with one member stays a compound path, as after Clear; +/// layers remain. Removed and replaced roots go through one [`super::pathops::Beside`], which +/// rebuilds each parent's children once when the roots are separate. Returns JSON `null` on +/// success, replacing direct-selection references with surviving object IDs. fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result { let st = s.doc()?; let sel = st.selection.clone(); @@ -1085,13 +1169,18 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result { // The selected ruler guides were copied too (#3226): they go in the same undo step. let gone = selection.guides.clone(); d.retain_guides(selection, |g| !g.id.is_some_and(|id| gone.contains(&id))); + // The compound paths that hold a root; one left with no members goes too. + let compounds: BTreeSet = roots + .iter() + .filter_map(|id| d.parent_of(*id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })))) + .collect(); let mut survivors = vec![]; let mut pieces = super::pathops::Beside::replacing(d, roots); for id in roots { let Some(node) = d.node(*id) else { continue }; let has_direct = sel.anchors.contains_key(id) || sel.segments.contains_key(id); if !has_direct || node.path_data().is_none() { - remove_leaving_no_empty_compound(d, *id)?; + pieces.put(d, *id, vec![])?; continue; } let original = super::path::deletion_source(d, *id)?; @@ -1114,12 +1203,14 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result { } subpaths.retain(|sp| sp.anchors.len() >= 2); if subpaths.is_empty() { - remove_leaving_no_empty_compound(d, *id)?; + pieces.put(d, *id, vec![])?; } else { survivors.extend(super::path::replace_deleted_pieces(d, &mut pieces, original, subpaths)?); } } pieces.finish(d)?; + let emptied: Vec = compounds.into_iter().filter(|p| d.node(*p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty()))).collect(); + super::pathops::remove_each(d, &emptied)?; selection.set(survivors); selection.anchors.clear(); selection.segments.clear(); @@ -1128,19 +1219,6 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result { ok() } -/// Remove object `id`, and the compound path that held it when it was the compound's last member. -/// A compound left with one member stays a compound path, as after Clear. -fn remove_leaving_no_empty_compound(d: &mut Document, id: NodeId) -> Result<()> { - let parent = d.parent_of(id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. }))); - d.remove(id)?; - if let Some(p) = parent - && d.node(p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())) - { - d.remove(p)?; - } - Ok(()) -} - fn clear(s: &mut Session, p: &Value) -> Result { let guides = switch_or(p, "guides", false, "edit.clear")?; let explicit = if p.get("ids").is_some() { Some(checked_ids_param(s, p, "ids", "edit.clear")?) } else { None }; @@ -1751,3 +1829,6 @@ pub(crate) fn copy_above(d: &mut Document, roots: &[NodeId], mut change: impl Fn pub(crate) fn arc_nodes(v: Vec) -> Vec> { v.into_iter().map(Arc::new).collect() } + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/edit/tests.rs b/crates/engine/src/cmd/edit/tests.rs new file mode 100644 index 0000000000..8146bec6c2 --- /dev/null +++ b/crates/engine/src/cmd/edit/tests.rs @@ -0,0 +1,343 @@ +//! Cut with direct-selected anchors removes the objects selected whole and the paths it empties +//! through one [`Beside`](super::super::pathops::Beside), and leaves the document, the selection, +//! the clipboard and the undo history exactly as removing each of them on its own does. + +use std::collections::BTreeSet; +use std::time::{Duration, Instant}; + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, NodeId, NodeKind, tree_walks}; + +use super::*; +use crate::tests_large_edits::{session, square}; + +/// Cut's removal with every root selected whole or emptied taken out by its own +/// [`Document::remove`], and its compound path removed right after when that left it empty. The +/// tests compare [`cut_direct_selection`] with it. +fn cut_one_at_a_time(s: &mut Session, roots: &[NodeId]) -> Result { + let st = s.doc()?; + let sel = st.selection.clone(); + s.edit("Cut", |d, selection| { + let gone = selection.guides.clone(); + d.retain_guides(selection, |g| !g.id.is_some_and(|id| gone.contains(&id))); + let mut survivors = vec![]; + let mut pieces = super::super::pathops::Beside::replacing(d, roots); + for id in roots { + let Some(node) = d.node(*id) else { continue }; + let has_direct = sel.anchors.contains_key(id) || sel.segments.contains_key(id); + if !has_direct || node.path_data().is_none() { + remove_one(d, *id)?; + continue; + } + let original = super::super::path::deletion_source(d, *id)?; + let seg_refs = sel.segments.get(id); + let anchor_refs = sel.anchors.get(id); + let mut subpaths = Vec::new(); + let owned = std::mem::take(&mut super::super::path::path_mut(d, *id)?.subpaths); + for (si, sp) in owned.into_iter().enumerate() { + let cuts = super::super::clipboard::subpath_selected_segments(&sp, si, seg_refs, anchor_refs); + if cuts.is_empty() { + subpaths.push(sp); + } else if seg_refs.is_some_and(|segments| !segments.is_empty()) { + subpaths.extend(super::super::path::without_segments(sp, &cuts)); + } else { + let gone: BTreeSet = anchor_refs.into_iter().flat_map(|refs| super::super::path::subpath_refs(refs, si)).collect(); + subpaths.extend(super::super::path::without_anchors(sp, &gone)); + } + } + subpaths.retain(|sp| sp.anchors.len() >= 2); + if subpaths.is_empty() { + remove_one(d, *id)?; + } else { + survivors.extend(super::super::path::replace_deleted_pieces(d, &mut pieces, original, subpaths)?); + } + } + pieces.finish(d)?; + selection.set(survivors); + selection.anchors.clear(); + selection.segments.clear(); + Ok(()) + })?; + ok() +} + +/// Removes object `id`, and the compound path that held it when it was the compound's last member. +fn remove_one(d: &mut Document, id: NodeId) -> Result<()> { + let parent = d.parent_of(id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. }))); + d.remove(id)?; + if let Some(p) = parent + && d.node(p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())) + { + d.remove(p)?; + } + Ok(()) +} + +/// Cut as `edit.cut` runs it for a direct selection, with [`cut_one_at_a_time`] in place of +/// [`cut_direct_selection`]. +fn reference_cut(s: &mut Session) { + let (direct, roots) = copy_cut_targets(s).unwrap(); + assert!(direct, "the selection is a direct selection"); + copy(s, &json!({})).unwrap(); + cut_one_at_a_time(s, &roots).unwrap(); +} + +fn run(s: &mut Session, cmd: &str, p: Value) -> Value { + s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}")) +} + +/// Selects `whole` as objects, then anchors `anchors` of each path in `partial`. +fn select_direct(s: &mut Session, whole: &[NodeId], partial: &[(NodeId, Value)]) { + run(s, "select.set", json!({"ids": whole.iter().map(|id| id.0).collect::>()})); + for (id, anchors) in partial { + run(s, "select.anchors", json!({"id": id.0, "anchors": anchors, "mode": "add"})); + } +} + +/// The ids of every node of the document, depth first, with the depth of each. +fn tree(d: &Document) -> Vec<(usize, NodeId)> { + fn walk(n: &vectorcraft_doc::Node, depth: usize, out: &mut Vec<(usize, NodeId)>) { + out.push((depth, n.id)); + for c in n.children().into_iter().flatten() { + walk(c, depth + 1, out); + } + } + let mut out = vec![]; + for l in &d.layers { + walk(l, 0, &mut out); + } + out +} + +/// Whether `a` and `b` hold the same document, selection, clipboard and number of undo and redo +/// steps. +fn assert_same(a: &Session, b: &Session, when: &str) { + let (x, y) = (a.doc().unwrap(), b.doc().unwrap()); + assert_eq!(tree(&x.doc), tree(&y.doc), "{when}: the tree"); + assert!(*x.doc == *y.doc, "{when}: the document"); + assert_eq!(x.selection, y.selection, "{when}: the selection"); + // Each session's document has its own uid; the clipboard names the one it came from. + assert_eq!(a.clipboard.source_doc.is_some(), b.clipboard.source_doc.is_some(), "{when}: the clipboard's source"); + let unsourced = |c: &Clipboard| Clipboard { source_doc: None, ..c.clone() }; + assert!(unsourced(&a.clipboard) == unsourced(&b.clipboard), "{when}: the clipboard"); + assert_eq!(x.history.undo.len(), y.history.undo.len(), "{when}: the undo steps"); + assert_eq!(x.history.redo.len(), y.history.redo.len(), "{when}: the redo steps"); +} + +/// Runs `edit.cut` on one session that `make` builds and [`reference_cut`] on another, and checks +/// that both hold the same after the Cut, after Undo and after Redo. Returns the first session after +/// the Cut. +fn same_as_one_at_a_time(make: impl Fn() -> Session) -> Session { + let (mut a, mut b) = (make(), make()); + let before = a.doc().unwrap().doc.clone(); + assert_same(&a, &b, "before"); + run(&mut a, "edit.cut", json!({})); + reference_cut(&mut b); + assert_same(&a, &b, "Cut"); + let after = a.doc().unwrap().doc.clone(); + run(&mut a, "edit.undo", json!({})); + run(&mut b, "edit.undo", json!({})); + assert_same(&a, &b, "Undo"); + assert!(*a.doc().unwrap().doc == *before, "Undo gives back the document"); + run(&mut a, "edit.redo", json!({})); + run(&mut b, "edit.redo", json!({})); + assert_same(&a, &b, "Redo"); + assert!(*a.doc().unwrap().doc == *after, "Redo gives back the Cut"); + run(&mut a, "edit.undo", json!({})); + run(&mut a, "edit.redo", json!({})); + a +} + +/// A new document; [`rect`] adds squares to it. +fn new_doc() -> Session { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 800, "height": 600})); + s +} + +/// Adds a 10 pt square to the current layer, 20 pt right of the last one. +fn rect(s: &mut Session) -> NodeId { + let x = 20.0 * s.doc().unwrap().doc.node_count() as f64; + NodeId(run(s, "shape.rectangle", json!({"x": x, "y": 10, "width": 10, "height": 10}))["id"].as_u64().unwrap()) +} + +/// Makes a compound path of `ids` and returns it with its members in order. +fn compound(s: &mut Session, ids: &[NodeId]) -> (NodeId, Vec) { + run(s, "select.set", json!({"ids": ids.iter().map(|id| id.0).collect::>()})); + let c = NodeId(run(s, "object.compoundPath.make", json!({}))["id"].as_u64().unwrap()); + let members = s.doc().unwrap().doc.node(c).unwrap().children().unwrap().iter().map(|m| m.id).collect(); + (c, members) +} + +/// Anchors 0 to 2 of a square: Cut leaves it no segment, so it is removed. +fn three_anchors() -> Value { + json!([[0, 0], [0, 1], [0, 2]]) +} + +/// Anchors 0 and 1 of a square: Cut keeps its other three sides. +fn two_anchors() -> Value { + json!([[0, 0], [0, 1]]) +} + +/// The compound path whose members are cut one whole and one emptied goes with them; the other +/// compound path keeps its one member left, as a compound path. +#[test] +fn cut_removes_a_compound_whose_members_all_go_and_keeps_one_with_one_member_left() { + let make = || { + let mut s = new_doc(); + let first = [(); 2].map(|()| rect(&mut s)); + let (gone, gone_members) = compound(&mut s, &first); + let second = [(); 3].map(|()| rect(&mut s)); + let (kept, kept_members) = compound(&mut s, &second); + let other = rect(&mut s); + select_direct( + &mut s, + &[gone_members[0], kept_members[0]], + &[(gone_members[1], three_anchors()), (kept_members[1], three_anchors()), (other, two_anchors())], + ); + (s, gone, kept, kept_members[2], other) + }; + let s = same_as_one_at_a_time(|| make().0); + let (_, gone, kept, left, other) = make(); + let d = &s.doc().unwrap().doc; + assert!(d.node(gone).is_none(), "the compound path whose members all went is removed"); + let kept = d.node(kept).expect("the compound path with a member left stays"); + assert!(matches!(kept.kind, NodeKind::Compound { .. })); + assert_eq!(kept.children().unwrap().iter().map(|m| m.id).collect::>(), [left]); + assert_eq!(s.doc().unwrap().selection.objects, [other], "the cut square's other sides stay selected"); +} + +/// Objects inside two groups and on the layer, removed whole, emptied or cut apart between kept +/// siblings, keep the order and ids that removing them one at a time leaves. +#[test] +fn cut_inside_groups_keeps_the_order_and_ids_of_removing_one_at_a_time() { + let make = || { + let mut s = new_doc(); + let a = [(); 4].map(|()| rect(&mut s)); + run(&mut s, "select.set", json!({"ids": a.iter().map(|id| id.0).collect::>()})); + run(&mut s, "object.group", json!({})); + let b = [(); 4].map(|()| rect(&mut s)); + run(&mut s, "select.set", json!({"ids": b.iter().map(|id| id.0).collect::>()})); + run(&mut s, "object.group", json!({})); + let c = [(); 4].map(|()| rect(&mut s)); + select_direct( + &mut s, + &[a[0], a[2], b[3], c[1]], + &[(a[1], two_anchors()), (b[0], three_anchors()), (b[2], two_anchors()), (c[3], three_anchors())], + ); + s + }; + let s = same_as_one_at_a_time(make); + assert_eq!(s.doc().unwrap().selection.objects.len(), 2, "the two squares cut apart stay selected"); +} + +/// Selected ruler guides go with the objects, in the Cut's undo step. +#[test] +fn cut_removes_the_selected_guides_with_the_objects() { + let make = || { + let mut s = new_doc(); + let [a, b, c] = [(); 3].map(|()| rect(&mut s)); + run(&mut s, "guide.add", json!({"vertical": true, "pos": 30})); + run(&mut s, "guide.add", json!({"vertical": false, "pos": 40})); + select_direct(&mut s, &[a, c], &[(b, two_anchors())]); + run(&mut s, "guide.select", json!({"indexes": [1], "toggle": true})); + s + }; + let s = same_as_one_at_a_time(make); + assert_eq!(s.doc().unwrap().doc.ruler_guides().len(), 1, "the selected guide is removed"); + assert_eq!(s.clipboard.guides.len(), 1, "the selected guide is on the clipboard"); +} + +/// Roots that are not separate (one inside another) are removed one at a time, as before. +#[test] +fn cut_of_roots_inside_another_root_matches_removing_one_at_a_time() { + let make = || { + let mut s = new_doc(); + let a = [(); 3].map(|()| rect(&mut s)); + run(&mut s, "select.set", json!({"ids": a.iter().map(|id| id.0).collect::>()})); + let group = NodeId(run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap()); + let b = rect(&mut s); + select_direct(&mut s, &[group, b], &[(a[1], two_anchors())]); + (s, vec![a[1], group, b]) + }; + let (mut x, roots) = make(); + let (mut y, _) = make(); + copy(&mut x, &json!({})).unwrap(); + copy(&mut y, &json!({})).unwrap(); + cut_direct_selection(&mut x, &roots).unwrap(); + cut_one_at_a_time(&mut y, &roots).unwrap(); + assert_same(&x, &y, "Cut"); +} + +/// One layer of 10,000 squares with every fifth of the first 10,000 selected whole (2,000) and +/// anchors 0 and 1 of the square after them picked. +fn many() -> Session { + let mut s = session(10_001, square); + let ids = crate::tests_large_edits::layer(&s, 0); + let whole: Vec = ids.iter().take(10_000).step_by(5).copied().collect(); + select_direct(&mut s, &whole, &[(ids[10_000], two_anchors())]); + s +} + +/// The tree walks [`tree_walks`] counts while `f` runs on `s`. +fn walks(s: &mut Session, f: impl FnOnce(&mut Session)) -> u64 { + let before = tree_walks(); + f(s); + tree_walks() - before +} + +/// Cut of 2,000 objects selected whole among 10,000, with a direct selection, walks the document's +/// tree a few times, where removing them one at a time walks it several times for each object. +#[test] +fn direct_selection_cut_of_2000_of_10000_objects_takes_few_tree_walks() { + let s = same_as_one_at_a_time(many); + assert_eq!(crate::tests_large_edits::layer(&s, 0).len(), 8_001); + let (mut a, mut b) = (many(), many()); + let batched = walks(&mut a, |s| { + run(s, "edit.cut", json!({})); + }); + let one_at_a_time = walks(&mut b, reference_cut); + println!("tree walks: Cut {batched}, one at a time {one_at_a_time}"); + assert!(batched <= 64, "Cut walked the document's tree {batched} times"); + assert!(one_at_a_time >= 4 * batched.max(1), "one at a time walked it {one_at_a_time} times, Cut {batched}"); +} + +/// This thread's CPU time, where the system reports it (`/proc/thread-self/schedstat` on Linux). +fn cpu_time() -> Option { + let stat = std::fs::read_to_string("/proc/thread-self/schedstat").ok()?; + stat.split_whitespace().next()?.parse().ok().map(Duration::from_nanos) +} + +/// The middle of `v`. +fn median(mut v: Vec) -> Duration { + v.sort_unstable(); + v[v.len() / 2] +} + +/// Times Cut of [`many`] and [`reference_cut`] seven times each, in turn, and prints every run's +/// CPU and wall-clock time with the medians. Run it with +/// `cargo test --release -p vectorcraft-engine --lib -- --ignored --nocapture direct_selection_cut_timing`. +#[test] +#[ignore = "timing; prints the numbers"] +fn direct_selection_cut_timing() { + let mut runs: [(Vec, Vec); 2] = Default::default(); + for round in 0..7 { + for (k, (cpu, wall)) in runs.iter_mut().enumerate() { + let mut s = many(); + let (c0, w0) = (cpu_time(), Instant::now()); + if k == 0 { + reference_cut(&mut s); + } else { + run(&mut s, "edit.cut", json!({})); + } + let w = w0.elapsed(); + let c = c0.zip(cpu_time()).map(|(a, b)| b.saturating_sub(a)).unwrap_or(w); + println!("round {round} {}: cpu {c:?}, wall {w:?}", ["one at a time", "Cut"][k]); + cpu.push(c); + wall.push(w); + } + } + for (k, (cpu, wall)) in runs.into_iter().enumerate() { + println!("median {}: cpu {:?}, wall {:?}", ["one at a time", "Cut"][k], median(cpu), median(wall)); + } +} diff --git a/crates/engine/src/cmd/effectcmd/graphics.rs b/crates/engine/src/cmd/effectcmd/graphics.rs index e80c1b2d36..868f6f5c5c 100644 --- a/crates/engine/src/cmd/effectcmd/graphics.rs +++ b/crates/engine/src/cmd/effectcmd/graphics.rs @@ -28,7 +28,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), 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 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 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) or Revolve; 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), 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 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 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) or Revolve; one undo step → {ids, graphic}", has_doc, map_graphic ), @@ -113,22 +113,32 @@ 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))); } 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 a9d3a754ce..35fd4cc893 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.rs b/crates/engine/src/cmd/fileio.rs index 86c72dec0e..cd6ec30f0d 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -65,6 +65,7 @@ pub mod zip; use serde_json::{Value, json}; +pub(crate) use action_batch::action_step; pub use action_batch::batch_overwrites_one_file; pub use dxf::{UNSUPPORTED, Unsupported, unsupported}; pub use encode::{ @@ -95,7 +96,7 @@ pub use naming::{NameParts as FileNameParts, parse_date as parse_file_date, rend pub(crate) use native::preview_png; pub use native::with_compression_pref; pub(crate) use pdfimport::opened_page_document; -pub use pdfimport::{LoadOptions, page_document}; +pub use pdfimport::{LoadOptions, page_document, pages_can_link}; pub(crate) use psdlayers::import_active as psd_layers; pub use psdlayers::{PsdInfo, info as psd_info}; pub(crate) use psdslices::over as psd_slices; 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/action_batch.rs b/crates/engine/src/cmd/fileio/action_batch.rs index 4e99f4ee3e..aa3be78e2a 100644 --- a/crates/engine/src/cmd/fileio/action_batch.rs +++ b/crates/engine/src/cmd/fileio/action_batch.rs @@ -54,24 +54,19 @@ pub(super) fn action_batch(s: &mut Session, p: &Value) -> Result { } for (i, c) in cmds.iter().enumerate() { let id = c.get("command").and_then(Value::as_str).unwrap_or(""); + let refuse = |reason: &str| bad(C, action_step(i, id, reason)); if id.is_empty() { - return Err(bad(C, format!("commands[{i}]: missing `command`"))); + return Err(refuse("missing `command`")); } if id == "command.batch" || id == "action.batch" { - return Err(bad(C, "batches cannot nest")); + return Err(refuse("batches cannot nest")); } // `command.batch` refuses the batch when it reaches this step, which would fail every file or data set it plays. if id == "prefs.import" { - return Err(bad(C, format!("commands[{i}]: `prefs.import` runs on its own, not as a batch step"))); + return Err(refuse("`prefs.import` runs on its own, not as a batch step")); } if find_command(id).is_none() { - return Err(bad( - C, - match super::super::params::nearest_command(id) { - Some(near) => format!("commands[{i}]: unknown command `{id}`; did you mean `{near}`?"), - None => format!("commands[{i}]: unknown command `{id}`"), - }, - )); + return Err(refuse(&super::super::params::unknown_command(id).to_string())); } } // Every option is checked before the destination folder is made. @@ -160,7 +155,7 @@ pub fn batch_overwrites_one_file(s: &Session, p: &Value) -> bool { Some(f) => own_format.is_some_and(|own| super::format(f).is_some_and(|f| f.id == own)), }; match c.get("command").and_then(Value::as_str).unwrap_or("") { - "document.save" | "file.save" => !save && (path || own_file()), + "document.save" => !save && (path || own_file()), "file.saveAs" => !save && path, "file.saveCopy" | "file.saveAsTemplate" => path, "document.export" | "document.exportSelection" => !export && path, @@ -184,7 +179,7 @@ fn saves_move_to_each_file(steps: &[Value], redirected: bool) -> bool { /// in the destination folder when `redirected`) and makes that file the document's own: a save in /// the native template format writes a copy and leaves the document's file as it was. fn retargeting_save(c: &Value, redirected: bool) -> bool { - if !matches!(c.get("command").and_then(Value::as_str), Some("document.save" | "file.save" | "file.saveAs")) { + if !matches!(c.get("command").and_then(Value::as_str), Some("document.save" | "file.saveAs")) { return false; } let params = c.get("params"); @@ -219,7 +214,7 @@ fn batch_folder(s: &mut Session, cmd: &str, p: &Value, override_open: bool, run: // open, so its artboard files count ([`dataset_output_paths`]). No output takes the name of a // source file in the destination folder, other than that file's own output, or of a subfolder // of the destination folder that holds source files. - let (steps, places) = filter_steps(run.steps, override_open, false); + let (steps, places) = filter_steps(run.steps, override_open); let run = Run { steps: &steps, ..*run }; let in_dest: Vec> = files.iter().map(|path| name_in_folder(path, run.dest_folder)).collect(); let mut picker = @@ -272,7 +267,7 @@ fn batch_datasets(s: &mut Session, cmd: &str, run: &Run<'_>) -> Result { } let doc_stem = st.path.as_deref().and_then(|p| std::path::Path::new(p).file_stem().and_then(|s| s.to_str())).unwrap_or("Untitled").to_string(); let stems = dataset_stems(&names, &doc_stem, run.dataset_file_naming, run, &st.doc)?; - let (steps, places) = filter_steps(run.steps, true, false); + let (steps, places) = filter_steps(run.steps, true); let run = Run { steps: &steps, ..*run }; let mut processed = Vec::new(); let mut failed = 0usize; @@ -353,22 +348,13 @@ impl StemPicker { } } -/// Drop Open (and optionally Close) steps when the batch supplies the file itself → the steps that -/// stay, and the index of each in `cmds`. +/// Drop the `document.open` steps when `drop_open` (the batch opens each source file itself) → the +/// steps that stay, and the index of each in `cmds`. #[cfg(not(target_arch = "wasm32"))] -fn filter_steps(cmds: &[Value], drop_open: bool, drop_close: bool) -> (Vec, Vec) { +fn filter_steps(cmds: &[Value], drop_open: bool) -> (Vec, Vec) { cmds.iter() .enumerate() - .filter(|(_, c)| { - let id = c.get("command").and_then(Value::as_str).unwrap_or(""); - if drop_open && matches!(id, "document.open" | "file.open") { - return false; - } - if drop_close && matches!(id, "file.close" | "document.close") { - return false; - } - true - }) + .filter(|(_, c)| !(drop_open && c.get("command").and_then(Value::as_str) == Some("document.open"))) .map(|(i, c)| (c.clone(), i)) .unzip() } @@ -385,12 +371,24 @@ fn play_steps(s: &mut Session, run: &Run<'_>, places: &[usize], commands: Vec EngineError::Other(format!("action step {} (`{id}`) failed: {reason}", place + 1)), + Some(&place) if same => EngineError::Other(action_step(place, id, reason)), _ => e, } }) } +/// The text naming the member at `index` of an `action.batch`'s `commands`, counted from 1, with +/// its command id when it has one, and `reason`: ``action step 2 (`object.move`) failed: …``. The +/// checks before a batch runs and the errors of its steps as they run give the same text. +pub(crate) fn action_step(index: usize, id: &str, reason: &str) -> String { + let n = index.saturating_add(1); + if id.is_empty() { + format!("action step {n} failed: {reason}") + } else { + format!("action step {n} (`{}`) failed: {reason}", vectorcraft_apischema::shown_key(id)) + } +} + /// The step number, command id and reason in the error `command.batch` gives when one of its steps /// fails (``batch step 2 (`object.move`) failed: …``); none for any other error. #[cfg(not(target_arch = "wasm32"))] @@ -540,7 +538,7 @@ fn dataset_output_extensions(run: &Run<'_>, doc: &vectorcraft_doc::Document, def outputs.push(DatasetOutput { ext: String::new(), artboards: false, joiner: "-", folder: true }); continue; } - let writes = (run.override_save && matches!(id, "document.save" | "file.save" | "file.saveAs")) + let writes = (run.override_save && matches!(id, "document.save" | "file.saveAs")) || (run.override_export && matches!(id, "document.export" | "document.exportSelection")); if writes { let format = step.get("params").and_then(|p| p.get("format")).and_then(Value::as_str).filter(|f| !f.is_empty()); @@ -551,7 +549,7 @@ fn dataset_output_extensions(run: &Run<'_>, doc: &vectorcraft_doc::Document, def }; if safe_extension(&ext) { let format_id = super::format(format.unwrap_or(default_ext)).map(|f| f.id).unwrap_or("vectorcraft"); - let is_save = matches!(id, "document.save" | "file.save" | "file.saveAs"); + let is_save = matches!(id, "document.save" | "file.saveAs"); let artboards = if is_save { !doc.artboards.is_empty() && matches!(format_id, "vectorcraft" | "template" | "ai" | "ait") } else { @@ -693,7 +691,7 @@ fn rewrite_paths( .map(|c| { let id = c.get("command").and_then(Value::as_str).unwrap_or(""); let mut c = c.clone(); - let rewrite = (override_save && matches!(id, "document.save" | "file.save" | "file.saveAs")) + let rewrite = (override_save && matches!(id, "document.save" | "file.saveAs")) || (override_export && matches!(id, "document.export" | "document.exportForScreens" | "document.exportSelection" | "assets.export")); if !rewrite { return c; @@ -2385,10 +2383,97 @@ mod tests { let mut s = Session::new(); let p = json!({"folder": src.to_string_lossy(), "commands": [{"command": "object.unlockAll"}, {"command": "prefs.import", "params": {}}]}); let e = s.execute("action.batch", &p).unwrap_err().to_string(); - assert!(e.contains("commands[1]: `prefs.import` runs on its own, not as a batch step"), "{e}"); + assert!(e.contains("action step 2 (`prefs.import`) failed: `prefs.import` runs on its own, not as a batch step"), "{e}"); assert!(s.active().is_none(), "no file was opened"); } + /// Each step the checks before the batch refuse is named by its place in `commands`, from 1, + /// as a step that fails as it runs is, and no source file is opened. + #[test] + fn a_refused_step_is_named_by_its_place_from_1() { + let src = tmp("step-number-refused-src"); + write_svg(&src, "a.svg", "#f00"); + let prefix = "invalid parameters for `action.batch`: "; + let cases = [ + (json!({"params": {}}), "action step 2 failed: missing `command`"), + (json!({"command": "select.al"}), "action step 2 (`select.al`) failed: unknown command `select.al`; did you mean `select.all`?"), + (json!({"command": "command.batch", "params": {"commands": []}}), "action step 2 (`command.batch`) failed: batches cannot nest"), + (json!({"command": "action.batch", "params": {}}), "action step 2 (`action.batch`) failed: batches cannot nest"), + ( + json!({"command": "view.saved.new", "params": {"center": [0, 0], "zoom": 0}}), + "action step 2 (`view.saved.new`) failed: invalid parameters for `view.saved.new`: `zoom` must be a number > 0, not 0", + ), + ]; + for (step, want) in cases { + let mut s = Session::new(); + let p = json!({"folder": src.to_string_lossy(), "commands": [{"command": "object.unlockAll"}, step]}); + let e = s.execute("action.batch", &p).unwrap_err().to_string(); + assert_eq!(e, format!("{prefix}{want}"), "{step}"); + assert!(s.active().is_none(), "{step}: a file was opened"); + assert!(s.journal.is_empty(), "{step}: a step ran"); + } + } + + /// The parameter check of an `action.batch` names the step whose params it refuses, from 1; + /// that of a `command.batch` passes the step's error on as it is. + #[test] + fn the_parameter_check_names_the_refused_step() { + let bad_view = json!({"command": "view.saved.new", "params": {"center": [0, 0], "zoom": 0}}); + let commands = json!([{"command": "object.unlockAll"}, {"command": "select.all"}, bad_view]); + let own = "invalid parameters for `view.saved.new`: `zoom` must be a number > 0, not 0"; + let e = crate::cmd::params::check_params("action.batch", &json!({"commands": commands})).unwrap_err().to_string(); + assert_eq!(e, format!("invalid parameters for `action.batch`: action step 3 (`view.saved.new`) failed: {own}")); + let e = crate::cmd::params::check_params("command.batch", &json!({"commands": commands})).unwrap_err().to_string(); + assert_eq!(e, own); + } + + /// The ids of the File menu's Open… and Save in the app (`file.open`, `file.save`) and + /// `document.close` are not engine commands, so a step with one is refused before the batch + /// starts, with Override Open and Override Save on or off. + #[test] + fn steps_with_ids_that_are_not_engine_commands_are_refused() { + let src = tmp("step-number-aliases-src"); + write_svg(&src, "a.svg", "#f00"); + for id in ["file.open", "file.save", "document.close"] { + for overrides in [true, false] { + let mut s = Session::new(); + let p = json!({ + "folder": src.to_string_lossy(), + "overrideOpen": overrides, + "overrideSave": overrides, + "commands": [{"command": "object.unlockAll"}, {"command": id, "params": {}}], + }); + let e = s.execute("action.batch", &p).unwrap_err().to_string(); + assert!( + e.starts_with(&format!("invalid parameters for `action.batch`: action step 2 (`{id}`) failed: unknown command `{id}`")), + "{e}" + ); + assert!(s.active().is_none(), "{id}: a file was opened"); + } + } + } + + /// `command.batch` keeps its own numbering, from 0, for a step that fails. + #[test] + fn command_batch_keeps_its_own_step_numbers() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let e = s + .execute("command.batch", &json!({"commands": [{"command": "object.unlockAll"}, {"command": "object.align", "params": {}}]})) + .unwrap_err(); + assert!(e.to_string().starts_with("batch step 1 (`object.align`) failed: "), "{e}"); + } + + /// A step's id in the error is cut short, as an unknown key's is. + #[test] + fn a_long_step_id_is_cut_short() { + let id = "x".repeat(10_000); + let shown = action_step(0, &id, "why"); + assert!(shown.len() < 1_000, "{}", shown.len()); + assert!(shown.starts_with("action step 1 (`xxx") && shown.ends_with("…`) failed: why"), "{shown}"); + assert_eq!(action_step(usize::MAX, "", "why"), format!("action step {} failed: why", usize::MAX)); + } + /// Only the error `command.batch` gives for a failed step is read as one. #[test] fn batch_step_failure_reads_only_a_step_error() { diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index adc73c2c85..0969adb5a2 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -117,7 +117,7 @@ pub fn specs() -> Vec { "Batch…", [], None, - "{commands: [{command, params}] (the action's steps), source?: folder (default) | datasets, folder? (required for folder: the source folder), includeSubdirs?: false, destination?: none (default: leave each file open) | saveAndClose (save over the source and close; for source datasets, save the open document over its own file after each data set, and refuse a document that was never saved, was converted from an older version or was restored by Data Recovery, unless a recorded Save or Save As step writes a file first; a Save or Save As step that overrideSave points into destinationFolder makes each data set's file the document's own) | folder (save or export into destinationFolder and close), destinationFolder? (required when destination is folder; also the folder Override Save/Export write into), datasetFileNaming?: fileNumber | fileDataSetName (default) | dataSetName (used only for source datasets; ignored for folder), overrideOpen?: true (skip document.open / file.open steps: the batch opens each source file), overrideSave?: true (point document.save / file.save / file.saveAs at destinationFolder/{stem}.{ext}), overrideExport?: true (point document.export / document.exportSelection the same way, and give document.exportForScreens / assets.export the folder destinationFolder/{stem}, one for each source file or data set, in which the export names its files as it does outside Batch), stopOnError?: true, label?} play the commands on every readable file in folder (and its subfolders when includeSubdirs; {stem} is the file's name without its extension and without trailing periods and spaces, with `-2`, `-3`… added to a name an earlier file used or whose file or folder has the name of one an earlier file wrote or of another source file or a folder of source files in destinationFolder), or on every data set of the open document. Data set names use the document stem plus a three-digit ordinal, the document stem and an underscore plus the data set name, or the data set name alone. Invalid file name characters become `-` and trailing periods and spaces are dropped; a name already used in the batch or whose output file or folder already exists in a destination folder the batch may read and write gets the next free `-2`, `-3` suffix before the format-derived extension. Caps: 500 files or data sets, 8 folder levels, 256 steps. Batches cannot nest, and a prefs.import step is refused (commands[i], from 0) before any file is opened. A switch (includeSubdirs, overrideOpen, overrideSave, overrideExport, stopOnError) that is not true or false, or a source, folder, destination, destinationFolder, datasetFileNaming or label that is not a string, is an error before any folder is made or file opened; null reads as left out. A step that fails is named in the error by its place in commands, from 1, counting the Open steps the batch skips (action step 3 (`object.align`) failed: …); the batch's own opening of a file, choosing of a data set and destination save, export or close give their errors without a step number. → {processed: [{path|dataset, result|error}…], count, failed, stopped, warning?} (warning: for source datasets, when Save and Close without such a step, or a Save, Save a Copy, Save as Template or export step (document.export, exportSelection, exportForScreens, exportPdf, exportEps, exportDxf, exportForWeb, exportForOffice) that writes a file and is not pointed into destinationFolder, saves every data set over the same file)", + "{commands: [{command, params}] (the action's steps), source?: folder (default) | datasets, folder? (required for folder: the source folder), includeSubdirs?: false, destination?: none (default: leave each file open) | saveAndClose (save over the source and close; for source datasets, save the open document over its own file after each data set, and refuse a document that was never saved, was converted from an older version or was restored by Data Recovery, unless a recorded Save or Save As step writes a file first; a Save or Save As step that overrideSave points into destinationFolder makes each data set's file the document's own) | folder (save or export into destinationFolder and close), destinationFolder? (required when destination is folder; also the folder Override Save/Export write into), datasetFileNaming?: fileNumber | fileDataSetName (default) | dataSetName (used only for source datasets; ignored for folder), overrideOpen?: true (skip document.open steps: the batch opens each source file), overrideSave?: true (point document.save / file.saveAs at destinationFolder/{stem}.{ext}), overrideExport?: true (point document.export / document.exportSelection the same way, and give document.exportForScreens / assets.export the folder destinationFolder/{stem}, one for each source file or data set, in which the export names its files as it does outside Batch), stopOnError?: true, label?} play the commands on every readable file in folder (and its subfolders when includeSubdirs; {stem} is the file's name without its extension and without trailing periods and spaces, with `-2`, `-3`… added to a name an earlier file used or whose file or folder has the name of one an earlier file wrote or of another source file or a folder of source files in destinationFolder), or on every data set of the open document. Data set names use the document stem plus a three-digit ordinal, the document stem and an underscore plus the data set name, or the data set name alone. Invalid file name characters become `-` and trailing periods and spaces are dropped; a name already used in the batch or whose output file or folder already exists in a destination folder the batch may read and write gets the next free `-2`, `-3` suffix before the format-derived extension. Caps: 500 files or data sets, 8 folder levels, 256 steps. A step without a command, with a command the engine doesn't have, with params its command refuses, or with command.batch, action.batch or prefs.import (batches cannot nest) is refused before any file is opened, named by its place in commands, from 1 (action step 2 (`select.al`) failed: unknown command `select.al`; did you mean `select.all`?). A switch (includeSubdirs, overrideOpen, overrideSave, overrideExport, stopOnError) that is not true or false, or a source, folder, destination, destinationFolder, datasetFileNaming or label that is not a string, is an error before any folder is made or file opened; null reads as left out. A step that fails as it runs is named the same way, counting the Open steps the batch skips (action step 3 (`object.align`) failed: …); the batch's own opening of a file, choosing of a data set and destination save, export or close give their errors without a step number. → {processed: [{path|dataset, result|error}…], count, failed, stopped, warning?} (warning: for source datasets, when Save and Close without such a step, or a Save, Save a Copy, Save as Template or export step (document.export, exportSelection, exportForScreens, exportPdf, exportEps, exportDxf, exportForWeb, exportForOffice) that writes a file and is not pointed into destinationFolder, saves every data set over the same file)", always, action_batch::action_batch ), diff --git a/crates/engine/src/cmd/fileio/dxf.rs b/crates/engine/src/cmd/fileio/dxf.rs index 8486cd2226..8004234c07 100644 --- a/crates/engine/src/cmd/fileio/dxf.rs +++ b/crates/engine/src/cmd/fileio/dxf.rs @@ -226,9 +226,10 @@ pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option) -> vec![(Some(b), rect(b)?, false)] } }; + let regions: Vec<(Rect, bool)> = drawings.iter().map(|&(_, region, crop)| (region, crop)).collect(); + let outs = vectorcraft_cad::export_drawings(doc, &opts, ®ions).map_err(|e| bad(C, e))?; let mut enc = Encoded::default(); - for (board, region, crop) in drawings { - let out = vectorcraft_cad::export(doc, &DxfOptions { region, crop, ..opts.clone() }).map_err(|e| bad(C, e))?; + for ((board, _, _), out) in drawings.into_iter().zip(outs) { enc.files.push((board, out.bytes)); for w in out.warnings { if !enc.warnings.contains(&w) { 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/fileio/metafile.rs b/crates/engine/src/cmd/fileio/metafile.rs index d987d82757..e9e1e882a7 100644 --- a/crates/engine/src/cmd/fileio/metafile.rs +++ b/crates/engine/src/cmd/fileio/metafile.rs @@ -26,13 +26,16 @@ pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option, kin Some(true) => pick.resolve(n).map_err(|e| bad(C, e))?.unwrap_or_else(|| (0..n).collect()), _ => vec![pick.one(n).map_err(|e| bad(C, e))?], }; + let rects = boards + .iter() + .map(|&b| doc.artboards.get(b).map(|a| a.rect).ok_or_else(|| bad(C, format!("no artboard {}", b + 1)))) + .collect::>>()?; // Raster effects (shadows, glows, blurs) as images, as PDF export does. let flat = crate::flatten_raster_effects(doc); let src = flat.as_ref().unwrap_or(doc); + let outs = vectorcraft_metafile::export_regions(src, &rects, kind).map_err(|e| bad(C, e))?; let mut enc = Encoded::default(); - for b in boards { - let region = doc.artboards.get(b).ok_or_else(|| bad(C, format!("no artboard {}", b + 1)))?.rect; - let out = vectorcraft_metafile::export(src, region, kind).map_err(|e| bad(C, e))?; + for (b, out) in boards.into_iter().zip(outs) { enc.files.push((Some(b), out.bytes)); for w in out.warnings { if !enc.warnings.contains(&w) { diff --git a/crates/engine/src/cmd/fileio/pdf.rs b/crates/engine/src/cmd/fileio/pdf.rs index 0adc827df0..daa20ac2b0 100644 --- a/crates/engine/src/cmd/fileio/pdf.rs +++ b/crates/engine/src/cmd/fileio/pdf.rs @@ -128,7 +128,7 @@ pub fn specs() -> Vec { "Export PDF", [], None, - "{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, and with destination and an sRGB destination a gray or RGB image tagged with an ICC profile is converted from it and written untagged; with destination and a CMYK destination, or another RGB one images are converted to (not when colours are ICC-tagged), an RGB image tagged with one is converted from it through sRGB; with preserveNumbers (and pdfX1a) only untagged images keep their numbers: an RGB image tagged with one is converted from it to sRGB or through sRGB to the destination, and a gray one is converted from it in an sRGB destination; any other image whose colors are converted (a CMYK image, an RGB one going to a CMYK destination, or with destination to an RGB one other than sRGB) but whose pixels can't be decoded or written that way is left out with a warning; printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours; images are written without the ICC profiles they carry, a JPEG without its ICC_PROFILE segments, but in PDF/A, pdfX3 and pdfX4)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile)|default (not set, the default; \"default\" unsets a preset's value, null keeps it: device colours, and gray and RGB images keep the profiles they carry, but in pdfX1a) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says; a CMYK image that keeps its numbers carries the CMYK profile it embeds with all and taggedSource, and in PDF/A, pdfX3 and pdfX4 unless destination, never in pdfX1a), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent), registry, trapped (/Trapped /True; /False when an output intent is written)} (PDF/A files keep their own output intent), advanced?: {fontSubsetPercent: 100 (below 100 is accepted with a warning: fonts are always embedded as subsets), outlineText: false (type as real, selectable and searchable text in embedded subset fonts with a ToUnicode map; fonts whose licence forbids embedding, or allows only whole fonts, stay outlines with a warning; true: every glyph as an outline), overprint: preserve (overprinting fills and strokes set /OP /op true, /OPM 1; white ones knock out with document.setup discardWhiteOverprint)|discard (they knock out)}, security?: {openPassword, permissionsPassword, printing: none|low|high, changes: none|pages|forms|comments|any, copy, screenReader, plaintextMetadata}, acknowledgeLoss?: bool (write over the file the document was read from although reading it left things out), format?: \"pdf\"} → {path, bytes, warnings}; no path → {dataBase64, bytes, warnings}. The options apply over the preset (null keeps its value); options accepted but not applied yet come back as warnings; a standard with a PDF version it doesn't allow and a password with a standard are refused, and so is a PDF/X file that would still break its standard (transparency the flattener left, RGB in pdfX1a, a font not embedded) or a PDF 1.3 file with transparency left. document.export {format: pdf} takes the same options. A key PDF doesn't take, and an unknown key inside one of the option objects, are refused. Under automation read roots, a PDF that carries the native document (preserveEditing on, every artboard, useArtboards not false) is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked)", + "{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, and with destination and an sRGB destination a gray or RGB image tagged with an ICC profile is converted from it and written untagged; with destination and a CMYK destination, or another RGB one images are converted to (not when colours are ICC-tagged), an RGB image tagged with one is converted from it through sRGB; with preserveNumbers (and pdfX1a) only untagged images keep their numbers: an RGB image tagged with one is converted from it to sRGB or through sRGB to the destination, and a gray one is converted from it in an sRGB destination; any other image whose colors are converted (a CMYK image, an RGB one going to a CMYK destination, or with destination to an RGB one other than sRGB) but whose pixels can't be decoded or written that way is left out with a warning; printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours; images are written without the ICC profiles they carry, a JPEG without its ICC_PROFILE segments, but in PDF/A, pdfX3 and pdfX4)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile)|default (not set, the default; \"default\" unsets a preset's value, null keeps it: device colours, and gray and RGB images keep the profiles they carry, but in pdfX1a) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says, but in pdfX3 and pdfX4 CMYK colors in the profile of a CMYK output intent are DeviceCMYK, and with none and a CMYK output intent pdfX3 and pdfX4 write every CMYK color as DeviceCMYK, unless colors are converted to a CMYK destination of another profile; a CMYK image that keeps its numbers carries the CMYK profile it embeds with all and taggedSource, and in PDF/A, pdfX3 and pdfX4 unless destination, never in pdfX1a, nor when CMYK colors are DeviceCMYK and either its profile is the output intent's or profiles is none), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent), registry, trapped (/Trapped /True; /False when an output intent is written)} (PDF/A files keep their own output intent), advanced?: {fontSubsetPercent: 100 (below 100 is accepted with a warning: fonts are always embedded as subsets), outlineText: false (type as real, selectable and searchable text in embedded subset fonts with a ToUnicode map; fonts whose licence forbids embedding, or allows only whole fonts, stay outlines with a warning; true: every glyph as an outline), overprint: preserve (overprinting fills and strokes set /OP /op true, /OPM 1; white ones knock out with document.setup discardWhiteOverprint)|discard (they knock out)}, security?: {openPassword, permissionsPassword, printing: none|low|high, changes: none|pages|forms|comments|any, copy, screenReader, plaintextMetadata}, acknowledgeLoss?: bool (write over the file the document was read from although reading it left things out), format?: \"pdf\"} → {path, bytes, warnings}; no path → {dataBase64, bytes, warnings}. The options apply over the preset (null keeps its value); options accepted but not applied yet come back as warnings; a standard with a PDF version it doesn't allow and a password with a standard are refused, and so is a PDF/X file that would still break its standard (transparency the flattener left, RGB in pdfX1a, a font not embedded) or a PDF 1.3 file with transparency left. document.export {format: pdf} takes the same options. A key PDF doesn't take, and an unknown key inside one of the option objects, are refused. Under automation read roots, a PDF that carries the native document (preserveEditing on, every artboard, useArtboards not false) is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked)", has_doc, export_pdf ), diff --git a/crates/engine/src/cmd/fileio/pdfimport.rs b/crates/engine/src/cmd/fileio/pdfimport.rs index 189274a31f..ea37575135 100644 --- a/crates/engine/src/cmd/fileio/pdfimport.rs +++ b/crates/engine/src/cmd/fileio/pdfimport.rs @@ -222,6 +222,13 @@ fn page_options(page: usize, o: &LoadOptions) -> ImportOptions { ImportOptions { pages: Some(vec![page]), crop: o.crop, password: o.password.clone(), text_as: o.text_as, layers: false, ..Default::default() } } +/// Whether `document.open`'s `linkPages` takes the file `name` holding `bytes`: a PDF or a +/// PDF-compatible `.ai` or `.ait` of at most [`document::MAX_FILE`] bytes. Its path, a password +/// and `textAs` are checked apart ([`linked_pages`]). +pub fn pages_can_link(name: &str, bytes: &[u8]) -> bool { + bytes.len() <= document::MAX_FILE && document::is_pdf(name, bytes) +} + /// `document.open` with `linkPages`: the pages `o` picks of the PDF (or PDF-compatible `.ai` or /// `.ait`) `name`, read from `path`, as a document holding one placed document per page, linked to /// that page of the file as File › Place with Link places one ([`document::source`]). Each page diff --git a/crates/engine/src/cmd/fileio/tests_dxf.rs b/crates/engine/src/cmd/fileio/tests_dxf.rs index 1a3368b56f..b5129d1910 100644 --- a/crates/engine/src/cmd/fileio/tests_dxf.rs +++ b/crates/engine/src/cmd/fileio/tests_dxf.rs @@ -116,6 +116,24 @@ fn use_artboards_writes_one_drawing_per_artboard() { assert!(e.contains("useArtboards"), "{e}"); } +#[test] +fn each_artboard_s_drawing_is_the_drawing_of_that_artboard_alone() { + let mut s = two_boards(); + // A second rectangle on the second artboard, so the two drawings differ. + let second = s.doc().unwrap().doc.artboards[1].rect.x0; + s.execute("shape.rectangle", &json!({"x": second + 50.0, "y": 50, "width": 20, "height": 20})).unwrap(); + let r = s.execute("document.export", &json!({"format": "dxf", "useArtboards": true, "unit": "pt"})).unwrap(); + let files = r["files"].as_array().unwrap(); + let doc = &s.doc().unwrap().doc; + let o = dxf::options(&json!({"unit": "pt"})).unwrap(); + assert_eq!(files.len(), doc.artboards.len()); + assert_ne!(b64(&files[0]), b64(&files[1])); + for (f, board) in files.iter().zip(&doc.artboards) { + let alone = vectorcraft_cad::export(doc, &vectorcraft_cad::DxfOptions { region: board.rect, crop: true, ..o.clone() }).unwrap(); + assert_eq!(b64(f), alone.bytes, "{}", f["name"]); + } +} + #[test] fn selected_only_exports_the_selection_in_its_layers() { let mut s = two_boards(); diff --git a/crates/engine/src/cmd/fileio/tests_pdfimport.rs b/crates/engine/src/cmd/fileio/tests_pdfimport.rs index 703c29fe74..63b70c48c7 100644 --- a/crates/engine/src/cmd/fileio/tests_pdfimport.rs +++ b/crates/engine/src/cmd/fileio/tests_pdfimport.rs @@ -410,3 +410,16 @@ fn a_placeholder_only_pdf_part_is_detected() { assert!(open(&mut s, &two, json!({"pages": "1"})).is_err()); open(&mut s, &two, json!({})).unwrap(); } + +/// `linkPages` takes a PDF up to the largest file placed, and nothing else. +#[test] +fn pages_can_link_a_pdf_up_to_the_largest_file_placed() { + let small = three_pages(); + assert!(pages_can_link("pages.pdf", &small)); + assert!(!pages_can_link("pages.svg", b"")); + let mut big = vec![0u8; crate::cmd::place::document::MAX_FILE + 1]; + big[..small.len()].copy_from_slice(&small); + assert!(!pages_can_link("pages.pdf", &big), "over the limit"); + big.pop(); + assert!(pages_can_link("pages.pdf", &big), "at the limit"); +} diff --git a/crates/engine/src/cmd/inline.rs b/crates/engine/src/cmd/inline.rs index 784548e491..676fb9b55b 100644 --- a/crates/engine/src/cmd/inline.rs +++ b/crates/engine/src/cmd/inline.rs @@ -3,7 +3,7 @@ use serde_json::{Value, json}; use vectorcraft_doc::text::INLINE_MAX_SCALE; -use vectorcraft_doc::{Document, InlineArt, NodeId, NodeKind, TextRun}; +use vectorcraft_doc::{Document, InlineArt, InlineMeasured, NodeId, NodeKind, TextRun}; use vectorcraft_text::edit; use super::brushsym::current_symbol; @@ -25,12 +25,33 @@ pub fn specs() -> Vec { /// Inline graphics follow their symbols: after an edit of a document that has (or had) symbols, /// resolve the inline art of every text again, in the layers and in the art of symbols, graph /// designs, pattern tiles and opacity masks, and lay out again the texts whose art changed (a -/// symbol's type before the type that shows that symbol inline). -pub(crate) fn refresh(before: &Document, d: &mut Document) { +/// symbol's type before the type that shows that symbol inline). `last` is the document the last +/// refresh left resolved, with what it measured: when nothing the inline art depends on changed +/// since, only the layer trees that differ from its own are checked +/// ([`Document::resolve_inline_art_since`]). Returns what this refresh measured, or `None` when +/// neither document has symbols and nothing was checked. +pub(crate) fn refresh(last: Option<&Resolved>, before: &Document, d: &mut Document) -> Option { if before.symbols.is_empty() && d.symbols.is_empty() { - return; + return None; } - d.resolve_inline_art_with(&mut refresh_bounds); + #[cfg(test)] + let last = last.filter(|_| !FULL_PASS.get()); + let pass = d.resolve_inline_art_since(last.map(|(doc, m)| (&**doc, m)), &mut refresh_bounds); + #[cfg(test)] + PASSES.with(|p| p.borrow_mut().push((pass.partial, pass.changed.clone()))); + Some(pass.measured) +} + +/// A document a [`refresh`] left resolved, and what that refresh measured. +pub(crate) type Resolved = (std::sync::Arc, InlineMeasured); + +#[cfg(test)] +thread_local! { + /// Each [`refresh`] on this thread that checked the document: whether it checked only the + /// changed layer trees, and the ids of the texts in the layers that changed. + pub(crate) static PASSES: std::cell::RefCell)>> = const { std::cell::RefCell::new(vec![]) }; + /// Set: every [`refresh`] on this thread takes the full pass. + pub(crate) static FULL_PASS: std::cell::Cell = const { std::cell::Cell::new(false) }; } fn insert_inline(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 237f0f9d49..7a7f2b8e08 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -29,7 +29,7 @@ pub fn specs() -> Vec { "New Layer…", ["Window", "Layers"], Some("Cmd+L"), - "{name?, top?: bool, below?: bool, color?, template?, locked?, visible?, printable?, preview?, dimImages?} a layer directly above the current layer, at its level (a sublayer beside a current sublayer); `top`: above all layers (Ctrl/Cmd-click the button); `below`: directly below the current layer, at its level (Ctrl/Cmd+Alt-click the button), not with `top`. Options as layer.setProps; refused while an opacity mask is edited (the Layers panel lists only the mask) → {id}", + "{name?, top?: bool, below?: bool, color?, template?, locked?, visible?, printable?, preview?, dimImages?} a layer directly above the current layer, at its level (a sublayer beside a current sublayer), or directly below it in Draw Behind; `top`: above all layers (Ctrl/Cmd-click the button); `below`: directly below the current layer, at its level (Ctrl/Cmd+Alt-click the button), not with `top`. Options as layer.setProps; refused while an opacity mask is edited (the Layers panel lists only the mask) → {id}", super::maskedit::outside_mask_editing, new_layer ), @@ -110,7 +110,7 @@ pub fn specs() -> Vec { "Move Rows", [], None, - "{ids|id, target, place?: \"above\"|\"below\"|\"inside\" (default inside), copy?: bool} drag rows in the Layers panel: above or below the target row (beside it, in its layer or group), or inside a layer, group or Intertwine group (on top of its contents). Layers go only in layers or at the top level, objects in layers, groups and Intertwine groups; an object placed beside a top-level layer goes inside it. An object placed in an Intertwine group becomes a member drawn in its row's order, with no arranged areas, and one placed in a group that is a member becomes part of that member; one that is or holds an Intertwine group, a Repeat, a graph or a Live Paint group is refused. A member moved out of its Intertwine group drops its arranged areas, and a group left with one member is replaced by that member, or becomes a plain group of it when the group has an opacity, blending, appearance, mask, lock or hidden state of its own (with no member, it is removed). A row never goes into itself; a locked layer or group takes nothing. `copy` (Alt-drag) moves copies. Every selected object left hidden or locked, such as one moved into a hidden layer or group, is deselected (the key object too). One undo step → {ids}", + "{ids|id, target, place?: \"above\"|\"below\"|\"inside\" (default inside), copy?: bool} drag rows in the Layers panel: above or below the target row (beside it, in its layer or group), or inside a layer, group or Intertwine group (on top of its contents). Layers go only in layers or at the top level, objects in layers, groups and Intertwine groups; an object placed beside a top-level layer goes inside it. An object placed in an Intertwine group becomes a member drawn in its row's order, with no arranged areas, and one placed in a group that is a member becomes part of that member; one that is or holds an Intertwine group, a Repeat, a graph or a Live Paint group is refused. A member moved out of its Intertwine group drops its arranged areas, and a group left with one member is replaced by that member, or becomes a plain group of it when the group has an opacity, blending, appearance, mask, lock or hidden state of its own (with no member, it is removed). A row never goes into itself; a locked layer or group takes nothing. `copy` (Alt-drag) moves copies, which may also go above or below a row they copy (the target among `ids`). Every selected object left hidden or locked, such as one moved into a hidden layer or group, is deselected (the key object too). One undo step → {ids}", has_doc, move_rows ), @@ -526,12 +526,15 @@ fn add_layer(s: &mut Session, p: &Value, cmd: &str, label: &str, place: impl FnO fn new_layer(s: &mut Session, p: &Value) -> Result { const C: &str = "layer.new"; let below = switch_or(p, "below", false, C)?; - if below && bool_or(p, "top", false) { + let top = bool_or(p, "top", false); + if below && top { return Err(bad(C, "`top` and `below` can't both be true")); } + // In Draw Behind a layer given neither `top` nor `below` goes below the current layer. + let below = below || (!top && s.draw_mode == crate::DrawMode::Behind); let st = s.doc()?; // Above the current layer, at its level; below it with `below`; on top of everything with `top`. - let cur = st.current_layer().filter(|_| !bool_or(p, "top", false)); + let cur = st.current_layer().filter(|_| !top); add_layer(s, p, C, "New Layer", |d| match cur.and_then(|c| d.position(c)) { Some((parent, i, _)) => Ok((parent, if below { i } else { i + 1 })), None => Ok((None, if below { 0 } else { usize::MAX })), @@ -723,19 +726,18 @@ fn select_art(s: &mut Session, p: &Value) -> Result { } else { vec![id] }; - let all_selected = !ids.is_empty() && ids.iter().all(|i| st.selection.contains(*i)); + let all_selected = add && !ids.is_empty() && { + let selected: HashSet = st.selection.objects.iter().copied().collect(); + ids.iter().all(|i| selected.contains(i)) + }; let rows = st.layer_rows.clone(); s.select(|_, sel| { if !add { sel.set(ids.iter().copied()); } else if all_selected { - for i in &ids { - sel.remove(*i); - } + sel.remove_all(ids.iter().copied()); } else { - for i in &ids { - sel.add(*i); - } + sel.add_all(ids.iter().copied()); } })?; let st = s.doc_mut()?; @@ -774,9 +776,11 @@ fn move_rows(s: &mut Session, p: &Value) -> Result { if ids.is_empty() { return Err(bad(C, "no such rows")); } - // Never into itself or a row inside it. + // Never into itself or a row inside it. A copy may go above or below one of the rows it + // copies, which a move there would leave where it is (#8237). + let beside_itself = copy && place != Place::Inside && ids.contains(&target); let around = d.ancestry(target).unwrap_or_default(); - if ids.iter().any(|i| around.contains(i)) { + if ids.iter().any(|i| around.contains(i) && !(beside_itself && *i == target)) { return Err(bad(C, "a row can't go into itself")); } let nodes: Vec<&Node> = ids.iter().filter_map(|i| d.node(*i)).collect(); @@ -788,6 +792,11 @@ fn move_rows(s: &mut Session, p: &Value) -> Result { parent => (parent, Some(target)), }, }; + // A copy beside a top-level layer it copies, with objects among the rows, would go inside + // that layer: into itself. + if parent.is_some_and(|p| ids.contains(&p)) { + return Err(bad(C, "a row can't go into itself")); + } if let Some(n) = nodes.iter().find(|n| !accepts(d, parent, n)) { let into = parent.and_then(|p| d.node(p)).map_or("the top level", |p| if p.is_layer() { "a layer" } else { p.kind_label() }); return Err(bad(C, format!("{} can't go into {into}", n.display_name()))); diff --git a/crates/engine/src/cmd/layerpanel.rs b/crates/engine/src/cmd/layerpanel.rs index 95c152e959..5400e66728 100644 --- a/crates/engine/src/cmd/layerpanel.rs +++ b/crates/engine/src/cmd/layerpanel.rs @@ -132,7 +132,7 @@ pub fn specs() -> Vec { "Locate Object", ["Window", "Layers"], None, - "{id?} (default: the last selected object) highlight the object's row; the Layers panel opens the layers around it and scrolls to it → {id, ancestry: [layer…, id]}", + "{id?, layersOnly?} (default: the last selected object) highlight the object's row; the Layers panel opens the layers around it and scrolls to it, also when the row was already highlighted →{id, ancestry: [layer…, id]}. layersOnly (default false; the panel sends true while Show Layers Only is on, as Locate Layer) highlights the innermost layer or sublayer holding the object instead, or a layer id itself → {id: layer, objectId, ancestry: [layer…]}", has_doc, locate ), @@ -435,10 +435,19 @@ fn reverse(s: &mut Session, p: &Value) -> Result { fn locate(s: &mut Session, p: &Value) -> Result { let id = object_param(p, "id", "layer.locate")?; + let layers_only = switch_or(p, "layersOnly", false, "layer.locate")?; let st = s.doc_mut()?; let id = id.or_else(|| st.selection.objects.last().copied()).ok_or_else(|| bad("layer.locate", "nothing selected"))?; - let ancestry = st.doc.ancestry(id).ok_or(EngineError::NoNode(id))?; - st.layer_rows = vec![id]; + let mut ancestry = st.doc.ancestry(id).ok_or(EngineError::NoNode(id))?; + if layers_only { + // Locate Layer: the innermost layer or sublayer holding the object (a layer locates itself). + let at = ancestry.iter().rposition(|a| st.doc.node(*a).is_some_and(Node::is_layer)).ok_or(EngineError::NoNode(id))?; + ancestry.truncate(at + 1); + } + let row = ancestry.last().copied().ok_or(EngineError::NoNode(id))?; + st.layer_rows = vec![row]; + st.locate_reveal = Some(row); st.revision += 1; - Ok(json!({ "id": id.0, "ancestry": ancestry.iter().map(|i| i.0).collect::>() })) + let ancestry: Vec = ancestry.iter().map(|i| i.0).collect(); + Ok(if layers_only { json!({ "id": row.0, "objectId": id.0, "ancestry": ancestry }) } else { json!({ "id": id.0, "ancestry": ancestry }) }) } 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/newart.rs b/crates/engine/src/cmd/newart.rs index ce8029e71b..84812dad97 100644 --- a/crates/engine/src/cmd/newart.rs +++ b/crates/engine/src/cmd/newart.rs @@ -7,12 +7,16 @@ //! panel's New Art Has Basic Appearance off, the whole appearance of the last selection. With the //! option on (the default) an inherited appearance gives new art its top stroke's options only, //! and a change of selection loads only the proxies. `paint.default` resets it. +//! +//! A document whose Default Graphic Style no longer has the shipped look (a New Document profile +//! redefined it) gives the reset that style's fills, strokes and effects instead, and `file.new` +//! resets new art when it opens such a document. use std::borrow::Cow; use serde_json::{Value, json}; use vectorcraft_color::{BlendMode, Paint}; -use vectorcraft_doc::{Appearance, AppearanceItem, FillLayer, GraphicStyle, Node, NodeKind, StrokeLayer}; +use vectorcraft_doc::{Appearance, AppearanceItem, ColorMode, DEFAULT_GRAPHIC_STYLE, Document, FillLayer, GraphicStyle, Node, NodeKind, StrokeLayer}; use vectorcraft_tools::PaintDefaults; use super::gradient::unplaced; @@ -263,7 +267,35 @@ fn describe(s: &mut Session, _: &Value) -> Result { })) } -/// The defaults for new art reset (`paint.default`): white fill, 1 pt black stroke, no template. +/// The defaults for new art reset (`paint.default`): white fill, 1 pt black stroke, no template; +/// in a document whose Default Graphic Style was redefined, that style's fills, strokes and effects +/// at full opacity, not linked to the style. pub(crate) fn reset(s: &mut Session) { s.paint = PaintDefaults::default(); + let style = s.doc().ok().and_then(|st| redefined_default_style(&st.doc)).cloned(); + if let Some(g) = style { + let ap = if g.unit_box { g.appearance } else { unplace_all(g.appearance) }; + s.take_new_art(ap, 1.0, BlendMode::Normal, None, false); + } +} + +/// `d`'s Default Graphic Style when its fills, strokes, effects or transparency differ from the +/// shipped style's (white fill, 1 pt black stroke), the shipped colors converted to `d`'s color mode +/// as a New Document profile's are. +pub(crate) fn redefined_default_style(d: &Document) -> Option<&GraphicStyle> { + let g = d.graphic_styles.iter().find(|g| g.name == DEFAULT_GRAPHIC_STYLE)?; + let same = + |o: &GraphicStyle| (&o.appearance, o.opacity, o.blend, o.isolate, o.knockout) == (&g.appearance, g.opacity, g.blend, g.isolate, g.knockout); + if same(&GraphicStyle::new(DEFAULT_GRAPHIC_STYLE, Appearance::default_art())) { + return None; + } + if d.color_mode != ColorMode::Rgb { + let mut shipped = Document::new_with_mode(1.0, 1.0, ColorMode::Rgb); + shipped.graphic_styles.retain(|o| o.name == DEFAULT_GRAPHIC_STYLE); + super::colormgmt::set_color_mode(&mut shipped, d.color_mode, true, None, super::colormgmt::Grays::Profile); + if shipped.graphic_styles.first().is_some_and(same) { + return None; + } + } + Some(g) } diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index 2a8d074617..e74a570a5b 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -814,6 +814,10 @@ pub(crate) fn file_new(s: &mut Session, p: &Value) -> Result { // The profile's links keep their relative paths, which name places from the profile's file, as // a new document from a history state keeps its source's. s.doc_mut()?.links_from = links_from; + // A profile whose Default Graphic Style was redefined gives new art in the document that style. + if super::newart::redefined_default_style(&s.doc()?.doc).is_some() { + super::newart::reset(s); + } // Overprint Preview is the engine's (the UI turns Pixel Preview on from `previewMode`). Both // are views of the whole app, so Default leaves them as they are. if settings.preview_mode == PreviewMode::Overprint { 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/arrange.rs b/crates/engine/src/cmd/object/arrange.rs index 17568d50b9..ff0b22b31b 100644 --- a/crates/engine/src/cmd/object/arrange.rs +++ b/crates/engine/src/cmd/object/arrange.rs @@ -384,6 +384,11 @@ fn add_drawn_live_paint(s: &mut Session, isolated: NodeId, next: Option) } pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result { + let key = "all"; + let all = match p.get(key) { + None => false, + Some(v) => v.as_bool().ok_or_else(|| bad("object.exitIsolation", format!("`{key}` must be true or false")))?, + }; // Opacity mask editing, pattern editing and symbol editing isolate their editing layer. Leaving // isolation mode then leaves that mode, as Stop Editing Opacity Mask and the isolation bar's // Done do. A group isolated inside the symbol's art goes back to the symbol's layer. @@ -419,12 +424,18 @@ pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result { return ok(); } let menu = s.menu.clone(); - let prev = s.active().and_then(|d| d.isolation); + let prev = st.isolation; + // An isolated sublayer goes up to its parent layer, which stays isolated, unless `all` is true or + // that layer is hidden or locked; anything else leaves isolation mode. + let up = prev + .filter(|i| !all && st.doc.node(*i).is_some_and(Node::is_layer)) + .and_then(|i| st.doc.parent_of(i)) + .filter(|parent| st.doc.is_editable(*parent)); if let Some(i) = prev { crate::cmd::settle_interaction(s)?; - let left = add_drawn_live_paint(s, i, None)?.unwrap_or(i); + let left = add_drawn_live_paint(s, i, up)?.unwrap_or(i); let st = s.doc_mut()?; - st.isolation = None; + st.isolation = up; crate::cmd::distortcmds::finish_edit_text(st, i); let target = st.doc.parent_of(left).filter(|p| st.doc.node(*p).is_some_and(|n| n.extras().shaper.is_some())).unwrap_or(left); st.selection.set([target]); 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 0c638ceb5e..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 ), @@ -250,7 +250,7 @@ pub fn specs() -> Vec { "Exit Isolation Mode", [], None, - "{} leave isolation mode; leaving an isolated Live Paint group adds the paths, compound paths and groups of them drawn in it (shown and unlocked with everything in them) to the group as livePaint.merge does, in one undo step, and leaves type, images and other objects in it as they are; object.isolate on a level outside the group does the same", + "{all?: bool (default false)} leave isolation mode; from an isolated sublayer, go up one level to its parent layer instead (the next call goes up again), unless all is true or the parent layer is hidden or locked; no undo step for the move up; while a symbol is edited, a group isolated in its art goes back to the symbol's layer first, with or without all; leaving an isolated Live Paint group adds the paths, compound paths and groups of them drawn in it (shown and unlocked with everything in them) to the group as livePaint.merge does, in one undo step, and leaves type, images and other objects in it as they are; object.isolate on a level outside the group does the same", has_doc, exit_isolation ), @@ -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)} (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)", + "{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 b30959de99..02edf6193b 100644 --- a/crates/engine/src/cmd/object/shape.rs +++ b/crates/engine/src/cmd/object/shape.rs @@ -6,6 +6,7 @@ use super::{ BTreeSet, CornerKind, EngineError, LiveCorners, LiveShape, NodeId, NodeKind, Result, Session, Value, bad, check_numbers, check_switches, convert_radii_relative, ok, selected_roots, set_corners, targets, }; +use crate::MAX_COORD; /// The largest scale of 0 or more at which `spans`, with the margins that scale grown by `k`, /// reach across `size` together. Returns 1 when their geometric boxes reach 1e-9 or less across @@ -98,8 +99,32 @@ fn corners_param(p: &Value) -> Result>> { list.iter().map(|k| k.as_u64().and_then(|k| usize::try_from(k).ok()).ok_or_else(err)).collect::>().map(Some) } +/// Live line `l` with Line Length `len` (its first end stays) and then Line Angle `angle` (about +/// its midpoint; a line whose ends meet has none to turn), or None when neither changes it. +fn line_edit(l: &LiveShape, len: Option, angle: Option) -> Option { + let now = l.line_length()?; + let mut new = l.clone(); + let mut changed = false; + if let Some(len) = len + && (len - now).abs() > 1e-9 * len.max(now) + { + new.set_line_length(len); + changed = true; + } + if let Some(a) = angle + && new.line_length().is_some_and(|n| n > 0.0) + && let Some(turn) = new.line_angle().map(|now| (a - now).rem_euclid(360.0)) + && turn > 1e-9 + && turn < 360.0 - 1e-9 + { + new.set_line_angle(a); + changed = true; + } + (changed && new != *l).then_some(new) +} + pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> 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()) { @@ -148,7 +173,7 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { } }; let angle = |k: &str| Ok::<_, EngineError>(number(k, |_| true, "an angle in degrees")?.map(|a| a.rem_euclid(360.0))); - let length = |k: &str| number(k, |x| x > 0.0 && x <= crate::MAX_COORD, "a length in points above 0"); + let length = |k: &str| number(k, |x| x > 0.0 && x <= MAX_COORD, "a length in points above 0"); // Saved steps ([`Session::replay`]) can hold values a direct call refuses, recorded before these // checks: a negative radius is 0, a whole side count of 0 or more is brought into 3 to 1000, and // a fractional or negative one is ignored. A whole number written as 5.0 counts as 5, as in a @@ -168,21 +193,58 @@ 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); + // A line's Line Properties: its length (its first end stays) and its angle (about its midpoint). + // A line's length can reach across the whole canvas, past `MAX_COORD`: its ends are checked below. + let line_length = number("lineLength", |x| x > 0.0, "a length in points above 0")?; + let line_angle = angle("lineAngle")?; // An ellipse's pie becomes `pie_of(pie)`. An end of 0 is a full turn (Illustrator shows a whole // 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 // are. let st = s.doc()?; + // The lines that Line Length or Line Angle changes, as they become. A line that would reach + // past the document's coordinate limit is an error before anything changes. + let mut lines = std::collections::BTreeMap::new(); + if line_length.is_some() || line_angle.is_some() { + for id in &ids { + let Some(NodeKind::Path { live: Some(l), .. }) = st.doc.node(*id).map(|n| &n.kind) else { continue }; + if let Some(new) = line_edit(l, line_length, line_angle) { + let LiveShape::Line { a, b } = &new else { continue }; + if ![a.x, a.y, b.x, b.y].iter().all(|c| c.abs() <= MAX_COORD) { + return Err(bad("object.setLiveShape", format!("coordinate out of range (limit ±{MAX_COORD} pt)"))); + } + lines.insert(*id, new); + } + } + } let has_values = |id: &NodeId| { let Some(NodeKind::Path { path, live, .. }) = st.doc.node(*id).map(|n| &n.kind) else { return true }; + if lines.contains_key(id) { + return false; + } match live.as_deref() { Some(l @ LiveShape::Polygon { sides: now, .. }) if !(sides.is_none_or(|n| n.clamp(3, 1000) == u64::from(*now)) @@ -244,6 +306,12 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { } *path = l.to_path(); } + if let Some(new) = lines.get(id) + && let Some(l) = live.as_deref_mut() + { + *l = new.clone(); + *path = l.to_path(); + } if let Some(on) = relative_radii && let Some(l) = live.as_deref_mut() { 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 2421b71d77..fddd6cdd9c 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -48,7 +48,7 @@ pub fn specs() -> Vec { "Default Fill and Stroke", [], Some("D"), - "{ids?|id?} white fill and 1 pt black stroke for the selection and the defaults; type gets black fill and no stroke. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke, and on a graph label the black fill and no stroke of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (exceptions: docs/mcp.md)", + "{ids?|id?} white fill and 1 pt black stroke for the selection and the defaults (in a document whose Default Graphic Style differs from the shipped one, as a New Document profile can redefine it: that style's fills, strokes and effects, without its opacity or a link to it); type gets black fill and no stroke. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke, and on a graph label the black fill and no stroke of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (exceptions: docs/mcp.md)", has_doc, default_paint ), @@ -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 }; @@ -1035,6 +1038,8 @@ fn default_paint(s: &mut Session, p: &Value) -> Result { if !ids.is_empty() { // When every object comes out as it was, the document and its undo history stay as they are. let before = s.doc()?.doc.clone(); + // A redefined Default Graphic Style gives other art its fills, strokes and effects, placed on each object. + let style = super::newart::redefined_default_style(&before).cloned(); super::overprint::edit_counted(s, "Default Fill and Stroke", |d| { for id in &ids { let Some(n) = d.node_mut(*id) else { continue }; @@ -1045,7 +1050,12 @@ fn default_paint(s: &mut Session, p: &Value) -> Result { r.style.stroke = Paint::None; } } - _ => n.appearance = Appearance::default_art().into(), + _ => { + n.appearance = match &style { + Some(g) => g.appearance_on(n).into_owned().into(), + None => Appearance::default_art().into(), + } + } } } let kept = super::appearance::capture_series_writes(&before, d, &ids, (true, true), (true, true), false, false); @@ -1316,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/params.rs b/crates/engine/src/cmd/params.rs index 3ee7117dbb..50e73f5a0d 100644 --- a/crates/engine/src/cmd/params.rs +++ b/crates/engine/src/cmd/params.rs @@ -36,6 +36,9 @@ //! `channel` that the effect doesn't have are refused by `effect.apply` and `effect.setParams` //! themselves ([`check_effect_color`], [`check_effect_channel`]). +use std::collections::HashMap; +use std::sync::OnceLock; + use serde_json::Value; use vectorcraft_apischema::shown_key; @@ -43,7 +46,7 @@ use super::{bad, command_specs, find_command}; use crate::Result; /// What a params description says about the keys of the params object. -#[derive(Debug, Default, PartialEq)] +#[derive(Clone, Debug, Default, PartialEq)] pub struct ParamKeys<'a> { /// The keys it names. pub keys: Vec<&'a str>, @@ -107,6 +110,8 @@ pub(crate) fn is_key(s: &str) -> bool { /// The keys a params description names, or what in it doesn't read as one. pub fn doc_keys(doc: &str) -> std::result::Result, String> { + #[cfg(test)] + PARSES.with(|n| n.set(n.get() + 1)); let mut out = ParamKeys::default(); let (mut body, mut rest) = object_body(doc)?; let mut entries = split_top(body, ','); @@ -155,7 +160,12 @@ fn named_commands(more: &str) -> impl Iterator Option> { - let parsed = doc_keys(doc).ok()?; + resolve(doc, depth, &mut |doc| doc_keys(doc).ok()) +} + +/// [`accepted`], with `parse` reading each description it reaches. +fn resolve(doc: &'static str, depth: usize, parse: &mut dyn FnMut(&'static str) -> Option>) -> Option> { + let parsed = parse(doc)?; let mut keys = parsed.keys; for more in parsed.more { let mut named = named_commands(more).peekable(); @@ -168,22 +178,120 @@ fn accepted(doc: &'static str, depth: usize) -> Option> { if UNCHECKED.contains(&spec.id) { return None; } - keys.extend(accepted(spec.params, depth + 1)?); + keys.extend(resolve(spec.params, depth + 1, parse)?); } } Some(keys) } +/// What the params description of a built-in command says about its keys, read once per process +/// ([`known`]). +#[derive(Debug)] +struct Known { + /// The keys it names itself; none when it doesn't parse. + own: Vec<&'static str>, + /// [`accepted`] of it. + accepted: Option>, + /// [`id_stands_for_ids`] of it. + id_stands_for_ids: bool, +} + +impl Known { + /// [`takes_key`] of the description. + fn takes(&self, key: &str) -> bool { + self.own.contains(&key) || self.accepted.as_ref().is_some_and(|keys| keys.contains(&key)) + } +} + +/// The place and length of `doc`'s text: a description with the same words elsewhere (a plug-in's) +/// has another place. +fn text_key(doc: &str) -> (usize, usize) { + (doc.as_ptr().addr(), doc.len()) +} + +/// [`Known`] of each description in `docs`, each one and each one its `…` entries name parsed once. +/// A description is left out when one it reaches has a `…` entry naming a plug-in command, whose +/// keys change as plug-ins are installed and removed. +fn read_descriptions(docs: impl IntoIterator) -> HashMap<(usize, usize), Known> { + let names_plugin = + |more: &str| more.split_whitespace().any(|w| w.trim_matches(|c: char| !c.is_ascii_alphanumeric()).starts_with(vectorcraft_plugins::PREFIX)); + let mut parsed: HashMap<(usize, usize), (Option>, bool)> = HashMap::new(); + let mut table = HashMap::new(); + for doc in docs { + if table.contains_key(&text_key(doc)) { + continue; + } + let mut live = false; + let mut parse = |doc: &'static str| { + let (keys, plugin) = parsed.entry(text_key(doc)).or_insert_with(|| { + let keys = doc_keys(doc).ok(); + let plugin = keys.as_ref().is_some_and(|k| k.more.iter().any(|m| names_plugin(m))); + (keys, plugin) + }); + live |= *plugin; + keys.clone() + }; + let own = parse(doc).map(|p| p.keys).unwrap_or_default(); + let accepted = resolve(doc, 0, &mut parse); + if live { + continue; + } + let mut known = Known { own, accepted, id_stands_for_ids: false }; + known.id_stands_for_ids = known.takes("ids") && known.takes("id") && no_required_id_beside_ids(doc); + table.insert(text_key(doc), known); + } + table +} + +/// [`Known`] of `doc` when it is the params description of a built-in command. +fn known(doc: &str) -> Option<&'static Known> { + #[cfg(test)] + if UNCACHED.get() { + return None; + } + static TABLE: OnceLock> = OnceLock::new(); + TABLE.get_or_init(|| read_descriptions(command_specs().iter().map(|c| c.params))).get(&text_key(doc)) +} + +#[cfg(test)] +thread_local! { + /// The times [`doc_keys`] parsed a description on this thread. + pub(crate) static PARSES: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// Whether [`known`] is skipped on this thread ([`uncached`]). + static UNCACHED: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Whether [`read_descriptions`] keeps what `doc` says. +#[cfg(test)] +pub(crate) fn read_once(doc: &'static str) -> bool { + read_descriptions([doc]).contains_key(&text_key(doc)) +} + +/// `f`'s result with every description parsed again where it is used, as without [`known`]. +#[cfg(test)] +pub(crate) fn uncached(f: impl FnOnce() -> T) -> T { + let before = UNCACHED.replace(true); + let out = f(); + UNCACHED.set(before); + out +} + /// Every key the description `doc` takes, those of the commands its `…` entries name included, or /// `None` when that isn't known: it doesn't parse, a `…` entry names no command, or one names a /// command in [`UNCHECKED`]. pub(crate) fn accepted_keys(doc: &'static str) -> Option> { - accepted(doc, 0) + match known(doc) { + Some(known) => known.accepted.clone(), + None => accepted(doc, 0), + } } /// Does the description `doc` name `key` as a parameter (its own keys, and those of the commands /// its `…` entries name)? pub fn takes_key(doc: &'static str, key: &str) -> bool { + if let Some(known) = known(doc) { + return known.takes(key); + } doc_keys(doc).is_ok_and(|parsed| parsed.keys.contains(&key)) || accepted(doc, 0).is_some_and(|keys| keys.contains(&key)) } @@ -191,12 +299,17 @@ pub fn takes_key(doc: &'static str, key: &str) -> bool { /// (instead of id)}`, `{id} or {ids: […]}`): it names both keys, and no params object of it names /// `ids` beside a required `id`, which is something else (`plugin.run {id, ids?}`: the plug-in's)? pub(crate) fn id_stands_for_ids(doc: &'static str) -> bool { + if let Some(known) = known(doc) { + return known.id_stands_for_ids; + } + takes_key(doc, "ids") && takes_key(doc, "id") && no_required_id_beside_ids(doc) +} + +/// No params object of `doc` names `ids` beside a required `id`. +fn no_required_id_beside_ids(doc: &str) -> bool { fn head(alternative: &str) -> &str { alternative.split([':', '=', '(']).next().unwrap_or_default().trim() } - if !takes_key(doc, "ids") || !takes_key(doc, "id") { - return false; - } let mut rest = doc; while let Ok((body, after)) = object_body(rest) { let entries = split_top(body, ','); @@ -249,9 +362,17 @@ pub fn check_keys(id: &str, doc: &'static str, params: &Value) -> Result<()> { if given.is_empty() { return Ok(()); } - let Some(keys) = accepted(doc, 0) else { return Ok(()) }; + let live; + let keys = match known(doc) { + Some(known) => known.accepted.as_deref(), + None => { + live = accepted(doc, 0); + live.as_deref() + } + }; + let Some(keys) = keys else { return Ok(()) }; match given.keys().find(|k| !keys.contains(&k.as_str())) { - Some(key) => Err(unknown(id, key, &keys)), + Some(key) => Err(unknown(id, key, keys)), None => Ok(()), } } @@ -933,9 +1054,14 @@ fn check_params_in(id: &str, params: &Value, in_batch: bool) -> Result<()> { crate::schemas::check(spec, params, false)?; } if matches!(id, "command.batch" | "action.batch") && !in_batch { - for step in params.get("commands").and_then(Value::as_array).into_iter().flatten() { + for (i, step) in params.get("commands").and_then(Value::as_array).into_iter().flatten().enumerate() { if let Some(step_id) = step.get("command").and_then(Value::as_str) { - check_params_in(step_id, step.get("params").unwrap_or(&Value::Null), true)?; + let checked = check_params_in(step_id, step.get("params").unwrap_or(&Value::Null), true); + // An `action.batch` names the step it refuses by its place, from 1, as its own checks and its steps' errors do. + match checked { + Err(e) if id == "action.batch" => return Err(bad(id, super::fileio::action_step(i, step_id, &e.to_string()))), + checked => checked?, + } } } } 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.rs b/crates/engine/src/cmd/plugin_call.rs index 6c23161a9d..867c1f2ff0 100644 --- a/crates/engine/src/cmd/plugin_call.rs +++ b/crates/engine/src/cmd/plugin_call.rs @@ -64,6 +64,7 @@ const DENIED_PREFIXES: &[&str] = &[ "edit.newDocument", "edit.colorSettings", "edit.dropSelection", + "symbol.placeFromDocument", "artboard.copy", "artboard.cut", "text.rescanFonts", 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/stroke.rs b/crates/engine/src/cmd/stroke.rs index 667e674d17..d1f147ffbe 100644 --- a/crates/engine/src/cmd/stroke.rs +++ b/crates/engine/src/cmd/stroke.rs @@ -220,8 +220,10 @@ fn own_stroke_or_leaves(s: &Session, p: &Value) -> Result, Vec<_>) = picked.into_iter().partition(own); + // A leaf already listed is skipped; a set keeps this linear in the number of leaves. + let mut seen: std::collections::HashSet = out.iter().copied().collect(); for id in super::leaf_targets(s, &rest)? { - if !out.contains(&id) { + if seen.insert(id) { out.push(id); } } @@ -429,6 +431,52 @@ impl Session { painted(first, true, &mut nodes); node_stroke(nodes.first()?) } + + /// Do all the strokes that `stroke.set` edits without `ids` or `item` draw with a brush + /// ([`vectorcraft_brush::keeps_brush_size`])? If they do, a width profile changes none of + /// them, and the result is `Some`, holding whether any of them has a width profile. The result + /// is `None` when a profile changes at least one of them. + /// + /// The strokes are the ones `stroke.set` edits: + /// - the Appearance panel's active stroke row in each target that has an equal row + /// ([`ItemTarget::per_target`]), and the top stroke in the others; + /// - else a selected group's own stroke; + /// - else the top strokes of the objects it paints ([`own_stroke_or_leaves`]). + /// + /// The art of graph designs is left out, and so are images and symbol instances without an + /// active row. The result is also `None` with nothing selected, with an object inside a symbol + /// instance selected, with type among the targets while no Appearance row is active for it, + /// and with a target that has no stroke row, since `stroke.set` gives such a target a plain + /// stroke. + pub fn brushed_strokes_profiled(&self) -> Option { + const C: &str = "stroke.set"; + let st = self.active()?; + if st.selected_symbol_part().is_some() { + return None; + } + let p = json!({}); + let item = item_target(self, &p, C).ok()?.of_kind(self, false); + let ids = if item == ItemTarget::Top { own_stroke_or_leaves(self, &p).ok()? } else { item.targets(self, &p).ok()? }; + let mut ids = super::appearance::drop_design_art_rows(self, ids, item, false, C).ok()?; + if item == ItemTarget::Top { + ids.retain(|id| !matches!(st.doc.node(*id).map(|n| &n.kind), Some(NodeKind::Image(_) | NodeKind::SymbolInstance { .. }))); + } + let mut strokes = vec![]; + for (id, each) in ids.iter().zip(item.per_target(self, &ids)) { + let n = st.doc.node(*id)?; + let row = each?.resolve(&n.appearance, false, C).ok()?; + if row.is_none() && matches!(n.kind, NodeKind::Text(_)) { + return None; + } + strokes.push(n.appearance.stroke_at(row).filter(|s| s.brush.is_some())?); + } + if strokes.is_empty() { + return None; + } + // The library is read only when every stroke names a brush. + let lib = vectorcraft_brush::library(&st.doc); + strokes.iter().all(|s| vectorcraft_brush::keeps_brush_size(&lib, s)).then(|| strokes.iter().any(|s| s.profile.is_some())) + } } impl DocState { @@ -678,6 +726,7 @@ fn profile_list(s: &mut Session, _: &Value) -> Result { #[cfg(test)] mod tests { use super::*; + use vectorcraft_doc::NodeId; #[test] fn weight_steps_follow_units_and_stop_at_their_bounds() { @@ -693,4 +742,93 @@ mod tests { assert!((step_weight(mm, Unit::Millimeters, true) - 2.0 * mm).abs() < 1e-9); assert!((step_weight(mm, Unit::Millimeters, false) - 0.75 * mm).abs() < 1e-9); } + + fn run(s: &mut Session, id: &str, p: Value) -> Value { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")) + } + + fn made(v: Value) -> NodeId { + NodeId(v["id"].as_u64().unwrap_or_else(|| panic!("no id in {v}"))) + } + + /// The targets of [`own_stroke_or_leaves`] merged by a linear search of the growing list. + fn listed_merge(s: &Session, p: &Value) -> Vec { + let d = &s.doc().unwrap().doc; + let own = |id: &NodeId| { + d.node(*id).is_some_and(|n| { + matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) && !n.is_compound_shape() && n.appearance.stroke().is_some() + }) + }; + let (mut out, rest): (Vec<_>, Vec<_>) = super::super::targets(s, p).unwrap().into_iter().partition(own); + for id in super::super::leaf_targets(s, &rest).unwrap() { + if !out.contains(&id) { + out.push(id); + } + } + out + } + + /// `stroke.set` with no `item` lists the same targets in the same order as a linear merge: + /// groups and layers with a stroke of their own (repeats kept), the leaves of plain groups and + /// layers, compound paths and compound shapes for their members, and each leaf once, also + /// when it is named both directly and through its group. + #[test] + fn stroke_targets_match_the_listed_merge() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 2000, "height": 400})); + let base = s.doc().unwrap().doc.layers[0].id; + let mut x = 0.0; + let mut rect = |s: &mut Session| { + x += 120.0; + made(run(s, "shape.rectangle", json!({"x": x, "y": 100, "width": 100, "height": 100}))) + }; + let (a, b) = (rect(&mut s), rect(&mut s)); + let plain = made(run(&mut s, "object.group", json!({"ids": [a.0, b.0]}))); + let (c, d) = (rect(&mut s), rect(&mut s)); + let owned = made(run(&mut s, "object.group", json!({"ids": [c.0, d.0]}))); + run(&mut s, "appearance.addStroke", json!({"ids": [owned.0]})); + let (e, f) = (rect(&mut s), rect(&mut s)); + run(&mut s, "select.set", json!({"ids": [e.0, f.0]})); + let compound = made(run(&mut s, "object.compoundPath.make", json!({}))); + let (g, h) = (rect(&mut s), rect(&mut s)); + run(&mut s, "select.set", json!({"ids": [g.0, h.0]})); + let shape = made(run(&mut s, "object.compoundShape.make", json!({}))); + let lone = rect(&mut s); + let layer = made(run(&mut s, "layer.new", json!({}))); + let (j, k) = (rect(&mut s), rect(&mut s)); + run(&mut s, "appearance.addStroke", json!({"ids": [layer.0]})); + { + let doc = &s.doc().unwrap().doc; + assert_eq!((doc.parent_of(j), doc.parent_of(k)), (Some(layer), Some(layer)), "the new layer holds the last two"); + assert_eq!((doc.parent_of(e), doc.parent_of(g)), (Some(compound), Some(shape))); + assert!(doc.node(owned).unwrap().appearance.stroke().is_some() && doc.node(layer).unwrap().appearance.stroke().is_some()); + } + let named = json!({"ids": [plain.0, a.0, owned.0, owned.0, c.0, e.0, compound.0, g.0, lone.0, layer.0, j.0]}); + let cases = [ + named.clone(), + json!({"ids": [j.0, h.0, f.0, b.0, plain.0, layer.0, owned.0, k.0, shape.0]}), + json!({"ids": [base.0, layer.0, base.0]}), + json!({"ids": [d.0, owned.0, base.0]}), + json!({"ids": []}), + ]; + for p in &cases { + assert_eq!(own_stroke_or_leaves(&s, p).unwrap(), listed_merge(&s, p), "{p}"); + } + run(&mut s, "select.set", json!({"ids": [lone.0, owned.0, f.0, plain.0, b.0, layer.0]})); + assert_eq!(own_stroke_or_leaves(&s, &json!({})).unwrap(), listed_merge(&s, &json!({})), "the selection"); + + // The edit reaches every listed target, counting a repeated one once, and leaves the other + // member of the group with its own stroke alone. + let want = listed_merge(&s, &named); + assert_eq!(want.iter().filter(|id| **id == owned).count(), 2, "{want:?}"); + let distinct: std::collections::HashSet<_> = want.iter().collect(); + let before = s.doc().unwrap().doc.node(d).unwrap().clone(); + let r = run(&mut s, "stroke.set", json!({"ids": named["ids"], "weight": 3})); + let doc = &s.doc().unwrap().doc; + assert_eq!(r["objects"], distinct.len(), "{r} {want:?}"); + for id in &want { + assert_eq!(doc.node(*id).unwrap().appearance.stroke().map(|st| st.width), Some(3.0), "{id:?}"); + } + assert_eq!(doc.node(d), Some(&before), "a member reached only through its group's own stroke is left alone"); + } } diff --git a/crates/engine/src/cmd/style.rs b/crates/engine/src/cmd/style.rs index 33c9ec67bb..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 ), @@ -318,8 +318,14 @@ impl Session { /// it is still linked (still has that style's look). A graph series group that holds nothing of its own stands /// for the topmost path directly inside it, which a style applied to the group links. pub fn selection_graphic_style(&self) -> Option<(&GraphicStyle, bool)> { + self.graphic_style_of(*self.active()?.selection.subjects().first()?) + } + + /// The graphic style of object `id` of the active document, as [`Self::selection_graphic_style`] + /// gives it for the first selected object. + pub fn graphic_style_of(&self, id: NodeId) -> Option<(&GraphicStyle, bool)> { let st = self.active()?; - let n = super::appearance::look_holder(&st.doc, st.doc.node(*st.selection.subjects().first()?)?); + let n = super::appearance::look_holder(&st.doc, st.doc.node(id)?); let g = st.doc.graphic_style_by_id(n.extras().graphic_style?)?; Some((g, in_sync(n, g))) } @@ -483,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, _| { @@ -507,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); @@ -515,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; @@ -524,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/symbollib.rs b/crates/engine/src/cmd/symbollib.rs index b82be77f43..3e4774a370 100644 --- a/crates/engine/src/cmd/symbollib.rs +++ b/crates/engine/src/cmd/symbollib.rs @@ -20,7 +20,7 @@ use super::clipboard::Clipboard; use super::clipboard::resources::SwatchChoices; use super::swatch::str_list; use super::swatchlib::{FileData, LibraryFile, LibraryInfo, concealed_library_id, concealed_library_ids, shown_id, shown_library_id, stem}; -use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, number_or, str_param}; +use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, number_or, str_param, u64_req}; /// The extension of saved symbol libraries: native documents. pub const SYMBOLS_EXT: &str = vectorcraft_format::EXTENSION; @@ -54,6 +54,15 @@ pub fn specs() -> Vec { has_doc, add ), + cmd!( + "symbol.placeFromDocument", + "Place Symbol Instance", + [], + None, + "{sourceDocument: uid, name: a symbol of that document, x?, y?} place an instance of a symbol of another open document so its registration point is at (x, y) (default: the first artboard's center), as a symbol dragged from that document's Symbols panel onto the canvas is placed. The symbol, the symbols it nests and the resources they use are added as a drop of art from that document adds them, in the same undo step as the instance: a symbol the active document already has with the same name, art and Symbol Options is used, and one with the same name but other art or Symbol Options gets a number (\"Leaf 2\"); each symbol added takes its Symbol Options along. When sourceDocument is the active document, its own symbol is placed, as symbol.place places it. An error, with no edit, when that document is no longer open or has no symbol `name` → {id, name: the symbol's name in the active document}", + has_doc, + place_from_document + ), cmd!( "symbol.saveLibrary", "Save Symbol Library…", @@ -630,6 +639,46 @@ fn add(s: &mut Session, p: &Value) -> Result { Ok(out) } +/// `symbol.placeFromDocument`: an instance of symbol `name` of the open document `sourceDocument` +/// placed in the active document, with the symbol and the resources it uses added as a drop of +/// art from that document adds them, in one undo step. The source document is not changed. +fn place_from_document(s: &mut Session, p: &Value) -> Result { + const C: &str = "symbol.placeFromDocument"; + let uid = u64_req(p, "sourceDocument", C)?; + let name = str_param(p, "name").ok_or_else(|| bad(C, "missing `name`"))?; + let st = s.doc()?; + let centre = st.doc.artboards.first().map(|a| a.rect.center()).unwrap_or(Point::ZERO); + let at = Point::new(number_or(p, "x", centre.x, C)?, number_or(p, "y", centre.y, C)?); + let parent = st.target_parent()?; + let same = uid == st.uid; + let src = s.documents().iter().find(|d| d.uid == uid).map(|d| Arc::clone(&d.doc)); + let src = src.ok_or_else(|| bad(C, "the document the symbol came from is no longer open"))?; + if !src.symbols.iter().any(|sym| sym.name == name) { + return Err(bad(C, format!("no symbol named `{name}` in the document it came from"))); + } + // A symbol of the active document itself is placed as it is. + let clip = (!same).then(|| Clipboard::gather(&src, vec![instance(name)])); + // The source's colors are kept even where the active document has swatches of the same names. + let choices = SwatchChoices::parse(C, &json!({"swatchConflict": "add"}))?; + let (id, placed) = s.edit("Place Symbol Instance", |d, sel| { + let placed = match &clip { + // Each symbol added takes its Symbol Options along. + Some(clip) => { + let imported = clip.import_into(d, &choices, false)?; + let renamed = imported.renamed.iter().find(|r| r["kind"] == "symbol" && r["from"] == name).and_then(|r| r["to"].as_str()); + renamed.unwrap_or(name).to_string() + } + None => name.to_string(), + }; + let xf = place_xf(at, natural_size(d, &placed), d.symbol_registration(&placed)); + let id = d.alloc_id(); + d.insert(parent, usize::MAX, Node::new(id, NodeKind::SymbolInstance { symbol: placed.clone(), xf }))?; + sel.set([id]); + Ok((id, placed)) + })?; + Ok(json!({ "id": id.0, "name": placed })) +} + fn save(s: &mut Session, p: &Value) -> Result { const C: &str = "symbol.saveLibrary"; let st = s.doc()?; 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/doc_state.rs b/crates/engine/src/doc_state.rs index 9cbdfb6827..cabc774737 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -25,6 +25,10 @@ pub struct DocState { /// Panel state, not art selection: not saved, not undoable (`layer.setCurrent`, /// `layer.highlight`). pub layer_rows: Vec, + /// The row the last Locate Object or Locate Layer (`layer.locate`) highlighted, until the + /// Layers panel takes it: the panel opens the layers around that row and scrolls to it, also + /// when the row was already highlighted. Panel state: not saved, not undoable. + pub locate_reveal: Option, /// The variable highlighted in the Variables panel: what its Delete, Options… and Select /// Bound Object act on. Panel state, not art selection: not saved, not undoable /// (`variable.highlight`). A name, so renaming a variable moves the highlight with it. @@ -136,6 +140,10 @@ pub struct DocState { /// same document comes to the front, its type set in them is not measured again. While this /// reference lasts, its allocation holds no other document. Not saved. pub(crate) measured_in_own: Option<(std::sync::Weak, std::collections::HashSet)>, + /// The document as the last edit's refresh of inline graphics left it, and what that refresh + /// measured: the next refresh checks only the layer trees that differ from it + /// ([`cmd::inline::refresh`]). Not saved. + pub(crate) inline_resolved: Option, } /// Whether a document has an artboard for Delete Empty Artboards to delete, with the document that @@ -318,6 +326,7 @@ impl DocState { revision: 1, active_layer, layer_rows: vec![], + locate_reveal: None, variables_highlight: None, variables_sort: Default::default(), isolation: None, @@ -355,6 +364,7 @@ impl DocState { plugin_effects: Default::default(), art_to_fit: Default::default(), measured_in_own: None, + inline_resolved: None, } } /// `measure`'s answer for the document now. `measure` runs once for each version of the document, diff --git a/crates/engine/src/history.rs b/crates/engine/src/history.rs index 3ab6a7dcb8..d472ec760c 100644 --- a/crates/engine/src/history.rs +++ b/crates/engine/src/history.rs @@ -32,6 +32,9 @@ pub struct HistoryEntry { pub(crate) color_mode_paints: Option<(vectorcraft_tools::PaintDefaults, vectorcraft_tools::PaintDefaults)>, /// Owned new-art snapshots included in both directional estimates. color_mode_bytes: usize, + /// The state that changes without an undo step as the next state had it: undo and redo compare + /// it with `doc` to tell what the step changed. + pub(crate) unrecorded: Arc, } impl Clone for HistoryEntry { @@ -49,6 +52,7 @@ impl Clone for HistoryEntry { serial: self.serial, color_mode_paints: self.color_mode_paints.clone(), color_mode_bytes: self.color_mode_bytes, + unrecorded: self.unrecorded.clone(), } } } @@ -94,6 +98,7 @@ impl HistoryEntry { serial: next_serial(), color_mode_paints: None, color_mode_bytes: 0, + unrecorded: Arc::new(crate::cmd::Unrecorded::of(next)), } } @@ -126,6 +131,7 @@ impl HistoryEntry { serial: next_serial(), color_mode_paints: None, color_mode_bytes: 0, + unrecorded: Arc::new(crate::cmd::Unrecorded::of(now)), } } @@ -337,6 +343,7 @@ impl History { e.next_bytes = after.saturating_add(e.color_mode_bytes); e.next = std::ptr::from_ref(now) as usize; e.serial = next_serial(); + e.unrecorded = Arc::new(crate::cmd::Unrecorded::of(now)); } } } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 7f4f49852d..de780f406c 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -28,7 +28,7 @@ use vectorcraft_tools::{PaintDefaults, Tool}; pub use cmd::clipboard::{Clipboard, SourceLayer}; pub use cmd::create::constrain_click; -pub use cmd::distortcmds::perspective_click; +pub use cmd::distortcmds::{perspective_click, width_point_pair}; pub use cmd::graph::{GraphTypeSubject, calculated_axes as graph_calculated_axes, graph_type_subject}; pub use cmd::params::{check_keys, check_params}; pub use cmd::pathops::auto_simplify_level; @@ -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 8c0f3e8803..ce0c2998fe 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -53,7 +53,8 @@ impl Session { let mut symbol_synced = if st.doc.symbol_edit.is_some() { cmd::symboledit::sync(&before, Arc::make_mut(&mut st.doc)) } else { Ok(()) }; // Inline graphics in text follow their symbols. - cmd::inline::refresh(&before, Arc::make_mut(&mut st.doc)); + let measured = cmd::inline::refresh(st.inline_resolved.as_ref(), &before, Arc::make_mut(&mut st.doc)); + let mut resolved = measured.map(|m| (st.doc.clone(), m)); // The document the passes below start from, for the symbol to follow what they // change on its editing layer. let synced = st.doc.symbol_edit.is_some().then(|| st.doc.clone()); @@ -86,7 +87,10 @@ impl Session { let new = art(&st.doc); if symbol_synced.is_ok() && !matches!((&old, &new), (Some(a), Some(b)) if Arc::ptr_eq(a, b)) { let resynced = st.doc.clone(); - cmd::inline::refresh(synced, Arc::make_mut(&mut st.doc)); + let last = resolved.as_ref().or(st.inline_resolved.as_ref()); + if let Some(m) = cmd::inline::refresh(last, synced, Arc::make_mut(&mut st.doc)) { + resolved = Some((st.doc.clone(), m)); + } if !st.doc.text_threads.is_empty() { cmd::threads::reflow(&resynced, Arc::make_mut(&mut st.doc)); } @@ -100,6 +104,7 @@ impl Session { if !st.doc.variables.bindings.is_empty() { Arc::make_mut(&mut st.doc).prune_variable_bindings(); } + st.inline_resolved = resolved; if let Err(e) = symbol_synced { Err(e) } else if st.doc.too_deep(Some(&before)) { @@ -437,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 a16f01cfa0..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; @@ -122,6 +123,7 @@ mod paintproxy; mod panelcmds; mod paragraphs; mod params; +mod params_cache; mod path_menu_enabled; mod pathfinder_clip; mod pathops; @@ -371,9 +373,12 @@ fn a_long_unknown_command_id_is_answered_at_once() { fn action_batch_names_the_nearest_command_id() { let mut s = session(); let e = s.execute("action.batch", &json!({"source": "dataSets", "commands": [{"command": "select.al"}]})).unwrap_err(); - assert_eq!(e.to_string(), "invalid parameters for `action.batch`: commands[0]: unknown command `select.al`; did you mean `select.all`?"); + assert_eq!( + e.to_string(), + "invalid parameters for `action.batch`: action step 1 (`select.al`) failed: unknown command `select.al`; did you mean `select.all`?" + ); let e = s.execute("action.batch", &json!({"source": "dataSets", "commands": [{"command": "nope"}]})).unwrap_err(); - assert_eq!(e.to_string(), "invalid parameters for `action.batch`: commands[0]: unknown command `nope`"); + assert_eq!(e.to_string(), "invalid parameters for `action.batch`: action step 1 (`nope`) failed: unknown command `nope`"); } #[test] @@ -3215,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/appearance.rs b/crates/engine/src/tests/appearance.rs index 53cbb42ca9..a04bb89b4a 100644 --- a/crates/engine/src/tests/appearance.rs +++ b/crates/engine/src/tests/appearance.rs @@ -227,6 +227,112 @@ fn stroke_options_on_a_group_with_its_own_stroke_edit_that_stroke() { assert_eq!((st.paint, st.width), (Paint::solid(Color::BLACK), 3.0)); } +/// `brushed_strokes_profiled` reads the strokes `stroke.set` edits: a group's own stroke when it +/// has one, else its members'. It answers only while each of them draws with a brush, and not +/// while an object has no stroke row, which `stroke.set` would give a plain stroke. +#[test] +fn brushed_strokes_profiled_reads_the_strokes_stroke_set_edits() { + let mut s = session(); + let (a, b) = (rect(&mut s, 100.0), rect(&mut s, 250.0)); + run(&mut s, "brush.apply", json!({"ids": [a.0, b.0], "name": "3 pt. Round"})); + run(&mut s, "select.set", json!({"ids": [a.0, b.0]})); + assert_eq!(s.brushed_strokes_profiled(), Some(false), "both draw with a brush, neither has a profile"); + run(&mut s, "stroke.set", json!({"ids": [b.0], "profile": "lens"})); + run(&mut s, "select.set", json!({"ids": [a.0, b.0]})); + assert_eq!(s.brushed_strokes_profiled(), Some(true), "one has a profile"); + let g = NodeId(run(&mut s, "object.group", json!({"ids": [a.0, b.0]}))["id"].as_u64().unwrap()); + run(&mut s, "select.set", json!({"ids": [g.0]})); + assert_eq!(s.brushed_strokes_profiled(), Some(true), "a group without its own stroke: its members'"); + run(&mut s, "appearance.addStroke", json!({"ids": [g.0]})); + run(&mut s, "select.set", json!({"ids": [g.0]})); + assert_eq!(s.brushed_strokes_profiled(), None, "the group's own plain stroke takes the profile"); + let c = rect(&mut s, 400.0); + run(&mut s, "appearance.removeItem", json!({"ids": [c.0], "index": 1})); + assert!(node(&s, c).appearance.stroke().is_none()); + run(&mut s, "select.set", json!({"ids": [a.0, c.0]})); + assert_eq!(s.brushed_strokes_profiled(), None, "an object without a stroke row takes a plain stroke"); +} + +/// A compound shape's own stroke is the one `stroke.set` edits: brushed members do not count. +#[test] +fn brushed_strokes_profiled_reads_a_compound_shapes_own_stroke() { + let mut s = session(); + let (a, b) = (rect(&mut s, 100.0), rect(&mut s, 120.0)); + run(&mut s, "select.set", json!({"ids": [a.0, b.0]})); + let c = NodeId(run(&mut s, "object.compoundShape.make", json!({"mode": "add"}))["id"].as_u64().unwrap()); + assert!(node(&s, c).appearance.stroke().is_some_and(|st| st.brush.is_none()), "the compound shape's own plain stroke"); + s.edit("Brush", |d, _| { + for id in [a, b] { + if let Some(st) = d.node_mut(id).and_then(|n| n.appearance.stroke_mut()) { + st.brush = Some("3 pt. Round".into()); + } + } + Ok(()) + }) + .unwrap(); + run(&mut s, "select.set", json!({"ids": [c.0]})); + assert_eq!(s.brushed_strokes_profiled(), None); + s.edit("Brush", |d, _| { + d.node_mut(c).unwrap().appearance.stroke_mut().unwrap().brush = Some("3 pt. Round".into()); + Ok(()) + }) + .unwrap(); + run(&mut s, "select.set", json!({"ids": [c.0]})); + assert_eq!(s.brushed_strokes_profiled(), Some(false)); +} + +/// A targeted layer with its own plain Stroke row active: `stroke.set` edits that row, so the +/// brushed path inside the layer does not count. +#[test] +fn brushed_strokes_profiled_reads_a_targeted_layers_active_stroke_row() { + let mut s = session(); + let a = rect(&mut s, 100.0); + run(&mut s, "brush.apply", json!({"ids": [a.0], "name": "3 pt. Round"})); + let layer = s.doc().unwrap().doc.layers[0].id; + run(&mut s, "layer.target", json!({"id": layer.0})); + run(&mut s, "appearance.addStroke", json!({})); + let rows = &node(&s, layer).appearance.items; + let index = rows.iter().position(|it| matches!(it, AppearanceItem::Stroke(st) if st.brush.is_none())).expect("the layer's own stroke row"); + run(&mut s, "appearance.setActiveItem", json!({"index": index})); + assert_eq!(s.brushed_strokes_profiled(), None, "the layer's plain stroke takes the profile"); + run(&mut s, "stroke.set", json!({"profile": "lens"})); + assert!(node(&s, layer).appearance.items.get(index).is_some_and(|it| matches!(it, AppearanceItem::Stroke(st) if st.profile.is_some()))); + assert!(node(&s, a).appearance.stroke().is_some_and(|st| st.profile.is_none()), "the brushed path is left as it was"); +} + +/// A symbol instance selected with a brushed path takes no stroke from `stroke.set`, so it does +/// not count; the brushed path alone decides. +#[test] +fn brushed_strokes_profiled_leaves_out_symbol_instances() { + let mut s = session(); + let a = rect(&mut s, 100.0); + run(&mut s, "brush.apply", json!({"ids": [a.0], "name": "3 pt. Round"})); + let r = rect(&mut s, 300.0); + run(&mut s, "select.set", json!({"ids": [r.0]})); + let inst = NodeId(run(&mut s, "symbol.new", json!({"name": "Dot"}))["id"].as_u64().unwrap()); + assert!(matches!(node(&s, inst).kind, NodeKind::SymbolInstance { .. })); + run(&mut s, "select.set", json!({"ids": [a.0, inst.0]})); + assert_eq!(s.brushed_strokes_profiled(), Some(false)); +} + +/// With the active row a stroke of the first object that another selected object has no equal +/// row for, `stroke.set` edits that object's top stroke, so its top stroke decides. +#[test] +fn brushed_strokes_profiled_falls_back_to_the_top_stroke_where_the_active_row_has_no_match() { + let mut s = session(); + let (a, b) = (rect(&mut s, 100.0), rect(&mut s, 250.0)); + run(&mut s, "select.set", json!({"ids": [a.0]})); + run(&mut s, "appearance.addStroke", json!({})); + run(&mut s, "brush.apply", json!({"ids": [a.0, b.0], "name": "3 pt. Round"})); + run(&mut s, "stroke.set", json!({"ids": [b.0], "weight": 5})); + let rows = &node(&s, a).appearance.items; + let index = rows.iter().position(|it| matches!(it, AppearanceItem::Stroke(st) if st.brush.is_some())).expect("a's brushed stroke"); + assert!(index >= node(&s, b).appearance.items.len() || node(&s, b).appearance.items[index].is_fill(), "{rows:?}"); + run(&mut s, "select.set", json!({"ids": [a.0, b.0]})); + run(&mut s, "appearance.setActiveItem", json!({"index": index})); + assert_eq!(s.brushed_strokes_profiled(), Some(false), "b's top stroke has the brush too"); +} + #[test] fn text_items_take_item_paint() { let mut s = session(); diff --git a/crates/engine/src/tests/assets.rs b/crates/engine/src/tests/assets.rs index 1d571884a0..fff9ed9588 100644 --- a/crates/engine/src/tests/assets.rs +++ b/crates/engine/src/tests/assets.rs @@ -302,6 +302,23 @@ fn the_shared_settings_drive_the_export_and_arent_an_undo_step() { assert_eq!(run(&mut s, "document.exportSettings", json!({}))["settings"]["formats"][0]["format"], "jpg"); } +/// The shared settings are not an undo step, so undo and redo of the steps before them leave them +/// as they are. +#[test] +fn undo_and_redo_keep_the_shared_settings() { + let mut s = session(); + let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0); + run(&mut s, "assets.add", json!({"ids": [a]})); + run(&mut s, "assets.settings.set", json!({"formats": [{"format": "svg"}], "prefix": "ic_"})); + let settings = run(&mut s, "document.exportSettings", json!({}))["settings"].clone(); + run(&mut s, "edit.undo", json!({})); + assert_eq!(run(&mut s, "document.exportSettings", json!({}))["settings"], settings); + run(&mut s, "assets.settings.set", json!({"formats": [{"format": "jpg"}], "prefix": ""})); + let settings = run(&mut s, "document.exportSettings", json!({}))["settings"].clone(); + run(&mut s, "edit.redo", json!({})); + assert_eq!(run(&mut s, "document.exportSettings", json!({}))["settings"], settings); +} + /// An export preset sets the shared settings as the Asset Export panel applies one: its rows (or /// mobile/density), its format settings over the saved ones, its prefix and its sub-folders. #[test] diff --git a/crates/engine/src/tests/brushsym.rs b/crates/engine/src/tests/brushsym.rs index 7e3ce00834..3a3a07a2c1 100644 --- a/crates/engine/src/tests/brushsym.rs +++ b/crates/engine/src/tests/brushsym.rs @@ -1289,6 +1289,29 @@ fn brush_freehand_continued_by_one_point_follows_keep_selected() { assert_eq!(s.doc().unwrap().history.undo.len(), undo, "the same brush again: no undo step"); } +/// A `brush.freehand` call that continues a path by one point with a bad `connect` is refused +/// before the path's brush changes: the brush, the selection and the undo history stay as they were. +#[test] +fn brush_freehand_continued_by_one_point_refuses_a_bad_connect() { + let mut s = session(); + let r = s.execute("brush.freehand", &json!({"points": [[10, 10], [60, 40], [120, 10]], "style": "brush", "brush": "Charcoal"})).unwrap(); + let p = NodeId(r["id"].as_u64().unwrap()); + let a = rect(&mut s, 200.0, 200.0, 10.0, 10.0); + select(&mut s, &[a]); + let undo = undo_steps(&s); + let one = json!({"points": [[120, 10]], "extend": {"id": p.0, "end": "end"}, "brush": "Dots"}); + for connect in + [json!({"id": p.0, "end": "end"}), json!({"id": a.0, "end": "middle"}), json!({"end": "end"}), json!({"id": 999_999, "end": "end"})] + { + let mut params = one.clone(); + params["connect"] = connect; + assert!(s.execute("brush.freehand", ¶ms).is_err(), "{params}"); + assert_eq!(brush_of(&s, p).as_deref(), Some("Charcoal"), "{params}: the brush stays"); + assert_eq!(selected(&s), [a], "{params}: the selection stays"); + assert_eq!(undo_steps(&s), undo, "{params}: no undo step"); + } +} + /// `brush.freehand` refuses a brush for a path with no stroke (a continued path, a redrawn one /// and a new filled pencil path while the stroke is None) instead of reporting it painted: the /// document, the selection and the undo history stay as they were. Without a brush the path is @@ -1400,6 +1423,40 @@ fn paintbrush_tool_uses_the_current_brush() { assert!(s.execute("brush.setCurrent", &json!({"name": "Nope"})).is_err()); } +/// The current brush and symbol are not undo steps, so undo and redo of other steps leave them as +/// they are. With nothing else changed outside the history, undo back to the saved document leaves +/// it saved. +#[test] +fn undo_and_redo_keep_the_current_brush_and_symbol() { + let mut s = session(); + rect(&mut s, 10.0, 10.0, 20.0, 20.0); + s.execute("symbol.new", &json!({"name": "A"})).unwrap(); + rect(&mut s, 40.0, 10.0, 20.0, 20.0); + s.execute("symbol.new", &json!({"name": "B"})).unwrap(); + s.doc_mut().unwrap().mark_saved(); + rect(&mut s, 70.0, 10.0, 20.0, 20.0); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(!s.doc().unwrap().is_dirty(), "back at the saved document"); + s.execute("edit.redo", &json!({})).unwrap(); + s.execute("brush.setCurrent", &json!({"name": "Arrow"})).unwrap(); + s.execute("symbol.setCurrent", &json!({"name": "A"})).unwrap(); + let current = |s: &mut Session| { + let brush = s.execute("brush.list", &json!({})).unwrap()["current"].clone(); + (brush, s.execute("symbol.list", &json!({})).unwrap()["current"].clone()) + }; + let want = (json!("Arrow"), json!("A")); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(current(&mut s), want); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(current(&mut s), want); + // A symbol made current between undoing and redoing its deletion is not kept as current. + s.execute("symbol.delete", &json!({"name": "B"})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("symbol.setCurrent", &json!({"name": "B"})).unwrap(); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.unknown.get("currentSymbol"), Some(&json!("A"))); +} + /// A Size: Pressure variant of "3 pt. Round" (3 ± 3 pt). fn pressure_round(s: &mut Session) { let params = json!({"variation": [0, 0, 3], "modes": ["fixed", "fixed", "pressure"]}); @@ -1569,6 +1626,34 @@ fn paintbrush_records_the_pens_tilt_on_the_stroke() { assert_eq!(back.node(pen).unwrap().appearance.stroke(), doc.node(pen).unwrap().appearance.stroke()); } +/// A Bristle path made from pen samples keeps its input when saved and uses it when exported. +#[test] +fn bristle_path_keeps_and_draws_its_pen_pose() { + let mut s = session(); + let id = NodeId( + s.execute( + "brush.freehand", + &json!({"points": [[20, 60, 0.1, 10, 0, 0], [200, 60, 0.9, 35, 0, 90]], "style": "brush", "brush": "Bristle Round"}), + ) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + let doc: Document = (*s.doc().unwrap().doc).clone(); + let st = doc.node(id).unwrap().appearance.stroke().unwrap(); + assert!(st.pressure.is_some() && st.tilt.is_some() && st.bearing.is_some() && st.rotation.is_some()); + let back = vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap(); + assert_eq!(back.node(id).unwrap().appearance.stroke(), Some(st)); + + let mut neutral = doc.clone(); + let st = neutral.node_mut(id).unwrap().appearance.stroke_mut().unwrap(); + st.pressure = None; + st.tilt = None; + st.bearing = None; + st.rotation = None; + assert_ne!(vectorcraft_svg::export(&doc, &Default::default()), vectorcraft_svg::export(&neutral, &Default::default())); +} + /// Pen pressure belongs to its path: new art, graphic styles and Brush Options' edits leave it. #[test] fn pressure_stays_with_its_own_path() { @@ -1612,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(); @@ -2074,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/build.rs b/crates/engine/src/tests/build.rs index 52c6ffa271..dfab5336de 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -1083,6 +1083,36 @@ fn shape_builder_drops_a_press_held_during_a_merge() { } } +/// When `tool.setOption` names no tool, the option is set on the tool that was active when the +/// call arrived (the Shape Builder), even when finishing its merge replays a held Cmd press that +/// switches to the Selection tool. +#[test] +fn shape_builder_option_set_while_a_cmd_press_is_held_goes_to_the_shape_builder() { + let v = ViewInfo::default(); + let mut s = session(); + s.select_tool("shapeBuilder", v).unwrap(); + s.set_tool_option_cmd(&json!({"key": "pickColorFrom", "value": "swatches"})).unwrap(); + square_row(&mut s); + click_row(&mut s, v); + s.pointer(&PointerEvent::new(PointerKind::Down, 305.0, 10.0).with_mods(Mods { cmd: true, ..Default::default() }), v).unwrap(); + assert!(s.tool_editing(), "the press is held"); + let out = s.set_tool_option_cmd(&json!({"key": "pickColorFrom", "value": "artwork"})).unwrap(); + assert_eq!(s.tool_id(), "selection", "the held press lent the selection tool"); + assert_eq!(s.lender.as_ref().map(|t| t.id()), Some("shapeBuilder")); + assert_eq!(out["pickColorFrom"], json!("artwork")); + assert_eq!(s.lender.as_ref().map(|t| t.options()["pickColorFrom"].clone()), Some(json!("artwork"))); + // Named while it waits, the Shape Builder is read where it waits, not made afresh from the + // preferences. + s.lender.as_mut().unwrap().set_option("pickColorFrom", &json!("swatches")); + let read = s.set_tool_option_cmd(&json!({"tool": "shapeBuilder"})).unwrap(); + assert_eq!(read["pickColorFrom"], json!("swatches"), "read from the waiting tool"); + // A value set on it counts as set on the tool chosen. + s.tool_set_since_reset = false; + s.set_tool_option_cmd(&json!({"tool": "shapeBuilder", "key": "highlightFill", "value": false})).unwrap(); + assert!(s.tool_set_since_reset(), "the tool chosen was set"); + assert_eq!(s.lender.as_ref().map(|t| t.options()["highlightFill"].clone()), Some(json!(false))); +} + /// A new revision of the document made outside a command while a merge is computed on another /// thread keeps the merge when the selected art is as it was (the next poll applies it, as the /// command computes it), and drops it when the art changed. diff --git a/crates/engine/src/tests/circle_through.rs b/crates/engine/src/tests/circle_through.rs index 25fcc04beb..e91c48e76a 100644 --- a/crates/engine/src/tests/circle_through.rs +++ b/crates/engine/src/tests/circle_through.rs @@ -1,5 +1,6 @@ -//! `shape.circleThroughPoints`: a circle through three given points, or through the three anchor -//! points selected with Direct Selection, and the Ellipse tool's three Shift-clicks that run it. +//! `shape.circleThroughPoints`: a circle through two or three given points, or through the two or +//! three anchor points selected with Direct Selection, the Ellipse tool's three Shift-clicks that +//! run it, and the Circle tool. use serde_json::{Value, json}; use vectorcraft_doc::{LiveShape, Node, NodeKind}; @@ -95,13 +96,42 @@ fn coincident_or_collinear_points_are_refused() { assert!((r - want).abs() / want < 1e-9 && (cx - 200.0).abs() < 1e-6 && (cy - (199.99 + want)).abs() / want < 1e-9, "{out}"); } -/// Points that are not three pairs of finite numbers are an error, not a fallback. +/// Two points are the ends of a diameter: (20, 40) and (100, 100) give the circle centered at +/// (60, 70) with radius 50, through both points, in one undo step. Two points that are the same +/// are refused, and so is a circle that would reach past the canvas, from two points or from three +/// nearly on one line; nothing is drawn and no undo step is recorded. +#[test] +fn two_points_are_the_ends_of_a_diameter() { + let mut s = session(); + let undo = undo_len(&s); + let out = s.execute(C, &json!({"points": [[20, 40], [100, 100]]})).unwrap(); + assert_eq!((out["cx"].as_f64(), out["cy"].as_f64(), out["radius"].as_f64()), (Some(60.0), Some(70.0), Some(50.0)), "{out}"); + let id = id_of(&out); + assert!(bounds_are(&s, id, vectorcraft_geom::Rect::new(10.0, 20.0, 110.0, 120.0))); + assert!(farthest_from_path(&s, id, &[Point::new(20.0, 40.0), Point::new(100.0, 100.0)]) < 50.0 * 3e-4); + assert_eq!(s.doc().unwrap().selection.objects, [id]); + assert_eq!(undo_len(&s), undo + 1); + let (undo, count) = (undo_len(&s), object_count(&s)); + let e = s.execute(C, &json!({"points": [[30, 30], [30, 30]]})).unwrap_err().to_string(); + assert!(e.contains("no circle passes through these points"), "{e}"); + // 4,100,000 pt across, past the canvas's 4,000,000 pt from the origin; and three points 0.001 pt + // off a chord 200 pt long, whose circle has a radius of about 5,000,000 pt. + for points in [json!([[0, 0], [4_100_000, 0]]), json!([[0, 0], [200, 0], [100, 0.001]])] { + let e = s.execute(C, &json!({ "points": points })).unwrap_err().to_string(); + assert!(e.contains("result would exceed the canvas"), "{points}: {e}"); + } + assert_eq!((undo_len(&s), object_count(&s)), (undo, count)); +} + +/// Points that are not two or three pairs of finite numbers are an error, not a fallback. #[test] fn malformed_points_are_refused() { let mut s = session(); let undo = undo_len(&s); for points in [ - json!([[0, 0], [10, 0]]), + json!([[0, 0]]), + json!([]), + json!([[0, 0], [10]]), json!([[0, 0], [10, 0], [0, 10], [5, 5]]), json!([[0, 0], [10, 0], [0]]), json!([[0, 0], [10, 0], ["0", 10]]), @@ -109,12 +139,12 @@ fn malformed_points_are_refused() { json!([[0, 0], [10, 0], [0, 10, 3]]), ] { let e = s.execute(C, &json!({ "points": points })).unwrap_err().to_string(); - assert!(e.contains("`points` must be three [x, y] pairs of numbers"), "{points}: {e}"); + assert!(e.contains("`points` must be two or three [x, y] pairs of numbers"), "{points}: {e}"); } assert_eq!(undo_len(&s), undo); } -/// With `points` left out, the three anchor points selected with Direct Selection give the +/// With `points` left out, the two or three anchor points selected with Direct Selection give the /// circle, from one path or several; any other number of them is an error. #[test] fn three_direct_selected_anchor_points_give_the_circle() { @@ -130,11 +160,15 @@ fn three_direct_selected_anchor_points_give_the_circle() { s.execute("select.anchors", &json!({"id": other.0, "anchors": [[0, 0]], "mode": "add"})).unwrap(); let out = s.execute(C, &json!({"points": null})).unwrap(); assert_eq!((out["cx"].as_f64(), out["cy"].as_f64()), (Some(40.0), Some(30.0)), "{out}"); - // Two or four anchors, or a path of four anchors selected whole. - for picked in [json!([[0, 0], [0, 1]]), json!([[0, 0], [0, 1], [0, 2], [0, 3]])] { + // Two anchors are the ends of a diameter: (0, 0) and (80, 0). + s.execute("select.anchors", &json!({"id": path.0, "anchors": [[0, 0], [0, 1]], "mode": "set"})).unwrap(); + let out = s.execute(C, &json!({})).unwrap(); + assert_eq!((out["cx"].as_f64(), out["cy"].as_f64(), out["radius"].as_f64()), (Some(40.0), Some(0.0), Some(40.0)), "{out}"); + // One or four anchors, or a path of four anchors selected whole. + for picked in [json!([[0, 0]]), json!([[0, 0], [0, 1], [0, 2], [0, 3]])] { s.execute("select.anchors", &json!({"id": path.0, "anchors": picked, "mode": "set"})).unwrap(); let e = s.execute(C, &json!({})).unwrap_err().to_string(); - assert!(e.contains("direct-select three anchor points, or give `points`"), "{picked}: {e}"); + assert!(e.contains("direct-select two or three anchor points, or give `points`"), "{picked}: {e}"); } s.execute("select.set", &json!({"ids": [path.0]})).unwrap(); assert!(s.execute(C, &json!({})).is_err()); @@ -153,7 +187,7 @@ fn three_direct_selected_anchor_points_give_the_circle() { s.execute("select.segments", &json!({"id": path.0, "segments": [[0, 0], [0, 1]], "mode": "set"})).unwrap(); assert_eq!(s.doc().unwrap().selection.anchors.get(&path).map(|a| a.len()), Some(3)); let e = s.execute(C, &json!({})).unwrap_err().to_string(); - assert!(e.contains("direct-select three anchor points, or give `points`"), "{e}"); + assert!(e.contains("direct-select two or three anchor points, or give `points`"), "{e}"); assert_eq!(undo_len(&s), undo); } diff --git a/crates/engine/src/tests/colormgmt.rs b/crates/engine/src/tests/colormgmt.rs index 2d024f552b..660b24d6f6 100644 --- a/crates/engine/src/tests/colormgmt.rs +++ b/crates/engine/src/tests/colormgmt.rs @@ -594,6 +594,78 @@ fn separations_preview_compares_the_visible_plates_as_a_set() { assert!(r["plates"].as_array().unwrap().iter().all(|p| p["visible"] == false), "{r}"); } +/// Each plate's visibility in a `view.separationsPreview` or `color.plates` reply, in plate order. +fn visible_plates(r: &Value) -> Vec { + r["plates"].as_array().unwrap().iter().map(|p| p["visible"].as_bool().unwrap()).collect() +} + +/// A session whose document has the process plates and the spot plate `Brand Orange`. +fn session_with_spot_plate() -> Session { + let mut s = session(); + s.execute("swatch.new", &json!({"name": "Brand Orange", "color": {"c": 0, "m": 60, "y": 100, "k": 0}, "global": true})).unwrap(); + s.execute("swatch.setSpot", &json!({"name": "Brand Orange"})).unwrap(); + let a = NodeId(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setFill", &json!({"ids": [a.0], "swatch": "Brand Orange"})).unwrap(); + s +} + +/// `soloToggle` (the panel's Alt-click on a plate's eye) shows that plate alone, and every plate +/// when it already shows alone. A hidden plate, a plate among others, another solo plate and an +/// empty set of plates all give the named plate alone. It leaves the document's undo list and +/// modified state alone. +#[test] +fn separations_preview_solo_toggle_shows_every_plate_the_second_time() { + let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let _v = DefaultView::new(); + let mut s = session_with_spot_plate(); + let undo = s.doc().unwrap().history.undo.len(); + let dirty = s.doc().unwrap().is_dirty(); + let solo = |s: &mut Session, n: &str| visible_plates(&s.execute("view.separationsPreview", &json!({"soloToggle": n})).unwrap()); + // Off: the preview turns on with the plate alone. + assert_eq!(solo(&mut s, "Cyan"), [true, false, false, false, false]); + assert_eq!(vectorcraft_render::proof::view().separations, Some(vec!["Cyan".to_string()])); + // The same plate again: every plate, the spot plate included, and the preview stays on. + assert_eq!(solo(&mut s, "Cyan"), [true; 5]); + assert!(vectorcraft_render::proof::view().separations.is_some(), "the preview stays on"); + // A plate shown among others, then another plate while one shows alone. + assert_eq!(solo(&mut s, "Magenta"), [false, true, false, false, false]); + assert_eq!(solo(&mut s, "Cyan"), [true, false, false, false, false]); + // A hidden plate. + s.execute("view.separationsPreview", &json!({"toggle": "Black"})).unwrap(); + assert_eq!(solo(&mut s, "Yellow"), [false, false, true, false, false]); + // No plate shown. + s.execute("view.separationsPreview", &json!({"plates": []})).unwrap(); + assert_eq!(solo(&mut s, "Black"), [false, false, false, true, false]); + // The spot plate alone, then every plate. + assert_eq!(solo(&mut s, "Brand Orange"), [false, false, false, false, true]); + assert_eq!(solo(&mut s, "Brand Orange"), [true; 5]); + // A plate the document doesn't have is an error and leaves the view as it is. + let before = vectorcraft_render::proof::view(); + assert!(s.execute("view.separationsPreview", &json!({"soloToggle": "Mauve"})).is_err()); + assert_eq!(vectorcraft_render::proof::view(), before); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step"); + assert_eq!(s.doc().unwrap().is_dirty(), dirty, "not marked modified"); + // `only` stays a setter: the same plate again keeps it alone. + s.execute("view.separationsPreview", &json!({"only": "Cyan"})).unwrap(); + let r = s.execute("view.separationsPreview", &json!({"only": "Cyan"})).unwrap(); + assert_eq!(visible_plates(&r), [true, false, false, false, false]); +} + +/// A plate counts as shown alone when no other plate of the active document shows: names left in +/// the visible set by another document's plates don't count. +#[test] +fn separations_preview_solo_toggle_counts_the_active_documents_plates() { + let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let _v = DefaultView::new(); + let mut s = session_with_spot_plate(); + s.execute("view.separationsPreview", &json!({"plates": ["Cyan", "Brand Orange"]})).unwrap(); + // A new document without the spot plate: Cyan is the only one of its plates shown. + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + assert_eq!(visible_plates(&s.execute("color.plates", &json!({})).unwrap()), [true, false, false, false]); + let r = s.execute("view.separationsPreview", &json!({"soloToggle": "Cyan"})).unwrap(); + assert_eq!(visible_plates(&r), [true; 4]); +} + #[test] fn proof_setup_simulates_tritanopia() { let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index 8fa31889a2..dfa3e95aba 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -414,6 +414,61 @@ fn pencil_refuses_an_unknown_style_or_extend_end() { assert!(ends.contains(&Point::new(0.0, 100.0)) && ends.contains(&Point::new(200.0, 100.0)), "continued from its start: {ends:?}"); } +/// `path.freehand` refuses a `connect` without `extend`, and checks a `connect` given with `extend` +/// before a stroke of one point returns, so a bad one is refused there too; a refused call changes +/// neither the document nor the undo history. A `connect` of null is a key left out. +#[test] +fn pencil_refuses_connect_without_extend_and_a_bad_connect_for_one_point() { + let mut s = session(); + let a = line(&mut s, 100.0, 100.0, 200.0, 100.0); + let b = line(&mut s, 300.0, 200.0, 400.0, 200.0); + let closed = NodeId(s.execute("path.create", &json!({"d": "M0 500 L50 500 L50 550 Z"})).unwrap()["id"].as_u64().unwrap()); + let inner = NodeId(s.execute("path.create", &json!({"d": "M600 500 L650 500"})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [inner.0]})).unwrap(); + let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + let stroke = json!({"points": [[200, 100], [250, 150], [300, 200]]}); + for connect in [json!({"id": b.0, "end": "start"}), json!({"id": b.0, "end": "middle"}), json!({"id": b.0}), json!({})] { + refuses_with(&mut s, "path.freehand", &with(&stroke, json!({ "connect": connect })), "connect needs extend"); + refuses_with(&mut s, "path.freehand", &with(&stroke, json!({"extend": null, "connect": connect})), "connect needs extend"); + } + let refused = |s: &mut Session, p: &serde_json::Value| { + let before = s.doc().unwrap().doc.clone(); + let undo = undo_steps(s); + assert!(s.execute("path.freehand", p).is_err(), "{p}"); + assert!(s.doc().unwrap().doc == before, "{p} changed the document"); + assert_eq!(undo_steps(s), undo, "{p} left an undo step"); + }; + refused(&mut s, &with(&stroke, json!({"connect": "b"}))); + let one = json!({"points": [[200, 100]], "extend": {"id": a.0, "end": "end"}}); + let end = "connect end must be \"start\" or \"end\""; + for e in [json!("middle"), json!(1), json!(null)] { + refuses_with(&mut s, "path.freehand", &with(&one, json!({"connect": {"id": b.0, "end": e}})), end); + } + refuses_with(&mut s, "path.freehand", &with(&one, json!({"connect": {"id": b.0}})), end); + refuses_with(&mut s, "path.freehand", &with(&one, json!({"connect": {"end": "end"}})), "connect needs id"); + refuses_with(&mut s, "path.freehand", &with(&one, json!({"connect": {"id": "b", "end": "end"}})), "`id` must be a whole number"); + let other = "connect needs a path other than the one extended"; + refuses_with(&mut s, "path.freehand", &with(&one, json!({"connect": {"id": a.0, "end": "end"}})), other); + refuses_with(&mut s, "path.freehand", &with(&one, json!({"connect": {"id": closed.0, "end": "end"}})), "connect path has no open end"); + for p in [ + with(&one, json!({"connect": "b"})), + with(&one, json!({"connect": {"id": 999_999, "end": "end"}})), + with(&one, json!({"connect": {"id": group.0, "end": "end"}})), + ] { + refused(&mut s, &p); + } + assert_eq!((paths(&s).len(), path(&s, a).anchor_count(), path(&s, b).anchor_count()), (4, 2, 2), "refused: nothing changed"); + // A good `connect`, or a null one, on a stroke of one point leaves the path as it was. + let undo = undo_steps(&s); + for connect in [json!({"id": b.0, "end": "start"}), json!(null)] { + assert_eq!(s.execute("path.freehand", &with(&one, json!({ "connect": connect }))).unwrap()["id"], json!(a.0)); + } + assert_eq!((path(&s, a).anchor_count(), undo_steps(&s)), (2, undo)); + // Null without `extend`, `connect` is left out, and the stroke draws a new path. + s.execute("path.freehand", &with(&stroke, json!({"connect": null}))).unwrap(); + assert_eq!(paths(&s).len(), 5); +} + /// With Keep selected off, a compound path whose direct-selected anchors all lie on the subpath /// that connect joins on is no longer selected, and Delete then has nothing to delete. #[test] @@ -6292,14 +6347,20 @@ fn pencil_at_the_lowest_fidelity_takes_degenerate_strokes() { } } -/// The Pencil's Fidelity option takes 0.01, and the Smooth tool's stays at 0.05 or more. +/// The Pencil's Fidelity option takes 0.01, and the Smooth tool's 0.05 or more: a lower Fidelity is +/// an error that leaves the option as it was. #[test] fn pencil_option_takes_a_hundredth_and_smooth_keeps_its_floor() { let mut s = session(); - for (tool, want) in [("pencil", 0.01), ("paintbrush", 0.01), ("smooth", 0.05)] { - s.set_tool_option_cmd(&json!({"tool": tool, "values": {"fidelity": 0.001}})).unwrap(); - assert_eq!(s.tool_options_of(tool)["fidelity"].as_f64(), Some(want), "{tool}"); - s.set_tool_option_cmd(&json!({"tool": tool, "values": {"fidelity": 0.02}})).unwrap(); + for (tool, floor) in [("pencil", 0.01), ("paintbrush", 0.01), ("smooth", 0.05)] { + let before = s.tool_options_of(tool)["fidelity"].clone(); + let e = s.set_tool_option_cmd(&json!({"tool": tool, "values": {"fidelity": 0.001}})).unwrap_err(); + assert_eq!(e, format!("tool `{tool}`: `fidelity` must be a number from {floor} to 100")); + assert_eq!(s.tool_options_of(tool)["fidelity"], before, "{tool}"); + s.set_tool_option_cmd(&json!({"tool": tool, "values": {"fidelity": floor}})).unwrap(); + assert_eq!(s.tool_options_of(tool)["fidelity"].as_f64(), Some(floor), "{tool}"); + let hundredth = s.set_tool_option_cmd(&json!({"tool": tool, "values": {"fidelity": 0.02}})); + assert_eq!(hundredth.is_ok(), tool != "smooth", "{tool}"); assert_eq!(s.tool_options_of(tool)["fidelity"].as_f64(), Some(if tool == "smooth" { 0.05 } else { 0.02 }), "{tool}"); } } diff --git a/crates/engine/src/tests/expand.rs b/crates/engine/src/tests/expand.rs index 0cc0106351..e728754655 100644 --- a/crates/engine/src/tests/expand.rs +++ b/crates/engine/src/tests/expand.rs @@ -260,6 +260,100 @@ fn a_stroke_effect_reshapes_a_stroke_a_dynamic_instance_adds() { assert!(b.x0 <= 31.0 && b.x1 >= 169.0, "the bounds take in the offset stroke: {b:?}"); let drawn = vectorcraft_render::drawn_bounds(&doc, doc.node(id).unwrap()).expect("the instance is drawn"); assert!(drawn.x0 <= 31.0 && drawn.x1 >= 169.0, "the drawn bounds take in the offset stroke: {drawn:?}"); + assert_eq!(hit_at(&s, 30.5, vectorcraft_doc::hit::HitOptions { tol: 1.0, ..Default::default() }), Some(id), "a click on the added stroke"); +} + +/// What a click at (`x`, 100) with `opt` hits. +fn hit_at(s: &Session, x: f64, opt: vectorcraft_doc::hit::HitOptions) -> Option { + vectorcraft_doc::hit::hit_test(&s.doc().unwrap().doc, vectorcraft_geom::Point::new(x, 100.0), opt).map(|h| h.leaf) +} + +/// [`instance_with_row`] of a symbol whose art is an instance of another symbol made of the square. +fn nested_instance_with_row(s: &mut Session) -> (NodeId, usize) { + square(s); + let inner = NodeId(run(s, "symbol.new", json!({"name": "Inner"}))["id"].as_u64().unwrap()); + run(s, "select.set", json!({"ids": [inner.0]})); + let id = NodeId(run(s, "symbol.new", json!({"name": "Outer"}))["id"].as_u64().unwrap()); + run(s, "appearance.addFill", json!({"ids": [id.0]})); + let row = node(s, id).appearance.items.len() - 1; + run(s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true})); + (id, row) +} + +/// Effect › Pathfinder › Add on a group holding a symbol instance combines the art the instance +/// draws: the effects on the instance's fill and stroke reshape the result as they reshape the +/// instance, in a symbol placed inside another symbol too. +#[test] +fn pathfinder_takes_a_symbol_instance_fill_and_stroke_effects() { + for (fill, x, color) in [(true, 44, RED), (false, 40, BLUE)] { + let mut s = session(); + let (id, row) = instance_with_row(&mut s, "Square", fill); + offset_row(&mut s, id, row, 10.0); + let g = NodeId(run(&mut s, "object.group", json!({"ids": [id.0]}))["id"].as_u64().unwrap()); + run(&mut s, "effect.apply", json!({"ids": [g.0], "effect": "pathfinder.add"})); + let r = render(&s); + assert!(near(r.pixel(x, 100), color), "fill {fill}: the result keeps the offset: {:?}", r.pixel(x, 100)); + assert!(near(r.pixel(100, 100), RED), "fill {fill}: the result keeps the art's fill: {:?}", r.pixel(100, 100)); + } + // An effect of the instance's own reshapes the art as well. + let mut s = session(); + let (id, row) = instance_with_row(&mut s, "Square", true); + offset_row(&mut s, id, row, 10.0); + run(&mut s, "effect.apply", json!({"ids": [id.0], "item": null, "effect": "path.offsetPath", "params": {"offset": 5}})); + assert!(near(render(&s).pixel(37, 100), RED), "both offsets grow the art on the canvas: {:?}", render(&s).pixel(37, 100)); + let g = NodeId(run(&mut s, "object.group", json!({"ids": [id.0]}))["id"].as_u64().unwrap()); + run(&mut s, "effect.apply", json!({"ids": [g.0], "effect": "pathfinder.add"})); + assert!(near(render(&s).pixel(37, 100), RED), "both offsets grow the result: {:?}", render(&s).pixel(37, 100)); + + let mut s = session(); + let (id, row) = nested_instance_with_row(&mut s); + offset_row(&mut s, id, row, 10.0); + assert!(near(render(&s).pixel(44, 100), RED), "the nested art grows on the canvas: {:?}", render(&s).pixel(44, 100)); + let g = NodeId(run(&mut s, "object.group", json!({"ids": [id.0]}))["id"].as_u64().unwrap()); + run(&mut s, "effect.apply", json!({"ids": [g.0], "effect": "pathfinder.add"})); + assert!(near(render(&s).pixel(44, 100), RED), "the nested art grows in the result: {:?}", render(&s).pixel(44, 100)); +} + +/// A click where the effect on a symbol instance's fill or stroke paints its art outside the +/// instance's bounds selects the instance; a click past the drawn art, a fill with Selection by +/// Path Only and outline mode do not. +#[test] +fn a_click_where_a_symbol_instance_fill_or_stroke_effect_paints_selects_it() { + use vectorcraft_doc::hit::HitOptions; + let opt = HitOptions { tol: 1.0, ..Default::default() }; + let mut s = session(); + let (id, row) = instance_with_row(&mut s, "Square", true); + assert_eq!(hit_at(&s, 44.0, opt), None); + offset_row(&mut s, id, row, 10.0); + assert_eq!(hit_at(&s, 44.0, opt), Some(id), "a click on the grown fill"); + assert_eq!(hit_at(&s, 100.0, opt), Some(id), "a click inside the instance"); + assert_eq!(hit_at(&s, 36.0, opt), None, "a click past the grown fill"); + assert_eq!(hit_at(&s, 44.0, HitOptions { path_only: true, ..opt }), None, "Selection by Path Only leaves the fill out"); + assert_eq!(hit_at(&s, 44.0, HitOptions { outline: true, ..opt }), None, "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!(hit_at(&s, 40.0, opt), Some(id), "a click on the moved stroke"); + assert_eq!(hit_at(&s, 45.0, opt), None, "a click between the moved stroke and the fill"); + assert_eq!(hit_at(&s, 40.0, HitOptions { path_only: true, ..opt }), Some(id), "Selection by Path Only takes the stroke"); + + let mut s = session(); + let (id, row) = nested_instance_with_row(&mut s); + offset_row(&mut s, id, row, 10.0); + assert_eq!(hit_at(&s, 44.0, opt), Some(id), "a click on the grown fill of the nested art"); + + // A path in the art with an Offset Path of its own: both offsets grow what it draws. + let mut s = session(); + let art = square(&mut s); + run(&mut s, "effect.apply", json!({"ids": [art.0], "item": null, "effect": "path.offsetPath", "params": {"offset": 5}})); + let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Offset"}))["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!(near(render(&s).pixel(37, 100), RED), "both offsets grow the art on the canvas: {:?}", render(&s).pixel(37, 100)); + assert_eq!(hit_at(&s, 37.0, opt), Some(id), "a click where both offsets grow the art"); } /// A group in the symbol's art with a fill of its own: the instance's fill effect reshapes what @@ -284,6 +378,7 @@ fn a_fill_effect_reshapes_the_fill_of_a_group_in_the_art() { assert!(b.x0 <= 31.0 && b.x1 >= 169.0, "the bounds take in the group's grown fill: {b:?}"); let drawn = vectorcraft_render::drawn_bounds(&doc, doc.node(id).unwrap()).expect("the instance is drawn"); assert!(drawn.x0 <= 31.0 && drawn.x1 >= 169.0, "the drawn bounds take in the group's grown fill: {drawn:?}"); + assert_eq!(hit_at(&s, 35.0, vectorcraft_doc::hit::HitOptions { tol: 1.0, ..Default::default() }), Some(id), "a click on the group's grown fill"); let before = render(&s); run(&mut s, "effect.expandAppearance", json!({})); @@ -292,6 +387,181 @@ 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(); + 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; + run(&mut s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true})); + let opt = vectorcraft_doc::hit::HitOptions { tol: 1.0, ..Default::default() }; + assert_eq!(hit_at(&s, 70.0, opt), None); + offset_row(&mut s, id, row, 10.0); + assert!(near(render(&s).pixel(70, 100), BLUE), "the image's fill grows by the offset: {:?}", render(&s).pixel(70, 100)); + assert_eq!(hit_at(&s, 70.0, opt), Some(id), "a click on the image's grown fill"); + assert_eq!(hit_at(&s, 60.0, opt), None, "a click past the grown fill"); +} + +/// A group in the symbol's art with Effect › Pathfinder › Subtract: the instance's fill effect +/// grows the result, and a click past both shapes where only the subtracted shape would grow does +/// not select the instance. +#[test] +fn a_click_on_a_shape_a_pathfinder_effect_in_the_art_subtracts_misses_the_instance() { + let mut s = session(); + // The back square runs from 50 to 110 and the front one from 80 to 140; the result runs from 50 to 80. + let back = NodeId(run(&mut s, "shape.rectangle", json!({"x": 50, "y": 50, "width": 60, "height": 100}))["id"].as_u64().unwrap()); + run(&mut s, "paint.setFill", json!({"color": "#ff0000"})); + run(&mut s, "paint.setStroke", json!({"color": "#0000ff"})); + run(&mut s, "stroke.set", json!({"weight": 4})); + let front = NodeId(run(&mut s, "shape.rectangle", json!({"x": 80, "y": 50, "width": 60, "height": 100}))["id"].as_u64().unwrap()); + let g = NodeId(run(&mut s, "object.group", json!({"ids": [back.0, front.0]}))["id"].as_u64().unwrap()); + run(&mut s, "effect.apply", json!({"ids": [g.0], "effect": "pathfinder.subtract"})); + run(&mut s, "select.set", json!({"ids": [g.0]})); + let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Subtracted"}))["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})); + let opt = vectorcraft_doc::hit::HitOptions { tol: 1.0, ..Default::default() }; + assert_eq!(hit_at(&s, 45.0, opt), None); + offset_row(&mut s, id, row, 10.0); + let r = render(&s); + assert!(near(r.pixel(45, 100), RED), "the result's fill grows by the offset: {:?}", r.pixel(45, 100)); + assert!(near(r.pixel(145, 100), WHITE), "the subtracted shape is not drawn: {:?}", r.pixel(145, 100)); + assert_eq!(hit_at(&s, 45.0, opt), Some(id), "a click on the result's grown fill"); + assert_eq!(hit_at(&s, 145.0, opt), None, "a click where only the subtracted shape would grow"); +} + +/// A Shaper group in the symbol's art: the instance's fill effect grows the faces it shows, and a +/// click where only its original shapes would grow does not select the instance. +#[test] +fn a_click_on_a_shaper_groups_original_shapes_in_the_art_misses_the_instance() { + let mut s = session(); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": []})); + for x in [0, 50] { + run(&mut s, "paint.setFill", json!({"color": "#ff0000", "ids": []})); + run(&mut s, "shape.rectangle", json!({"x": x, "y": 50, "width": 100, "height": 100})); + } + // The scribble inside the overlap removes the front rectangle's face; the face left runs from 0 to 50. + let g = NodeId(run(&mut s, "shaper.scribble", json!({"points": [[65, 70], [85, 90], [65, 110], [85, 130]]}))["id"].as_u64().unwrap()); + assert!(node(&s, g).extras().shaper.is_some()); + run(&mut s, "select.set", json!({"ids": [g.0]})); + let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Shaped"}))["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})); + let opt = vectorcraft_doc::hit::HitOptions { tol: 1.0, ..Default::default() }; + assert_eq!(hit_at(&s, 57.0, opt), None); + offset_row(&mut s, id, row, 10.0); + let r = render(&s); + assert!(near(r.pixel(57, 100), RED), "the face's fill grows by the offset: {:?}", r.pixel(57, 100)); + assert!(near(r.pixel(125, 100), WHITE), "the original shapes are not drawn: {:?}", r.pixel(125, 100)); + assert_eq!(hit_at(&s, 57.0, opt), Some(id), "a click on the face's grown fill"); + assert_eq!(hit_at(&s, 125.0, opt), None, "a click on an original shape"); +} + +/// A Shaper group in the symbol's art with a stroke of its own below its Contents row: the +/// instance's stroke effect moves what that stroke paints, and a click selects the instance where +/// the canvas draws the moved stroke, not inside the original shapes. +#[test] +fn a_click_on_a_shaper_group_with_a_stroke_below_its_contents_selects_the_instance_where_it_draws() { + let mut s = session(); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": []})); + for x in [0, 50] { + run(&mut s, "paint.setFill", json!({"color": "#ff0000", "ids": []})); + run(&mut s, "shape.rectangle", json!({"x": x, "y": 50, "width": 100, "height": 100})); + } + // The scribble removes the front rectangle's face; the group's stroke outlines both rectangles. + let g = NodeId(run(&mut s, "shaper.scribble", json!({"points": [[65, 70], [85, 90], [65, 110], [85, 130]]}))["id"].as_u64().unwrap()); + run(&mut s, "appearance.addStroke", json!({"ids": [g.0]})); + let stroke = node(&s, g).appearance.items.len() - 1; + run(&mut s, "paint.setStroke", json!({"ids": [g.0], "item": stroke, "color": "#0000ff"})); + run(&mut s, "stroke.set", json!({"ids": [g.0], "item": stroke, "weight": 4})); + run(&mut s, "appearance.moveItem", json!({"ids": [g.0], "from": "contents", "to": stroke + 1})); + assert_eq!(node(&s, g).appearance.split_contents().0.len(), stroke + 1, "the group's stroke is below its Contents row"); + run(&mut s, "select.set", json!({"ids": [g.0]})); + let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Shaped"}))["id"].as_u64().unwrap()); + run(&mut s, "appearance.addStroke", 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); + let r = render(&s); + let opt = vectorcraft_doc::hit::HitOptions { tol: 1.0, ..Default::default() }; + assert!(near(r.pixel(160, 100), BLUE), "the group's stroke moves out by the offset: {:?}", r.pixel(160, 100)); + assert!(near(r.pixel(125, 100), WHITE), "the original shapes are not drawn: {:?}", r.pixel(125, 100)); + assert_eq!(hit_at(&s, 160.0, opt), Some(id), "a click on the group's moved stroke"); + assert_eq!(hit_at(&s, 125.0, opt), None, "a click inside an original shape"); +} + /// Of several fills, only the topmost one's effects reach the art, and only while it is visible. #[test] fn only_the_topmost_visible_instance_fill_reshapes_the_art() { diff --git a/crates/engine/src/tests/inline.rs b/crates/engine/src/tests/inline.rs index b6ea42d3f2..1d68881b4d 100644 --- a/crates/engine/src/tests/inline.rs +++ b/crates/engine/src/tests/inline.rs @@ -529,6 +529,245 @@ fn saved_documents_keep_inline_graphics() { assert_eq!(t.cached_bounds, obj(&s, id).cached_bounds); } +/// `groups` groups of `each` 5 × 5 black rectangles added to the first layer in one edit; returns +/// the ids of each group's rectangles. +fn rect_groups(s: &mut Session, groups: usize, each: usize) -> Vec> { + s.edit("Rectangles", |d, _| { + let look = vectorcraft_doc::Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0); + let mut ids = vec![]; + let mut made = vec![]; + for g in 0..groups { + let kids: Vec> = (0..each) + .map(|i| { + let r = Rect::new(i as f64 * 6.0, g as f64 * 6.0, i as f64 * 6.0 + 5.0, g as f64 * 6.0 + 5.0); + Arc::new(Node::path(d.alloc_id(), vectorcraft_geom::shapes::rectangle(r), look.clone())) + }) + .collect(); + ids.push(kids.iter().map(|k| k.id).collect()); + made.push(Arc::new(Node::group(d.alloc_id(), kids))); + } + match Arc::make_mut(&mut d.layers[0]).children_mut() { + Some(kids) => kids.extend(made), + None => panic!("the first layer holds art"), + } + Ok(ids) + }) + .unwrap() +} + +/// Runs `step` on `full`, with every refresh of inline graphics taking the full pass, then on +/// `fast`; checks that both leave the same document and that each refresh returned the same changed +/// texts. Returns whether each of `fast`'s refreshes checked only the changed layer trees. +fn same_as_full_pass(full: &mut Session, fast: &mut Session, step: &dyn Fn(&mut Session)) -> Vec { + let take = || cmd::inline::PASSES.with(|p| std::mem::take(&mut *p.borrow_mut())); + take(); + cmd::inline::FULL_PASS.set(true); + step(full); + cmd::inline::FULL_PASS.set(false); + let want = take(); + step(fast); + let got = take(); + assert_eq!(*full.doc().unwrap().doc, *fast.doc().unwrap().doc); + let ids = |passes: &[(bool, Vec)]| passes.iter().map(|(_, ids)| ids.clone()).collect::>(); + assert_eq!(ids(&got), ids(&want)); + assert!(want.iter().all(|(partial, _)| !partial)); + got.iter().map(|(partial, _)| *partial).collect() +} + +/// After an edit, inline graphics are checked again only in the layer trees the edit changed, and +/// the document and the changed texts are those of the full pass; a change to a symbol's art, its +/// natural size or anything else a symbol is measured with checks them all. +#[test] +fn refreshing_only_changed_trees_matches_the_full_pass() { + let setup = |s: &mut Session| { + circle_symbol(s, "Tap", 10.0); + circle_symbol(s, "Dot", 6.0); + let groups = rect_groups(s, 20, 10); + let id = text(s, "Tap here"); + s.execute("text.insertInline", &json!({"id": id.0, "at": 0, "symbol": "Tap"})).unwrap(); + // Type showing Dot inline becomes the opacity mask of a rectangle. + let masked = s.execute("shape.rectangle", &json!({"x": 300, "y": 300, "width": 50, "height": 50})).unwrap()["id"].clone(); + let mask = text(s, "Dot"); + s.execute("text.insertInline", &json!({"id": mask.0, "at": 0, "symbol": "Dot"})).unwrap(); + s.execute("transparency.makeOpacityMask", &json!({"ids": [masked, mask.0]})).unwrap(); + (groups, id) + }; + let (mut full, mut fast) = (session(), session()); + let (groups, id) = setup(&mut full); + assert_eq!(setup(&mut fast), (groups.clone(), id)); + let rect = groups[3][4].0; + let len = obj(&fast, id).plain_text().len(); + let only_changed = |passes: &[bool]| !passes.is_empty() && passes.iter().all(|&p| p); + let all = |passes: &[bool]| !passes.is_empty() && passes.iter().all(|&p| !p); + + // A rectangle beside 19 unchanged groups moves. + let passes = same_as_full_pass(&mut full, &mut fast, &|s| { + s.execute("select.set", &json!({"ids": [rect]})).unwrap(); + s.execute("object.move", &json!({"dx": 5, "dy": 0})).unwrap(); + }); + assert!(only_changed(&passes), "{passes:?}"); + // Type with an inline graphic is edited, gets a second one, and loses it again. + let passes = same_as_full_pass(&mut full, &mut fast, &|s| { + s.execute("text.editRange", &json!({"id": id.0, "start": len, "end": len, "insert": "!"})).unwrap(); + s.execute("text.insertInline", &json!({"id": id.0, "at": len, "symbol": "Dot"})).unwrap(); + s.execute("text.editRange", &json!({"id": id.0, "start": len, "end": len + INLINE_CHAR.len_utf8(), "insert": ""})).unwrap(); + }); + assert!(only_changed(&passes), "{passes:?}"); + // Dot's art is redefined: the type in the opacity mask follows it. + let passes = same_as_full_pass(&mut full, &mut fast, &|s| redefine_as_wide_ellipse(s, "Dot")); + assert!(passes.contains(&false), "{passes:?}"); + // Tap's natural size changes, its art unchanged. + let passes = same_as_full_pass(&mut full, &mut fast, &|s| { + s.edit("Size", |d, _| { + d.unknown.insert(vectorcraft_doc::SYMBOL_SIZES.into(), json!({ "Tap": [40.0, 20.0] })); + Ok(()) + }) + .unwrap(); + }); + assert!(all(&passes), "{passes:?}"); + let (b, want) = (inline_bounds(&obj(&fast, id)), fast.doc().unwrap().doc.symbol_art_bounds("Tap")); + assert!(b.is_some() && b == want, "{b:?} {want:?}"); + // 9-slice guides for Tap, its art unchanged. + let passes = same_as_full_pass(&mut full, &mut fast, &|s| { + s.execute("symbol.options", &json!({"name": "Tap", "nineSlice": true})).unwrap(); + }); + assert!(all(&passes), "{passes:?}"); + // Symbol editing mode, entered and left, a rectangle moved inside it. + same_as_full_pass(&mut full, &mut fast, &|s| { + s.execute("symbol.edit", &json!({"name": "Dot"})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 4, "height": 4})).unwrap(); + s.execute("symbol.exitEditing", &json!({})).unwrap(); + }); + // Undo and redo, then edits after them. + same_as_full_pass(&mut full, &mut fast, &|s| { + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [rect]})).unwrap(); + s.execute("object.move", &json!({"dx": 0, "dy": 5})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.redo", &json!({})).unwrap(); + s.execute("object.move", &json!({"dx": -5, "dy": 0})).unwrap(); + }); + // Fonts scanned again, then another move. + same_as_full_pass(&mut full, &mut fast, &|s| { + s.execute("text.rescanFonts", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [rect]})).unwrap(); + s.execute("object.move", &json!({"dx": 1, "dy": 1})).unwrap(); + }); +} + +/// 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 in milliseconds: this thread's CPU time where Linux reports it, otherwise the +/// wall clock. +fn time_ms(f: impl FnOnce()) -> f64 { + let d = 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() + } + }; + d.as_secs_f64() * 1000.0 +} + +/// The median, fastest and slowest of `runs`, as text. +fn spread(runs: &mut [f64]) -> String { + runs.sort_by(f64::total_cmp); + format!("{:>9.3} ({:.3}-{:.3})", runs[runs.len() / 2], runs[0], runs[runs.len() - 1]) +} + +/// Timings of the refresh of inline graphics after one rectangle moves, with the full pass and with +/// only the changed layer trees checked, in documents of 5,000, 50,000 and 200,000 rectangles in 100 +/// groups, with three symbols and one line of type showing one of them inline: the refresh alone, +/// on copies of the same edit, and the whole `object.move` command. 7 runs each, taking turns going +/// first. Ignored by default; it prints the median, fastest and slowest run and sets no bound on +/// them: `cargo test --release -p vectorcraft-engine --lib inline_refresh_perf -- --ignored --nocapture`. +#[test] +#[ignore = "a benchmark: run with --ignored --nocapture"] +fn inline_refresh_perf() { + const RUNS: usize = 7; + eprintln!("inline_refresh_perf: {}", if thread_cpu().is_some() { "thread CPU time" } else { "wall clock" }); + eprintln!("inline_refresh_perf: {:>7} {:<14} {:>28} {:>28}", "objects", "case", "full pass ms (min-max)", "changed trees ms (min-max)"); + for n in [5_000, 50_000, 200_000] { + let mut s = session(); + for name in ["A", "B", "C"] { + circle_symbol(&mut s, name, 10.0); + } + let groups = rect_groups(&mut s, 100, n / 100); + let id = text(&mut s, "Type"); + s.execute("text.insertInline", &json!({"id": id.0, "at": 0, "symbol": "B"})).unwrap(); + let rect = groups[50][7]; + s.execute("select.set", &json!({"ids": [rect.0]})).unwrap(); + s.execute("object.move", &json!({"dx": 1, "dy": 0})).unwrap(); + // The refresh alone, after the same move made on a copy of the resolved document. + let resolved = s.doc().unwrap().inline_resolved.clone().unwrap(); + let before = resolved.0.clone(); + // The rectangle and the group and layer above it become new nodes, as a move makes them. + let mut after = (*before).clone(); + assert!(after.node_mut(rect).is_some()); + // Each run times EACH refreshes, or EACH commands, and gives the time of one. + const EACH: usize = 20; + let (mut full, mut partial) = (vec![], vec![]); + for run in 0..RUNS { + let (mut a, mut b) = (vec![after.clone(); EACH], vec![after.clone(); EACH]); + let mut go_full = || { + cmd::inline::FULL_PASS.set(true); + full.push( + time_ms(|| { + for d in &mut a { + cmd::inline::refresh(Some(&resolved), &before, d); + } + }) / EACH as f64, + ); + cmd::inline::FULL_PASS.set(false); + }; + let mut go_partial = || { + partial.push( + time_ms(|| { + for d in &mut b { + cmd::inline::refresh(Some(&resolved), &before, d); + } + }) / EACH as f64, + ); + }; + if run % 2 == 0 { + go_full(); + go_partial(); + } else { + go_partial(); + go_full(); + } + assert_eq!(a, b); + } + eprintln!("inline_refresh_perf: {n:>7} {:<14} {:>28} {:>28}", "refresh", spread(&mut full), spread(&mut partial)); + // The whole command, moving the rectangle back and forth. + let (mut full, mut partial) = (vec![], vec![]); + for run in 0..2 * RUNS { + let take_full = (run / 2) % 2 == run % 2; + cmd::inline::FULL_PASS.set(take_full); + let ms = time_ms(|| { + for i in 0..EACH { + let dx = if i % 2 == 0 { -1 } else { 1 }; + s.execute("object.move", &json!({"dx": dx, "dy": 0})).unwrap(); + } + }) / EACH as f64; + cmd::inline::FULL_PASS.set(false); + if take_full { full.push(ms) } else { partial.push(ms) } + } + eprintln!("inline_refresh_perf: {n:>7} {:<14} {:>28} {:>28}", "object.move", spread(&mut full), spread(&mut partial)); + cmd::inline::PASSES.with(|p| p.borrow_mut().clear()); + } +} + #[test] fn create_outlines_turns_inline_graphics_into_symbol_instances() { let mut s = session(); 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/layers.rs b/crates/engine/src/tests/layers.rs index f6b35716f6..e5cb1c8f63 100644 --- a/crates/engine/src/tests/layers.rs +++ b/crates/engine/src/tests/layers.rs @@ -213,6 +213,117 @@ fn the_selection_column_selects_a_rows_art_and_shift_adds_or_removes_it() { assert_eq!(ids_sel(&run(&mut s, "layer.target", json!({"id": layer.0}))), vec![c, a, g]); } +/// The rows of [`column_start`]: [`tree`]'s, plus a rectangle `o` on a second layer and an empty +/// third layer `e`. +#[derive(Clone, Copy)] +struct Column { + layer: NodeId, + sub: NodeId, + a: NodeId, + g: NodeId, + b: NodeId, + c: NodeId, + o: NodeId, + e: NodeId, +} + +fn column_start() -> (Session, Column) { + let mut s = session(); + let (layer, sub, a, g, b, c) = tree(&mut s); + run(&mut s, "layer.setCurrent", json!({"id": layer.0})); + let other = id(&run(&mut s, "layer.new", json!({}))); + let o = rect(&mut s, 200.0); + let e = id(&run(&mut s, "layer.new", json!({}))); + run(&mut s, "select.none", json!({})); + let top: Vec = s.doc().unwrap().doc.layers.iter().map(|l| l.id).collect(); + assert!(top.contains(&other) && top.contains(&e) && parent(&s, o) == Some(other), "{top:?}"); + (s, Column { layer, sub, a, g, b, c, o, e }) +} + +type Prep = dyn Fn(&mut Session, Column); + +/// A Shift-click in the selection column of `row` (whose art is `art`) after `prep` gives the +/// same selection, reply, current layer, highlighted rows and revision as removing or adding each +/// id of `art` one at a time. Returns the session the click ran in. +fn shift_column_matches_each_id(prep: &Prep, row: impl Fn(Column) -> NodeId, art: impl Fn(Column) -> Vec) -> (Session, Column) { + let (mut new, t) = column_start(); + prep(&mut new, t); + let row = row(t); + let before = new.doc().unwrap().selection.clone(); + let reply = run(&mut new, "layer.selectAll", json!({"id": row.0, "add": true})); + let (mut old, t) = column_start(); + prep(&mut old, t); + let ids = art(t); + let st = old.doc().unwrap(); + let all_selected = !ids.is_empty() && ids.iter().all(|i| st.selection.contains(*i)); + let rows = st.layer_rows.clone(); + old.select(|_, sel| { + for i in &ids { + if all_selected { sel.remove(*i) } else { sel.add(*i) } + } + }) + .unwrap(); + old.doc_mut().unwrap().layer_rows = rows; + let (n, o) = (new.doc().unwrap(), old.doc().unwrap()); + assert_eq!(n.selection, o.selection, "row {row:?} from {before:?}"); + assert_eq!(ids_sel(&reply), o.selection.objects); + assert_eq!(n.active_layer, o.active_layer); + assert_eq!(n.highlighted_rows(), o.highlighted_rows()); + assert_eq!(n.revision, o.revision); + assert_eq!(undos(&new), undos(&old)); + (new, t) +} + +#[test] +fn a_shift_click_in_the_selection_column_matches_adding_or_removing_each_id() { + // `o` outside the layer is selected first and is the key object and the target; `a` is + // selected by one anchor, which is the key anchor. + let partly: &Prep = &|s, t| { + run(s, "layer.setCurrent", json!({"id": t.sub.0})); + let sel = &mut s.doc_mut().unwrap().selection; + sel.objects = vec![t.o, t.a]; + sel.anchors.insert(t.a, [(0, 1)].into()); + sel.key = Some(t.o); + sel.key_anchor = Some((t.a, (0, 1))); + sel.target = Some(t.o); + }; + let layer_art = |t: Column| vec![t.c, t.a, t.g]; + // Some of the layer's art is selected: the rest is added after what was selected. + let (s, t) = shift_column_matches_each_id(partly, |t| t.layer, layer_art); + let sel = &s.doc().unwrap().selection; + assert_eq!(sel.objects, vec![t.o, t.a, t.c, t.g]); + assert_eq!(sel.anchors.len(), 1, "the picked anchor stays picked"); + assert!(sel.target.is_none()); + // All of it is selected, `a` as the key object: it is removed, with its anchors, key and key + // anchor. + let all: &Prep = &|s, t| { + partly(s, t); + let sel = &mut s.doc_mut().unwrap().selection; + sel.objects.extend([t.c, t.g]); + sel.key = Some(t.a); + }; + let (s, t) = shift_column_matches_each_id(all, |t| t.layer, layer_art); + let sel = &s.doc().unwrap().selection; + assert_eq!(sel.objects, vec![t.o]); + assert!(sel.anchors.is_empty() && sel.key.is_none() && sel.key_anchor.is_none()); + // An object row, a group row and an empty layer's row. + shift_column_matches_each_id(all, |t| t.c, |t| vec![t.c]); + shift_column_matches_each_id(partly, |t| t.g, |t| vec![t.g]); + shift_column_matches_each_id(partly, |t| t.e, |_| vec![]); + // A locked sublayer's row, and rows outside and inside the isolated group. + let locked: &Prep = &|s, t| { + partly(s, t); + run(s, "layer.setProps", json!({"id": t.sub.0, "locked": true})); + }; + shift_column_matches_each_id(locked, |t| t.sub, |_| vec![]); + let isolated: &Prep = &|s, t| { + partly(s, t); + s.doc_mut().unwrap().isolation = Some(t.g); + }; + shift_column_matches_each_id(isolated, |t| t.c, |_| vec![]); + shift_column_matches_each_id(isolated, |t| t.b, |t| vec![t.b]); +} + fn ids_sel(v: &Value) -> Vec { v["selected"].as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect() } @@ -481,6 +592,54 @@ fn new_layers_go_below_the_current_one_and_sublayers_under_the_contents() { assert_eq!(children(&s, layer), vec![front, under, back]); } +/// In Draw Behind a new layer goes directly below the current layer, at its level, in one undo +/// step; `top` and `below` keep their meaning, Draw Inside and Draw Normal keep it above, and new +/// sublayers are not affected. +#[test] +fn new_layers_go_below_the_current_one_in_draw_behind() { + let mut s = session(); + let (layer, sub, a, g, _, c) = tree(&mut s); + run(&mut s, "view.drawMode", json!({"mode": "behind"})); + run(&mut s, "layer.setCurrent", json!({"id": sub.0})); + let before = undos(&s); + let n = id(&run(&mut s, "layer.new", json!({}))); + assert_eq!(children(&s, layer), vec![c, n, sub], "a sublayer directly below the current sublayer"); + assert_eq!(undos(&s), before + 1); + assert_eq!(s.doc().unwrap().highlighted_rows(), vec![n]); + assert_eq!(s.doc().unwrap().current_layer(), Some(n)); + run(&mut s, "edit.undo", json!({})); + assert_eq!(children(&s, layer), vec![c, sub]); + // The Create New Layer button sends `top: false` for a plain click: still below. + run(&mut s, "layer.setCurrent", json!({"id": sub.0})); + let n = id(&run(&mut s, "layer.new", json!({"top": false}))); + assert_eq!(children(&s, layer), vec![c, n, sub]); + run(&mut s, "edit.undo", json!({})); + // At the top level, and with options. + run(&mut s, "layer.setCurrent", json!({"id": layer.0})); + let back = id(&run(&mut s, "layer.new", json!({"name": "Back", "locked": true}))); + let order = |s: &Session| s.doc().unwrap().doc.layers.iter().map(|l| l.id).collect::>(); + assert_eq!(order(&s), vec![back, layer]); + assert!(node(&s, back).locked); + // `top` and `below` win over the drawing mode. + let top = id(&run(&mut s, "layer.new", json!({"top": true}))); + assert_eq!(order(&s), vec![back, layer, top]); + let below = id(&run(&mut s, "layer.new", json!({"below": true}))); + assert_eq!(order(&s), vec![back, layer, below, top]); + assert!(s.execute("layer.new", &json!({"top": true, "below": true})).is_err()); + // New sublayers still go on top of the parent's contents. + let inner = id(&run(&mut s, "layer.newSublayer", json!({"parent": sub.0}))); + assert_eq!(children(&s, sub), vec![a, g, inner]); + // Draw Inside and Draw Normal put it above. + run(&mut s, "select.set", json!({"ids": [c.0]})); + for mode in ["inside", "normal"] { + run(&mut s, "view.drawMode", json!({"mode": mode})); + assert_eq!(s.draw_mode, if mode == "inside" { DrawMode::Inside } else { DrawMode::Normal }); + run(&mut s, "layer.setCurrent", json!({"id": back.0})); + let n = id(&run(&mut s, "layer.new", json!({}))); + assert_eq!(s.doc().unwrap().doc.layers[1].id, n, "{mode}"); + } +} + #[test] fn rows_move_above_below_and_into_layers_and_groups() { let mut s = session(); @@ -643,6 +802,45 @@ fn alt_drag_copies_rows_and_the_selected_art_moves_between_layers() { assert_eq!(s.doc().unwrap().selection.objects, vec![a, g], "it stays selected"); } +/// #8237: a copy may go above or below a row it copies, so a lone layer, the top layer dragged up +/// and the bottom one dragged down can be copied. A move there, or a copy inside the row, is still +/// refused. +#[test] +fn a_copy_goes_above_or_below_a_row_it_copies() { + let mut s = session(); + let layers = |s: &Session| s.doc().unwrap().doc.layers.iter().map(|l| l.id).collect::>(); + let [only] = layers(&s)[..] else { panic!("one layer") }; + for place in ["above", "below", "inside"] { + assert!(s.execute("layer.move", &json!({"ids": [only.0], "target": only.0, "place": place})).is_err(), "a move {place} itself"); + } + assert!(s.execute("layer.move", &json!({"ids": [only.0], "target": only.0, "place": "inside", "copy": true})).is_err()); + assert_eq!(layers(&s), vec![only], "nothing changed"); + let above = ids(&run(&mut s, "layer.move", json!({"ids": [only.0], "target": only.0, "place": "above", "copy": true}))); + assert_eq!(layers(&s), vec![only, above[0]], "the copy above the original"); + let below = ids(&run(&mut s, "layer.move", json!({"ids": [only.0], "target": only.0, "place": "below", "copy": true}))); + assert_eq!(layers(&s), vec![below[0], only, above[0]], "and one below it"); + run(&mut s, "edit.undo", json!({})); + assert_eq!(layers(&s), vec![only, above[0]], "each copy is one undo step"); +} + +/// #8237 review: rows that hold an object can't sit beside a top-level layer, so copied beside a +/// top-level layer among them they would go inside it: a copy of that layer inside itself. Refused, +/// and nothing changes. +#[test] +fn a_copy_with_objects_beside_a_copied_top_level_layer_is_refused() { + let mut s = session(); + let bottom = s.doc().unwrap().doc.layers[0].id; + let other = id(&run(&mut s, "layer.new", json!({}))); + let r = rect(&mut s, 0.0); + assert_eq!(s.doc().unwrap().doc.parent_of(r), Some(other), "the rectangle is in the other layer"); + let count = s.doc().unwrap().doc.node_count(); + for place in ["above", "below"] { + let p = json!({"ids": [bottom.0, r.0], "target": bottom.0, "place": place, "copy": true}); + assert!(s.execute("layer.move", &p).is_err(), "{place}: the layer's copy would go inside it"); + } + assert_eq!(s.doc().unwrap().doc.node_count(), count, "nothing copied"); +} + /// The selected art in rows dragged into a hidden layer or group is deselected, the key object /// included. Undo puts the rows back and selects the art again. #[test] @@ -904,6 +1102,38 @@ fn locate_object_highlights_its_row() { assert!(s.execute("layer.locate", &json!({})).is_err()); } +/// Locate Layer (`layersOnly`, sent while Show Layers Only is on) highlights the innermost layer +/// or sublayer holding the object, through any groups; a layer locates itself. +#[test] +fn locate_layer_highlights_the_layer_holding_the_object() { + let mut s = session(); + let (layer, sub, _, g, b, c) = tree(&mut s); + run(&mut s, "select.set", json!({"ids": [b.0]})); + let r = run(&mut s, "layer.locate", json!({"layersOnly": true})); + assert_eq!(r, json!({"id": sub.0, "objectId": b.0, "ancestry": [layer.0, sub.0]}), "the group's sublayer"); + assert_eq!(s.doc().unwrap().highlighted_rows(), vec![sub]); + assert_eq!(s.doc().unwrap().locate_reveal, Some(sub), "the Layers panel reveals the located row"); + s.doc_mut().unwrap().locate_reveal = None; + let undo = s.doc().unwrap().history.undo.len(); + run(&mut s, "layer.locate", json!({"layersOnly": true})); + assert_eq!(s.doc().unwrap().locate_reveal, Some(sub), "again for a row already highlighted"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step"); + assert_eq!(run(&mut s, "layer.locate", json!({"id": c.0, "layersOnly": true}))["id"], layer.0, "art directly in a layer"); + assert_eq!(s.doc().unwrap().highlighted_rows(), vec![layer]); + let r = run(&mut s, "layer.locate", json!({"id": sub.0, "layersOnly": true})); + assert_eq!((r["id"].clone(), r["objectId"].clone()), (json!(sub.0), json!(sub.0)), "a sublayer locates itself"); + // Off, the object's own row is highlighted, as before. + assert_eq!(run(&mut s, "layer.locate", json!({"id": g.0, "layersOnly": false})), json!({"id": g.0, "ancestry": [layer.0, sub.0, g.0]})); + // Bad input changes nothing. + for p in [json!({"id": b.0, "layersOnly": "yes"}), json!({"id": 999_999, "layersOnly": true})] { + assert!(s.execute("layer.locate", &p).is_err(), "{p}"); + assert_eq!(s.doc().unwrap().highlighted_rows(), vec![g], "{p}"); + assert_eq!(s.doc().unwrap().locate_reveal, Some(g), "{p}"); + } + run(&mut s, "select.none", json!({})); + assert!(s.execute("layer.locate", &json!({"layersOnly": true})).is_err(), "nothing selected"); +} + #[test] fn the_clipping_mask_button_acts_on_the_highlighted_group() { let mut s = session(); diff --git a/crates/engine/src/tests/links.rs b/crates/engine/src/tests/links.rs index 87dd7453f6..313d573206 100644 --- a/crates/engine/src/tests/links.rs +++ b/crates/engine/src/tests/links.rs @@ -2542,34 +2542,6 @@ fn confined_screens_rows_check_the_artboard_each_file_holds() { } } -/// A confined caller's single-file PDF with Preserve Editing of several assets carries the first -/// asset's document alone, so only that document is checked: an image linked outside the read roots in a later asset does -/// not refuse it, and one in the first asset does. -#[test] -fn confined_single_file_pdf_checks_the_document_it_carries() { - use crate::file_access::{AutomationRoots, confine}; - - let away = Folder::new("single-pdf-away"); - let home = Folder::new("single-pdf-home"); - let photo = away.file("photo.png"); - write(&photo, &png(60, 30, RED)); - let mut s = session(); - let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap(); - let rect: vectorcraft_doc::NodeId = serde_json::from_value(r["id"].clone()).unwrap(); - let placed = place(&mut s, &photo); - let mut assets = vec![]; - for id in [rect, placed] { - assets.push(s.execute("assets.add", &json!({"ids": [id.0]})).unwrap()["assets"][0].as_u64().unwrap()); - } - let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap(); - let p = |ids: &[u64], folder: &str| json!({"assets": ids, "folder": home.file(folder), "pdfs": "single", "formats": [{"format": "pdf", "preserveEditing": true}]}); - let r = confine(roots.as_ref(), || s.execute("assets.export", &p(&assets, "first-plain"))).unwrap_or_else(|e| panic!("{e}")); - assert_eq!(r["files"].as_array().map(Vec::len), Some(1), "{r}"); - let reversed = [assets[1], assets[0]]; - let e = confine(roots.as_ref(), || s.execute("assets.export", &p(&reversed, "first-linked"))).expect_err("first asset links outside").to_string(); - assert!(e.contains("a linked image file is outside the read roots"), "{e}"); -} - /// A confined caller's native outputs (a native file or template, an EPS or `.ai` file, a PDF with /// Preserve Editing, a package's document) carry the document without the Export for Screens /// folder when it is outside the read roots, with the other export settings and the art; the open diff --git a/crates/engine/src/tests/live.rs b/crates/engine/src/tests/live.rs index 2aa182c8b9..dc37c49761 100644 --- a/crates/engine/src/tests/live.rs +++ b/crates/engine/src/tests/live.rs @@ -1629,9 +1629,9 @@ fn cmyk_mesh(create: Value) -> (Session, NodeId) { (s, a) } -/// The fill colours `document.exportPdf {standard: pdfX4}` writes (`… scn` operands, and the -/// corner colours of its gradient meshes, which are patch shadings, as PDF import reads them -/// back), and its warnings. +/// The fill colours `document.exportPdf {standard: pdfX4}` writes (`… scn` and DeviceCMYK +/// `c m y k k` operands, and the corner colours of its gradient meshes, which are patch shadings, +/// as PDF import reads them back), and its warnings. fn pdf_fill_colours(s: &mut Session) -> (Vec>, Vec) { let v = s.execute("document.exportPdf", &json!({"standard": "pdfX4", "compression": {"compressText": false}})).unwrap(); let bytes = vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap(); @@ -1646,6 +1646,11 @@ fn pdf_fill_colours(s: &mut Session) -> (Vec>, Vec) { if !nums.is_empty() { out.push(nums.into_iter().rev().collect()); } + } else if *w == "k" { + let nums: Vec = words[..i].iter().rev().take(4).map_while(|x| x.parse().ok()).collect(); + if nums.len() == 4 { + out.push(nums.into_iter().rev().collect()); + } } } } diff --git a/crates/engine/src/tests/livecorners.rs b/crates/engine/src/tests/livecorners.rs index 1797ce27fe..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. @@ -524,6 +585,107 @@ fn a_polygon_takes_its_angle_radius_side_length_and_equal_sides() { } } +/// A live line's Line Properties: Line Length keeps its first end in place, Line Angle (degrees +/// counterclockwise, any finite value brought into 0 to 360) turns it about its midpoint, the +/// length applies before the angle, every selected line takes them in one undo step, and a value +/// that changes nothing records none. +#[test] +fn a_line_takes_its_length_and_angle() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let line = |s: &mut Session, a: (f64, f64), b: (f64, f64)| { + NodeId(s.execute("shape.line", &json!({"x1": a.0, "y1": a.1, "x2": b.0, "y2": b.1})).unwrap()["id"].as_u64().unwrap()) + }; + let id = line(&mut s, (100.0, 100.0), (200.0, 100.0)); + let ends = |s: &Session, id: NodeId| match &s.doc().unwrap().doc.node(id).unwrap().kind { + NodeKind::Path { live: Some(l), path, .. } => { + let LiveShape::Line { a, b } = **l else { panic!("{l:?}") }; + assert_eq!(*path, l.to_path(), "the path follows the line"); + (a.x, a.y, b.x, b.y) + } + k => panic!("{k:?}"), + }; + let near = |got: (f64, f64, f64, f64), want: (f64, f64, f64, f64)| { + assert!([got.0 - want.0, got.1 - want.1, got.2 - want.2, got.3 - want.3].iter().all(|d| d.abs() < 1e-9), "{got:?} ≠ {want:?}") + }; + let steps = |s: &Session| s.doc().unwrap().history.undo.len(); + run(&mut s, json!({"lineLength": 50})); + near(ends(&s, id), (100.0, 100.0, 150.0, 100.0)); + // 90° points up the page. + run(&mut s, json!({"lineAngle": 90})); + near(ends(&s, id), (125.0, 125.0, 125.0, 75.0)); + let n = steps(&s); + for same in [json!({"lineAngle": 450}), json!({"lineAngle": -270}), json!({"lineLength": 50}), json!({"lineLength": 50, "lineAngle": 90})] { + run(&mut s, same.clone()); + assert_eq!(steps(&s), n, "{same} records no undo step"); + } + near(ends(&s, id), (125.0, 125.0, 125.0, 75.0)); + run(&mut s, json!({"lineLength": 20, "lineAngle": 0})); + near(ends(&s, id), (115.0, 115.0, 135.0, 115.0)); + assert_eq!(steps(&s), n + 1, "both in one step"); + run(&mut s, json!({"lineAngle": 180})); + near(ends(&s, id), (135.0, 115.0, 115.0, 115.0)); + run(&mut s, json!({"lineAngle": -90})); + near(ends(&s, id), (125.0, 105.0, 125.0, 125.0)); + let LiveShape::Line { .. } = s.doc().unwrap().doc.node(id).unwrap().live_shape().unwrap() else { panic!("still live") }; + assert_eq!(s.doc().unwrap().doc.node(id).unwrap().live_shape().unwrap().line_angle(), Some(270.0)); + // Several lines: each keeps its own first end, in one undo step. + let other = line(&mut s, (0.0, 0.0), (0.0, 40.0)); + let n = steps(&s); + run(&mut s, json!({"ids": [id.0, other.0], "lineLength": 10})); + near(ends(&s, id), (125.0, 105.0, 125.0, 115.0)); + near(ends(&s, other), (0.0, 0.0, 0.0, 10.0)); + assert_eq!(steps(&s), n + 1); + s.execute("edit.undo", &json!({})).unwrap(); + near(ends(&s, id), (125.0, 105.0, 125.0, 125.0)); + near(ends(&s, other), (0.0, 0.0, 0.0, 40.0)); + // Bad values, and a line that would reach past the coordinate limit, change neither line. + let far = line(&mut s, (3_900_000.0, 0.0), (3_900_100.0, 0.0)); + let n = steps(&s); + for bad in [ + json!({"ids": [id.0], "lineLength": 0}), + json!({"ids": [id.0], "lineLength": -3}), + json!({"ids": [id.0], "lineLength": "long"}), + json!({"ids": [id.0], "lineAngle": "up"}), + json!({"ids": [id.0], "lineLength": 1e300}), + json!({"ids": [id.0, far.0], "lineLength": 200_000}), + ] { + assert!(s.execute("object.setLiveShape", &bad).is_err(), "{bad}"); + assert_eq!(steps(&s), n, "{bad}"); + } + near(ends(&s, id), (125.0, 105.0, 125.0, 125.0)); + near(ends(&s, far), (3_900_000.0, 0.0, 3_900_100.0, 0.0)); + // A length past the coordinate limit is fine while both ends stay inside it. + let wide = line(&mut s, (-3_500_000.0, 0.0), (3_500_000.0, 0.0)); + run(&mut s, json!({"ids": [wide.0], "lineLength": 6_000_000})); + near(ends(&s, wide), (-3_500_000.0, 0.0, 2_500_000.0, 0.0)); + // A line whose ends meet reads 0°: an angle leaves it as it is, and a length points it right. + let dot = line(&mut s, (10.0, 10.0), (10.0, 10.0)); + assert_eq!(s.doc().unwrap().doc.node(dot).unwrap().live_shape().unwrap().line_angle(), Some(0.0)); + let n = steps(&s); + run(&mut s, json!({"lineAngle": 45})); + assert_eq!(steps(&s), n); + run(&mut s, json!({"lineLength": 30})); + near(ends(&s, dot), (10.0, 10.0, 40.0, 10.0)); + // A very short length is applied. + let speck = line(&mut s, (20.0, 20.0), (20.0, 20.0)); + let n = steps(&s); + run(&mut s, json!({"ids": [speck.0], "lineLength": 1e-12})); + assert_eq!(steps(&s), n + 1, "a length of 1e-12 pt is a change"); + assert!(ends(&s, speck).2 > 20.0, "{:?}", ends(&s, speck)); + // A length so short that the rounded ends do not move records no undo step. + let dust = line(&mut s, (20.0, 20.0), (20.0, 20.0)); + let n = steps(&s); + run(&mut s, json!({"ids": [dust.0], "lineLength": 1e-20})); + assert_eq!(steps(&s), n, "a length of 1e-20 pt changes nothing"); + near(ends(&s, dust), (20.0, 20.0, 20.0, 20.0)); + // Other live shapes ignore the line params. + let rect = NodeId(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap()); + let n = steps(&s); + run(&mut s, json!({"ids": [rect.0], "lineLength": 30, "lineAngle": 45})); + assert_eq!(steps(&s), n); +} + #[test] fn relative_corner_rounding_keeps_fraction_on_resize() { let (mut s, id) = session(); diff --git a/crates/engine/src/tests/menucmds.rs b/crates/engine/src/tests/menucmds.rs index 1faeaa76ad..2656d8c4f8 100644 --- a/crates/engine/src/tests/menucmds.rs +++ b/crates/engine/src/tests/menucmds.rs @@ -4473,6 +4473,58 @@ fn exit_isolation_leaves_a_locked_guide_path_deselected() { assert_eq!(selected(&s), vec![g]); } +/// Exit Isolation Mode on an isolated sublayer isolates its parent layer and selects the sublayer, one +/// layer per call, without an undo step; from the top-level layer it leaves isolation mode. `all: true` +/// leaves from any depth, a hidden parent layer is not isolated (the call leaves), and a group in a +/// sublayer still leaves in one call. +#[test] +fn exit_isolation_goes_up_one_layer_from_a_sublayer() { + let mut s = session(); + let top = s.doc().unwrap().doc.layers[0].id; + let mid = id_of(&s.execute("layer.newSublayer", &json!({"parent": top.0})).unwrap()); + let deep = id_of(&s.execute("layer.newSublayer", &json!({"parent": mid.0})).unwrap()); + s.execute("layer.setCurrent", &json!({"id": deep.0})).unwrap(); + let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + let b = rect(&mut s, 20.0, 0.0, 10.0, 10.0); + let isolation = |s: &Session| s.doc().unwrap().isolation; + let exit = |s: &mut Session, p: Value| s.execute("object.exitIsolation", &p).unwrap(); + + s.execute("object.isolate", &json!({"id": deep.0})).unwrap(); + let before = history(&s); + exit(&mut s, json!({})); + assert_eq!((isolation(&s), selected(&s)), (Some(mid), vec![deep]), "up from the deepest sublayer"); + exit(&mut s, json!({})); + assert_eq!((isolation(&s), selected(&s)), (Some(top), vec![mid]), "up from the middle sublayer"); + exit(&mut s, json!({})); + assert_eq!((isolation(&s), selected(&s)), (None, vec![top]), "out from the top-level layer"); + assert_eq!(history(&s), before, "no undo step"); + + s.execute("object.isolate", &json!({"id": deep.0})).unwrap(); + exit(&mut s, json!({"all": true})); + assert_eq!((isolation(&s), selected(&s)), (None, vec![deep]), "all: true"); + s.execute("object.isolate", &json!({"id": deep.0})).unwrap(); + exit(&mut s, json!({"all": false})); + assert_eq!(isolation(&s), Some(mid), "all: false"); + for bad in [json!({"all": 1}), json!({"all": "yes"}), json!({"all": null})] { + let e = s.execute("object.exitIsolation", &bad).unwrap_err().to_string(); + assert!(e.contains("`all` must be true or false"), "{bad}: {e}"); + assert_eq!(isolation(&s), Some(mid), "{bad}: still isolated"); + } + + // A parent layer hidden while its sublayer is isolated isn't isolated: the call leaves. + s.execute("object.isolate", &json!({"id": deep.0})).unwrap(); + s.execute("layer.setProps", &json!({"id": mid.0, "visible": false})).unwrap(); + exit(&mut s, json!({})); + assert_eq!(isolation(&s), None, "hidden parent layer"); + s.execute("layer.setProps", &json!({"id": mid.0, "visible": true})).unwrap(); + + sel(&mut s, &[a, b]); + let g = id_of(&s.execute("object.group", &json!({})).unwrap()); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + exit(&mut s, json!({})); + assert_eq!((isolation(&s), selected(&s)), (None, vec![g]), "a group in a sublayer"); +} + /// Undo and Redo bring back a selection without the guides, ruler guides or guide paths, that /// Lock Guides has locked since, so a move after them leaves the guides where they are. #[test] @@ -5689,3 +5741,20 @@ fn crop_image_trim_leaves_a_cmyk_image_alone() { let r = s.execute("object.cropImage", &json!({"trim": true})).unwrap(); assert_eq!((r["trimmed"].as_bool(), r["width"].as_u64(), r["height"].as_u64()), (Some(false), Some(4), Some(2)), "{r}"); } + +/// Lock Guides is not an undo step: it adds none, and undo and redo of the steps before it leave +/// the guides locked. +#[test] +fn lock_guides_is_not_an_undo_step() { + let mut s = session(); + let g = rect(&mut s, 200.0, 0.0, 10.0, 10.0); + sel(&mut s, &[g]); + s.execute("view.guides.make", &json!({})).unwrap(); + let steps = s.doc().unwrap().history.undo.len(); + s.execute("view.guides.lock", &json!({"locked": true})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), steps); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.guides_locked()); + s.execute("edit.redo", &json!({})).unwrap(); + assert!(s.guides_locked()); +} diff --git a/crates/engine/src/tests/newdoc.rs b/crates/engine/src/tests/newdoc.rs index 9e20de0ad1..c6699190b6 100644 --- a/crates/engine/src/tests/newdoc.rs +++ b/crates/engine/src/tests/newdoc.rs @@ -637,6 +637,69 @@ fn an_edited_profile_starts_the_documents_of_its_category() { let _ = std::fs::remove_dir_all(&dir); } +/// The fill, stroke and weight of `id` in the active document. +fn look(s: &Session, id: u64) -> (vectorcraft_color::Paint, vectorcraft_color::Paint, Option) { + let n = s.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).cloned().unwrap(); + (n.appearance.fill_paint(), n.appearance.stroke_paint(), n.appearance.stroke().map(|st| st.width)) +} + +#[test] +fn a_redefined_default_graphic_style_in_a_profile_is_the_default_fill_and_stroke() { + use vectorcraft_color::Paint; + let (mut s, dir) = with_profiles("default-style"); + // The Print profile's Default Graphic Style becomes no fill and a 0.25 pt red stroke. + s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap(); + s.execute("paint.setFill", &json!({"none": true})).unwrap(); + s.execute("paint.setStroke", &json!({"color": "#ff0000"})).unwrap(); + s.execute("stroke.set", &json!({"weight": 0.25})).unwrap(); + s.execute("graphicStyle.redefine", &json!({"name": "Default Graphic Style"})).unwrap(); + s.execute("document.save", &json!({})).unwrap(); + let style = s.doc().unwrap().doc.graphic_styles[0].clone(); + let red = style.appearance.stroke_paint(); + assert!(matches!(red, Paint::Solid { .. }), "{red:?}"); + assert_eq!(style.appearance.stroke().map(|st| st.width), Some(0.25), "{style:?}"); + // The Mobile profile is saved as shipped. + s.execute("file.newProfiles.edit", &json!({"name": "Mobile"})).unwrap(); + s.execute("document.save", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#00ff00"})).unwrap(); + let green = s.paint.fill.clone(); + + // A document from the Print profile starts with the style's fill, stroke and weight, and its art takes them. + s.execute("file.new", &json!({"profile": "Print", "colorMode": "cmyk"})).unwrap(); + assert_eq!((s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width), (Paint::None, red.clone(), 0.25)); + let id = s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 60, "height": 60})).unwrap()["id"].as_u64().unwrap(); + assert_eq!(look(&s, id), (Paint::None, red.clone(), Some(0.25))); + // Default Fill and Stroke gives the selection and the defaults that look again, as one undo step. + s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + s.execute("stroke.set", &json!({"weight": 3})).unwrap(); + let steps = s.doc().unwrap().history.undo.len(); + s.execute("paint.default", &json!({})).unwrap(); + assert_eq!(look(&s, id), (Paint::None, red.clone(), Some(0.25))); + assert_eq!((s.paint.fill.clone(), s.paint.stroke_width), (Paint::None, 0.25)); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1); + // Nothing to change: no undo step. + let step = s.doc().unwrap().history.step(); + s.execute("paint.default", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().history.step(), step); + // The new art is not linked to the style. + assert!(s.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().extras().graphic_style.is_none()); + + // A profile with the shipped style, here converted to CMYK, leaves the fill and stroke the user chose. + s.execute("select.none", &json!({})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#00ff00", "keepModel": true})).unwrap(); + s.execute("file.new", &json!({"profile": "Mobile", "colorMode": "cmyk"})).unwrap(); + assert_eq!(s.doc().unwrap().doc.color_mode, ColorMode::Cmyk); + assert_eq!(s.paint.fill, green); + // So does a document without a profile, and Default Fill and Stroke there gives white and 1 pt black. + s.execute("file.new", &json!({})).unwrap(); + assert_eq!(s.paint.fill, green); + s.execute("paint.default", &json!({})).unwrap(); + assert_eq!(s.paint, vectorcraft_tools::PaintDefaults::default()); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn the_profile_follows_the_preset_access_and_reset() { let (mut s, dir) = with_profiles("choice"); @@ -682,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 708b602d1f..ca72e66eec 100644 --- a/crates/engine/src/tests/params.rs +++ b/crates/engine/src/tests/params.rs @@ -430,6 +430,8 @@ 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}), ] { assert!(check_params(ID, &ok).is_ok(), "{ok}"); diff --git a/crates/engine/src/tests/params_cache.rs b/crates/engine/src/tests/params_cache.rs new file mode 100644 index 0000000000..3fc2d629e7 --- /dev/null +++ b/crates/engine/src/tests/params_cache.rs @@ -0,0 +1,168 @@ +//! The params description of each built-in command is parsed once per process; the answers read +//! from it are those of parsing it where they are used. + +use std::hint::black_box; + +use serde_json::{Value, json}; + +use crate::cmd::params::{PARSES, accepted_keys, check_keys, doc_keys, id_stands_for_ids, read_once, takes_key, uncached}; +use crate::{Session, command_specs}; + +/// Every answer the key functions give about `doc` for command `id`, as text. +fn answers(id: &str, doc: &'static str) -> Vec { + let own = doc_keys(doc).map(|p| p.keys).unwrap_or_default(); + let accepted = accepted_keys(doc); + let mut out = vec![format!("{accepted:?}"), format!("{}", id_stands_for_ids(doc))]; + let near = own.first().map(|k| format!("{k}q")); + for key in own.iter().copied().chain(["ids", "id", "zzz"]).chain(near.as_deref()) { + out.push(format!("{key}: {}", takes_key(doc, key))); + } + let all: serde_json::Map = accepted.iter().flatten().map(|k| (k.to_string(), Value::Null)).collect(); + let mut cases = vec![json!({}), json!({"zzz": 1}), Value::Object(all)]; + cases.extend(near.map(|k| json!({ k: 1 }))); + for params in cases { + out.push(format!("{params}: {:?}", check_keys(id, doc, ¶ms))); + } + out +} + +#[test] +fn every_command_gets_the_answers_of_its_parsed_description() { + for c in command_specs() { + assert_eq!(answers(c.id, c.params), uncached(|| answers(c.id, c.params)), "{}", c.id); + } +} + +#[test] +fn a_built_in_description_is_not_parsed_again() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200, "created": null})).unwrap(); + let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap()["id"].as_u64().unwrap(); + let run = |s: &mut Session| { + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + s.execute("object.move", &json!({"ids": [id], "dx": 1})).unwrap(); + s.execute("object.move", &json!({"ids": [id], "dx": -1})).unwrap(); + for c in command_specs() { + black_box((accepted_keys(c.params), takes_key(c.params, "ids"), takes_key(c.params, "id"), id_stands_for_ids(c.params))); + black_box(check_keys(c.id, c.params, &json!({"zzz": 1})).is_err()); + } + }; + run(&mut s); + PARSES.set(0); + run(&mut s); + assert_eq!(PARSES.get(), 0, "descriptions parsed again"); + // Without the table each command parses its description where it is used. + uncached(|| run(&mut s)); + assert!(PARSES.get() > command_specs().len()); +} + +/// A description that isn't a built-in command's, even with the same words (a plug-in's), is parsed +/// where it is used, and so is one that names a plug-in command, whose keys change as plug-ins are +/// installed and removed. +#[test] +fn other_descriptions_are_parsed_where_they_are_used() { + let spec = command_specs().iter().find(|c| id_stands_for_ids(c.params)).unwrap(); + let copy: &'static str = String::from(spec.params).leak(); + assert_eq!(answers(spec.id, copy), answers(spec.id, spec.params)); + PARSES.set(0); + assert!(takes_key(copy, "ids") && id_stands_for_ids(copy)); + assert!(PARSES.get() > 0); + assert!(read_once("{a, …settings as file.new}")); + assert!(!read_once("{a, …settings as plugin.some.command}")); + assert!(!read_once("{a, …the options of `plugin.some.command`}")); +} + +/// This thread's CPU time in ns where Linux reports it, else the time since `start`. +fn now(start: std::time::Instant) -> (u128, bool) { + let cpu = std::fs::read_to_string("/proc/thread-self/schedstat").ok().and_then(|s| s.split_whitespace().next()?.parse().ok()); + match cpu { + Some(ns) => (ns, true), + None => (start.elapsed().as_nanos(), false), + } +} + +fn median(mut v: Vec) -> u128 { + v.sort_unstable(); + v[v.len() / 2] +} + +/// `cargo test --release -p vectorcraft-engine --lib params_cache -- --ignored --nocapture` prints +/// the time of the key questions over every built-in description and of `Session::execute` on a +/// one-object document, with descriptions parsed where they are used (`parse`) and read once +/// (`once`), alternating in one process: the median of 7 runs, in this thread's CPU time on Linux. +#[test] +#[ignore = "benchmark"] +fn bench_params_keys_once() { + let start = std::time::Instant::now(); + let specs = command_specs(); + let questions = || { + for c in specs { + black_box((accepted_keys(c.params), takes_key(c.params, "ids"), takes_key(c.params, "id"))); + black_box((takes_key(c.params, "ids"), takes_key(c.params, "id"), id_stands_for_ids(c.params))); + } + }; + let time = |f: &dyn Fn()| { + let t = now(start); + f(); + (now(start).0 - t.0, t.1) + }; + questions(); + uncached(questions); + let (mut parse, mut once, mut cpu) = (Vec::new(), Vec::new(), true); + for _ in 0..7 { + let (p, c1) = time(&|| uncached(|| (0..200).for_each(|_| questions()))); + let (o, c2) = time(&|| (0..200).for_each(|_| questions())); + parse.push(p); + once.push(o); + cpu &= c1 && c2; + } + let per = |ns: u128| ns / (200 * specs.len() as u128); + println!("clock: {}", if cpu { "thread CPU time" } else { "wall time" }); + println!("key questions, ns per description: parse {} once {}", per(median(parse)), per(median(once))); + for (cmd, params) in [("select.set", "ids"), ("object.move", "move")] { + let doc = || { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200, "created": null})).unwrap(); + let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap()["id"].as_u64().unwrap(); + let p = if params == "ids" { json!({"ids": [id]}) } else { json!({"ids": [id], "dx": 1}) }; + (s, p) + }; + let run = |s: &mut Session, p: &Value| { + for _ in 0..20_000 { + black_box(s.execute(cmd, p).unwrap()); + } + }; + let ((mut a, pa), (mut b, pb)) = (doc(), doc()); + assert_eq!(uncached(|| a.execute(cmd, &pa).unwrap()), b.execute(cmd, &pb).unwrap(), "{cmd}: both ways give the same result"); + let timed = |s: &mut Session, p: &Value, cached: bool| { + let t = now(start).0; + if cached { + run(s, p) + } else { + uncached(|| run(s, p)) + } + now(start).0 - t + }; + let (mut parse, mut once) = (Vec::new(), Vec::new()); + for i in 0..7 { + let (mut s1, p1) = doc(); + let (mut s2, p2) = doc(); + if i % 2 == 0 { + parse.push(timed(&mut s1, &p1, false)); + once.push(timed(&mut s2, &p2, true)); + } else { + once.push(timed(&mut s2, &p2, true)); + parse.push(timed(&mut s1, &p1, false)); + } + // Each document has a `uid` of its own. + let state = |s: &Session| { + let mut d = crate::inspect::document(s); + d.as_object_mut().unwrap().remove("uid"); + d + }; + assert_eq!(state(&s1), state(&s2), "{cmd}: same document"); + } + let ms = |ns: u128| ns as f64 / 1e6; + println!("{cmd} x 20,000: parse {:.1} ms once {:.1} ms", ms(median(parse)), ms(median(once))); + } +} diff --git a/crates/engine/src/tests/perspgrid.rs b/crates/engine/src/tests/perspgrid.rs index 4b7c1c2ae4..b4f8d89ca3 100644 --- a/crates/engine/src/tests/perspgrid.rs +++ b/crates/engine/src/tests/perspgrid.rs @@ -312,6 +312,91 @@ fn view_options_toggle_without_undo_steps_and_survive_presets() { assert_eq!(PerspectiveGrid::from_doc(&back), Some(g)); } +/// The view options are not undo steps, so undo and redo of other steps leave them as they are: +/// Lock Grid, Lock Station Point, Snap to Grid, Show Rulers and whether the grid shows. Undoing a +/// grid definition brings back the old grid with the current view options. +#[test] +fn undo_and_redo_keep_the_view_options() { + let mut s = session(); + run(&mut s, "perspective.grid.preset", json!({"kind": 2})); + let old = grid(&s); + run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 40})); + run(&mut s, "perspective.grid.preset", json!({"kind": 1})); + let n = undo_len(&s); + for (id, on) in + [("perspective.grid.lock", true), ("perspective.grid.lockStation", true), ("perspective.grid.snap", false), ("perspective.grid.rulers", true)] + { + run(&mut s, id, json!({"on": on})); + } + run(&mut s, "perspective.grid.show", json!({"visible": false})); + assert_eq!(undo_len(&s), n); + let view = |g: &PerspectiveGrid| (g.locked, g.lock_station, g.snap, g.rulers, g.visible); + let want = (true, true, false, true, false); + assert_eq!(view(&grid(&s)), want); + // Undo the one-point preset: the two-point grid comes back with today's view options. + s.execute("edit.undo", &json!({})).unwrap(); + let g = grid(&s); + assert_eq!((g.kind, g.vp_left, view(&g)), (old.kind, old.vp_left, want)); + // Undo the rectangle, which left the grid alone. + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(view(&grid(&s)), want); + // An option changed now holds through the redo steps. + run(&mut s, "perspective.grid.lock", json!({"on": false})); + s.execute("edit.redo", &json!({})).unwrap(); + s.execute("edit.redo", &json!({})).unwrap(); + let g = grid(&s); + assert_eq!((g.kind, view(&g)), (1, (false, true, false, true, false))); +} + +/// The view options set on a document whose steps hold no grid yet stay as they are when undo +/// brings back a step without one, and the active plane chosen without an undo step stays too. +#[test] +fn undo_keeps_the_view_options_of_a_grid_no_step_defined() { + let mut s = session(); + run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 40})); + run(&mut s, "shape.rectangle", json!({"x": 100, "y": 10, "width": 50, "height": 40})); + assert!(!s.doc().unwrap().doc.unknown.contains_key(vectorcraft_tools::distort::perspective::DOC_KEY)); + run(&mut s, "perspective.grid.show", json!({"visible": true})); + run(&mut s, "perspective.grid.lock", json!({"on": true})); + run(&mut s, "perspective.grid.snap", json!({"on": false})); + run(&mut s, "perspective.plane.set", json!({"plane": "ground"})); + let view = |g: &PerspectiveGrid| (g.visible, g.locked, g.snap, g.plane); + let want = (true, true, false, vectorcraft_tools::distort::perspective::Plane::Ground); + assert_eq!(view(&grid(&s)), want); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(view(&grid(&s)), want); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(view(&grid(&s)), want); +} + +/// A step that changed a view option itself takes it back on undo and sets it again on redo: a +/// preset shows the grid, and a grid definition can lock it. +#[test] +fn undo_takes_back_the_view_options_a_step_changed() { + let mut s = session(); + run(&mut s, "perspective.grid.preset", json!({"kind": 2})); + run(&mut s, "perspective.grid.show", json!({"visible": false})); + run(&mut s, "perspective.grid.preset", json!({"kind": 1})); + assert!(grid(&s).visible); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(!grid(&s).visible, "the preset showed the grid"); + s.execute("edit.redo", &json!({})).unwrap(); + assert!(grid(&s).visible); + let cell = grid(&s).cell; + run(&mut s, "perspective.grid.set", json!({"locked": true, "cell": cell + 10.0})); + assert!(grid(&s).locked); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!((grid(&s).locked, grid(&s).cell), (false, cell)); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!((grid(&s).locked, grid(&s).cell), (true, cell + 10.0)); + // An option the step left alone and changed after it stays as it is. + run(&mut s, "perspective.grid.snap", json!({"on": false})); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!((grid(&s).locked, grid(&s).snap), (false, false)); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!((grid(&s).locked, grid(&s).snap), (true, false)); +} + /// Lock Grid, Lock Station Point, Snap to Grid and Show Rulers refuse an `on` given as text or as /// another value that is not true or false: the grid and the undo history stay as they were. Null is /// read as the key left out, so it toggles the option. 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 81cea5fd59..966e68dc60 100644 --- a/crates/engine/src/tests/prefs.rs +++ b/crates/engine/src/tests/prefs.rs @@ -109,6 +109,23 @@ fn grid_prefs_apply_to_open_documents() { assert_eq!((g.spacing, g.subdivisions), (36.0, 4)); } +/// The grid preferences are not an undo step in the documents they apply to, so undo and redo +/// leave the grid as the preferences set it. +#[test] +fn undo_and_redo_keep_the_grid_prefs() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap(); + s.execute("prefs.set", &json!({"values": {"gridlineEvery": 36, "gridSubdivisions": 4}})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + let g = &s.doc().unwrap().doc.grid; + assert_eq!((g.spacing, g.subdivisions), (36.0, 4)); + s.execute("prefs.set", &json!({"values": {"gridlineEvery": 18, "gridSubdivisions": 3}})).unwrap(); + s.execute("edit.redo", &json!({})).unwrap(); + let g = &s.doc().unwrap().doc.grid; + assert_eq!((g.spacing, g.subdivisions), (18.0, 3)); +} + /// Guides & Grid › Gridline every and Subdivisions (#394): set with no document open, as the /// desktop app restores them at launch, they give `file.new`'s document their grid. #[test] @@ -447,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/symbollib.rs b/crates/engine/src/tests/symbollib.rs index c5d32e822a..02e45a7153 100644 --- a/crates/engine/src/tests/symbollib.rs +++ b/crates/engine/src/tests/symbollib.rs @@ -375,3 +375,69 @@ fn other_documents_symbols_load_and_unreadable_files_are_errors() { let bytes = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap(); assert_eq!(vectorcraft_format::load(&bytes).unwrap().symbols.len(), 1); } + +/// `symbol.placeFromDocument` places another open document's symbol in the active document as +/// one undo step, with the symbol it nests, the pattern its art uses and its Symbol Options. A +/// second placement uses what the first added; the source document is left as it was; a symbol +/// of the active document itself is placed as it is; a closed document, a name the document does +/// not have and bad params are errors that change nothing. +#[test] +fn another_documents_symbol_is_added_and_placed_in_one_step() { + let mut s = kit(); + let source = s.doc().unwrap().uid; + let source_doc = s.doc().unwrap().doc.clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + let before = undo_len(&s); + let r = run(&mut s, "symbol.placeFromDocument", json!({"sourceDocument": source, "name": "Badge", "x": 30, "y": 40})); + assert_eq!(undo_len(&s), before + 1, "added and placed in one step"); + assert_eq!(r["name"], "Badge"); + let mut names = symbols(&s); + names.sort(); + assert_eq!(names, ["Badge", "Star"], "the nested Star came along"); + assert_eq!(doc(&s).symbol_registration("Badge"), SymbolRegistration(0)); + let placed = NodeId(r["id"].as_u64().unwrap()); + assert_eq!(s.doc().unwrap().selection.objects, [placed]); + let NodeKind::SymbolInstance { symbol, .. } = &doc(&s).node(placed).unwrap().kind else { panic!("not an instance") }; + assert_eq!(symbol, "Badge"); + let size = |d: &vectorcraft_doc::Document| d.unknown.get("symbolSizes").and_then(|m| m.get("Badge")).cloned(); + assert!(size(doc(&s)).is_some()); + assert_eq!(size(doc(&s)), size(&source_doc)); + // The Dots symbol brings its pattern and swatch. + run(&mut s, "symbol.placeFromDocument", json!({"sourceDocument": source, "name": "Dots"})); + assert!(doc(&s).pattern("Dots").is_some() && doc(&s).swatch("Dots").is_some()); + // Placed again, Badge is the one already added. + let count = doc(&s).symbols.len(); + let r = run(&mut s, "symbol.placeFromDocument", json!({"sourceDocument": source, "name": "Badge"})); + assert_eq!((r["name"].as_str(), doc(&s).symbols.len()), (Some("Badge"), count)); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "edit.undo", json!({})); + assert!(symbols(&s).is_empty() && doc(&s).pattern("Dots").is_none()); + // The active document's own symbol, by its uid: placed, nothing added. + run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})); + run(&mut s, "symbol.new", json!({"name": "Star"})); + let own = s.doc().unwrap().uid; + let before = undo_len(&s); + let r = run(&mut s, "symbol.placeFromDocument", json!({"sourceDocument": own, "name": "Star", "x": 70, "y": 70})); + assert_eq!((undo_len(&s), r["name"].as_str(), symbols(&s)), (before + 1, Some("Star"), vec!["Star".to_string()])); + // Errors change nothing. + let before = (undo_len(&s), doc(&s).clone()); + for p in [ + json!({"sourceDocument": source, "name": "Nope"}), + json!({"sourceDocument": source}), + json!({"name": "Star"}), + json!({"sourceDocument": -1, "name": "Star"}), + json!({"sourceDocument": "1", "name": "Star"}), + json!({"sourceDocument": source, "name": "Star", "x": "10"}), + json!({"sourceDocument": u64::MAX, "name": "Star"}), + ] { + assert!(s.execute("symbol.placeFromDocument", &p).is_err(), "{p}"); + assert_eq!((undo_len(&s), doc(&s)), (before.0, &before.1), "{p}"); + } + // The source document is left as it was, and once it is closed its symbols are gone with it. + assert!(s.set_active(0)); + assert_eq!(*s.doc().unwrap().doc, *source_doc); + run(&mut s, "file.close", json!({"index": 0})); + let e = s.execute("symbol.placeFromDocument", &json!({"sourceDocument": source, "name": "Star"})).unwrap_err(); + assert!(e.to_string().contains("no longer open"), "{e}"); +} diff --git a/crates/engine/src/tests/toolsettings.rs b/crates/engine/src/tests/toolsettings.rs index a9d9e3f5bd..fbde9edca7 100644 --- a/crates/engine/src/tests/toolsettings.rs +++ b/crates/engine/src/tests/toolsettings.rs @@ -246,7 +246,12 @@ fn spiral_decay_is_normalized_for_active_and_inactive_tools_and_preferences() { let mut s = session(); for active in [false, true] { select(&mut s, if active { "spiral" } else { "selection" }); - let options = s.set_tool_option_cmd(&json!({"tool": "spiral", "values": {"decay": 150, "segments": 4, "clockwise": false}})).unwrap(); + // A decay past the 99.99 % a spiral draws is refused, and nothing changes. + let before = s.tool_options_of("spiral"); + let refused = s.set_tool_option_cmd(&json!({"tool": "spiral", "values": {"decay": 150, "segments": 4, "clockwise": false}})); + assert_eq!(refused.err(), Some("tool `spiral`: `decay` must be a number from 5 to 99.99".to_string())); + assert_eq!(s.tool_options_of("spiral"), before); + let options = s.set_tool_option_cmd(&json!({"tool": "spiral", "values": {"decay": 99.99, "segments": 4, "clockwise": false}})).unwrap(); assert_eq!(options["decay"], json!(99.99)); assert_eq!(s.tool_options_of("spiral")["decay"], json!(99.99)); assert_eq!(s.prefs.tool_settings["spiral"]["decay"], json!(99.99)); @@ -387,3 +392,110 @@ fn alt_smoothing_takes_the_smooth_tools_fidelity() { assert_eq!(s.tool_options()["fidelity"], json!(3.0), "{id}"); } } + +/// `tool.setOption` with a value of the wrong type, a number out of range, an unknown value or an +/// option the tool doesn't have is an error naming the tool and the option. Nothing is set, also +/// when another option given with it is good, and nothing is saved or recorded for undo. +#[test] +fn bad_option_values_are_errors_that_set_nothing() { + let mut s = session(); + select(&mut s, "smooth"); + let (options, saved, undo) = (s.tool_options(), s.prefs.tool_settings.clone(), s.doc().unwrap().history.undo.len()); + let fidelity = "tool `smooth`: `fidelity` must be a number from 0.05 to 100"; + for bad in [json!("abc"), json!(true), json!(-3), json!(1e9), json!(null), json!([2])] { + assert_eq!(s.set_tool_option_cmd(&json!({"key": "fidelity", "value": bad})).unwrap_err(), fidelity, "{bad}"); + } + let cases = [ + (json!({"key": "bogus", "value": 1}), "tool `smooth`: unknown option `bogus`"), + (json!({"tool": "pencil", "values": {"closeWithin": 5, "fidelity": "x"}}), "tool `pencil`: `fidelity` must be a number from 0.01 to 100"), + (json!({"tool": "pencil", "key": "fill", "value": "yes"}), "tool `pencil`: `fill` must be true or false"), + (json!({"tool": "blobBrush", "key": "sizeMode", "value": "huge"}), "tool `blobBrush`: `sizeMode` must be one of `fixed`, `pressure`"), + (json!({"tool": "eraser", "key": "fidelity", "value": 4}), "tool `eraser`: unknown option `fidelity`"), + (json!({"tool": "polygon", "key": "sides", "value": 2}), "tool `polygon`: `sides` must be a whole number from 3 to 1000"), + ( + json!({"tool": "mirrorCut", "key": "axis", "value": "diagonal"}), + "tool `mirrorCut`: `axis` must be one of `vertical`, `horizontal`, `free`", + ), + (json!({"tool": "selection", "key": "fidelity", "value": 4}), "tool `selection`: unknown option `fidelity`"), + (json!({"values": [1]}), "`values` must be an object"), + (json!({"tool": 3, "key": "fidelity", "value": 4}), "`tool` must be a tool id"), + (json!({"key": "fidelity"}), "`value` is missing for `fidelity`"), + ]; + for (p, want) in cases { + assert_eq!(s.set_tool_option_cmd(&p).unwrap_err(), want, "{p}"); + } + assert_eq!(s.tool_options_of("pencil")["closeWithin"], session().tool_options_of("pencil")["closeWithin"]); + assert_eq!((s.tool_options(), &s.prefs.tool_settings, s.doc().unwrap().history.undo.len()), (options, &saved, undo)); + // A good value after the errors is set and read back. + assert_eq!(s.set_tool_option_cmd(&json!({"key": "fidelity", "value": 9})).unwrap()["fidelity"], json!(9.0)); +} + +/// `tool.setOption {}` reads the options, of the active tool or of the tool named, and saves nothing. +#[test] +fn an_empty_set_option_reads_and_saves_nothing() { + let mut s = session(); + select(&mut s, "smooth"); + let saved = s.prefs.tool_settings.clone(); + assert_eq!(s.set_tool_option_cmd(&json!({})).unwrap(), s.tool_options()); + assert_eq!(s.set_tool_option_cmd(&json!({"tool": "flare"})).unwrap(), s.tool_options_of("flare")); + // No params (null) read too; params that are not an object are an error. + assert_eq!(s.set_tool_option_cmd(&serde_json::Value::Null).unwrap(), s.tool_options()); + for (bad, got) in [(json!(true), "true"), (json!([]), "[]")] { + assert_eq!(s.set_tool_option_cmd(&bad).unwrap_err(), format!("the params must be an object, not {got}")); + } + assert_eq!(s.prefs.tool_settings, saved); +} + +/// A Place queue with a malformed entry is an error, and the queue held stays as it was. +#[test] +fn a_malformed_place_queue_is_an_error() { + let mut s = session(); + select(&mut s, "place"); + let entry = json!({"params": {"svg": ""}, "name": "a", "width": 10, "height": 10}); + s.set_tool_option_cmd(&json!({"key": "queue", "value": {"entries": [entry]}})).unwrap(); + let bad = json!({"params": {}, "name": "b", "width": "wide", "height": 10}); + let e = s.set_tool_option_cmd(&json!({"key": "queue", "value": {"entries": [entry, bad]}})).unwrap_err(); + assert!(e.starts_with("tool `place`: `queue` must be"), "{e}"); + assert_eq!(s.tool_options()["names"], json!(["a"])); + assert_eq!( + s.set_tool_option_cmd(&json!({"key": "current", "value": 1})).unwrap_err(), + "tool `place`: `current` must be the index of a queued file, from 0 to 0" + ); +} + +/// A `current` given with a new Place queue picks among the files of that queue. +#[test] +fn a_place_queue_and_its_current_file_set_together() { + let mut s = session(); + select(&mut s, "place"); + let entry = |name: &str| json!({"params": {"svg": ""}, "name": name, "width": 10, "height": 10}); + let queue = json!({"entries": [entry("a"), entry("b"), entry("c")]}); + let out = s.set_tool_option_cmd(&json!({"values": {"queue": queue, "current": 2}})).unwrap(); + assert_eq!((out["names"].clone(), out["current"].clone()), (json!(["a", "b", "c"]), json!(2))); + let short = json!({"entries": [entry("d")]}); + let e = s.set_tool_option_cmd(&json!({"values": {"queue": short, "current": 2}})).unwrap_err(); + assert_eq!(e, "tool `place`: `current` must be the index of a queued file, from 0 to 0"); + assert_eq!(s.tool_options()["names"], json!(["a", "b", "c"]), "a refused call keeps the queue held"); +} + +/// A value given with a parametric shape's new `kind` is checked against that kind's range and +/// set on it, whether the tool is chosen or not. +#[test] +fn a_parametric_shape_kind_and_its_values_set_together() { + for active in [false, true] { + let mut s = session(); + if active { + select(&mut s, "parametricShape"); + } + let set = |s: &mut Session, values: serde_json::Value| s.set_tool_option_cmd(&json!({"tool": "parametricShape", "values": values})); + set(&mut s, json!({"kind": "polygon"})).unwrap(); + let out = set(&mut s, json!({"kind": "star", "a": 0.8})).unwrap(); + assert_eq!((out["kind"].clone(), out["a"].clone()), (json!("star"), json!(0.8)), "active {active}"); + set(&mut s, json!({"kind": "ring"})).unwrap(); + let out = set(&mut s, json!({"kind": "star", "a": 1.0})).unwrap(); + assert_eq!((out["kind"].clone(), out["a"].clone()), (json!("star"), json!(1.0)), "active {active}"); + let e = set(&mut s, json!({"kind": "ring", "a": 1.0})).unwrap_err(); + assert!(e.contains("`a`"), "{e}"); + assert_eq!(s.tool_options_of("parametricShape")["kind"], json!("star"), "a refused call sets nothing"); + } +} diff --git a/crates/engine/src/tests/widthpoints.rs b/crates/engine/src/tests/widthpoints.rs index 6aa324aa90..bed235421e 100644 --- a/crates/engine/src/tests/widthpoints.rs +++ b/crates/engine/src/tests/widthpoints.rs @@ -167,6 +167,124 @@ fn adjust_adjoining_scales_the_neighbours() { assert_eq!(points(&s, id), vec![(0.5, 4.0, 1.0)]); } +/// A line with a discontinuous point in the middle: 1× before it, 2× after it. +fn pair_session(points: serde_json::Value) -> (Session, NodeId) { + let (mut s, id) = line_session(); + s.execute("stroke.widthProfile.set", &json!({"ids": [id.0], "points": points})).unwrap(); + s.doc_mut().unwrap().mark_saved(); + (s, id) +} + +#[test] +fn paired_set_edits_both_halves_in_one_step() { + let (mut s, id) = pair_session(json!([[0, 1, 1], [0.5, 1, 1], [0.5, 2, 2], [1, 1, 1]])); + let before = s.doc().unwrap().doc.clone(); + let undo = s.doc().unwrap().history.undo.len(); + let p = json!({"id": id.0, "index": 1, "t": 0.5, "left": 10, "right": 5, "outIndex": 2, "outLeft": 15, "outRight": 20}); + assert_eq!(set(&mut s, p.clone()), 1); + assert_eq!(points(&s, id), vec![(0.0, 1.0, 1.0), (0.5, 2.0, 1.0), (0.5, 3.0, 4.0), (1.0, 1.0, 1.0)]); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + let after = s.doc().unwrap().doc.clone(); + // The same widths again change nothing and record no undo step. + set(&mut s, p); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc, before); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc, after); +} + +#[test] +fn paired_set_adjusts_the_point_before_and_the_point_after_once_each() { + let (mut s, id) = pair_session(json!([[0, 1, 1], [0.5, 1, 1], [0.5, 2, 2], [1, 1, 1]])); + // The incoming half doubles and the outgoing half halves: the start doubles, the end halves. + set( + &mut s, + json!({"id": id.0, "index": 1, "t": 0.5, "left": 10, "right": 10, "outIndex": 2, "outLeft": 5, "outRight": 5, "adjustAdjoining": true}), + ); + assert_eq!(points(&s, id), vec![(0.0, 2.0, 2.0), (0.5, 2.0, 2.0), (0.5, 1.0, 1.0), (1.0, 0.5, 0.5)]); + // A discontinuous point at the start has only a point after it to adjust. + let (mut s, id) = pair_session(json!([[0, 1, 1], [0, 2, 2], [1, 1, 1]])); + set( + &mut s, + json!({"id": id.0, "index": 0, "t": 0, "left": 10, "right": 10, "outIndex": 1, "outLeft": 20, "outRight": 20, "adjustAdjoining": true}), + ); + assert_eq!(points(&s, id), vec![(0.0, 2.0, 2.0), (0.0, 4.0, 4.0), (1.0, 2.0, 2.0)]); +} + +/// Three points each within 1e-6 of the next: the first two are the pair, and the third, though +/// within 1e-6 of the outgoing half, is the point after the pair that the outgoing half adjusts. +#[test] +fn paired_set_adjusts_the_point_after_a_chained_pair() { + let (mut s, id) = pair_session(json!([[0, 1, 1], [0.5, 1, 1], [0.50000075, 2, 2], [0.5000015, 1, 1], [1, 1, 1]])); + set( + &mut s, + json!({"id": id.0, "index": 1, "t": 0.5, "left": 5, "right": 5, "outIndex": 2, "outLeft": 5, "outRight": 5, "adjustAdjoining": true}), + ); + assert_eq!(points(&s, id), vec![(0.0, 1.0, 1.0), (0.5, 1.0, 1.0), (0.50000075, 1.0, 1.0), (0.5000015, 0.5, 0.5), (1.0, 1.0, 1.0)]); +} + +#[test] +fn single_width_only_leaves_one_continuous_point() { + for (single, kept) in [("incoming", (2.0, 1.0)), ("outgoing", (3.0, 4.0))] { + let (mut s, id) = pair_session(json!([[0, 1, 1], [0.5, 1, 1], [0.5, 2, 2], [1, 1, 1]])); + let before = s.doc().unwrap().doc.clone(); + let undo = s.doc().unwrap().history.undo.len(); + let p = json!({"id": id.0, "index": 1, "t": 0.5, "left": 10, "right": 5, "outIndex": 2, "outLeft": 15, "outRight": 20, "single": single}); + assert_eq!(set(&mut s, p), 1); + assert_eq!(points(&s, id), vec![(0.0, 1.0, 1.0), (0.5, kept.0, kept.1), (1.0, 1.0, 1.0)], "{single}"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc, before); + } + // With Adjust Adjoining, each neighbor follows the change of the half beside it. + let (mut s, id) = pair_session(json!([[0, 1, 1], [0.5, 1, 1], [0.5, 2, 2], [1, 1, 1]])); + let p = json!({"id": id.0, "index": 1, "t": 0.5, "left": 5, "right": 5, "outIndex": 2, "outLeft": 5, "outRight": 5, "single": "incoming", "adjustAdjoining": true}); + set(&mut s, p); + assert_eq!(points(&s, id), vec![(0.0, 1.0, 1.0), (0.5, 1.0, 1.0), (1.0, 0.5, 0.5)]); +} + +#[test] +fn paired_set_refuses_what_is_not_one_discontinuous_point() { + let (mut s, id) = pair_session(json!([[0, 1, 1], [0.25, 1, 1], [0.5, 1, 1], [0.5, 2, 2], [0.75, 3, 3], [0.75, 3, 3], [0.75, 3, 3], [1, 1, 1]])); + let before = s.doc().unwrap().doc.clone(); + let undo = s.doc().unwrap().history.undo.len(); + let pair = |extra: serde_json::Value| { + let mut p = json!({"id": id.0, "index": 2, "t": 0.5, "left": 5, "right": 5, "outIndex": 3, "outLeft": 5, "outRight": 5}); + for (k, v) in extra.as_object().unwrap() { + if v.is_null() { + p.as_object_mut().unwrap().remove(k); + } else { + p[k] = v.clone(); + } + } + p + }; + for p in [ + pair(json!({"index": 1, "t": 0.25, "outIndex": 2})), + pair(json!({"outIndex": 4})), + pair(json!({"index": 3, "outIndex": 2})), + pair(json!({"outIndex": 99})), + pair(json!({"outIndex": "3"})), + pair(json!({"outIndex": -1})), + pair(json!({"t": 0.6})), + pair(json!({"index": 4, "t": 0.75, "outIndex": 5})), + pair(json!({"index": null})), + pair(json!({"outLeft": null})), + pair(json!({"outRight": -1})), + pair(json!({"outLeft": 1.0e6})), + pair(json!({"single": "both"})), + pair(json!({"single": true})), + pair(json!({"outIndex": null})), + pair(json!({"outIndex": null, "outLeft": null})), + json!({"id": id.0, "index": 2, "t": 0.5, "left": 5, "right": 5, "single": "incoming"}), + ] { + assert!(s.execute("stroke.widthPoint.set", &p).is_err(), "accepted {p}"); + assert_eq!(s.doc().unwrap().doc, before, "{p}"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo); + } +} + #[test] fn flipping_along_swaps_the_sides_of_a_discontinuous_point() { let (mut s, id) = line_session(); diff --git a/crates/engine/src/tests/widthtool.rs b/crates/engine/src/tests/widthtool.rs index fda761de61..6b2ed12c54 100644 --- a/crates/engine/src/tests/widthtool.rs +++ b/crates/engine/src/tests/widthtool.rs @@ -40,6 +40,24 @@ fn the_width_tool_edits_a_compound_paths_stroke() { assert_eq!(s.journal.last().unwrap().1["id"], json!(c.0)); } +/// A compound path whose stroke draws with a brush: a press or a double-click on a member puts the +/// tool's reason in the status bar and leaves the stroke and the undo history as they were. +#[test] +fn the_width_tool_says_why_it_leaves_a_brushed_compound_path_alone() { + let (mut s, c, _) = compound(); + s.execute("brush.apply", &json!({"ids": [c.0], "name": "3 pt. Round"})).unwrap(); + let steps = s.journal.len(); + let v = ViewInfo::default(); + s.select_tool("width", v).unwrap(); + for (kind, reason) in [(PointerKind::Down, true), (PointerKind::Drag, false), (PointerKind::Up, false), (PointerKind::DoubleClick, true)] { + let ui = s.pointer(&PointerEvent::new(kind, 200.0, 301.0), v).unwrap(); + let said = ui.iter().any(|r| matches!(r, UiRequest::Status(m) if m == vectorcraft_tools::distort::KEEPS_SIZE)); + assert_eq!(said, reason, "{kind:?}: {ui:?}"); + } + assert_eq!(profile(&s, c), None); + assert_eq!(s.journal.len(), steps, "no command ran"); +} + #[test] fn width_point_commands_given_a_member_edit_the_compound() { let (mut s, c, members) = compound(); 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/src/tooling.rs b/crates/engine/src/tooling.rs index 90a7c001e0..794cc7a2a3 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -1321,7 +1321,14 @@ impl Session { /// The options of tool `id`: the active tool's, or those it would have if chosen now. pub fn tool_options_of(&self, id: &str) -> Value { - if id == self.tool.id() { self.tool.options() } else { self.make_tool(id).options() } + if id == self.tool.id() { + self.tool.options() + } else if let Some(lender) = self.lender.as_deref().filter(|l| l.id() == id) { + // The tool that lent a selection tool for a Cmd-drag holds its options while it waits. + lender.options() + } else { + self.make_tool(id).options() + } } /// Set options of tool `id` (default: the active tool). Another tool's persistent options are @@ -1333,14 +1340,22 @@ impl Session { self.note_place_queue_roots(); } let active = id.is_none_or(|id| id == self.tool.id()); - self.tool_set_since_reset |= active; + // The tool that lent a selection tool for a Cmd-drag is the tool chosen, and active again + // when the drag ends. + let lender = id.is_some_and(|id| self.lender.as_deref().is_some_and(|l| l.id() == id)); + self.tool_set_since_reset |= active || lender; + // The Place queue and a parametric shape's kind are set first: setting the queue starts + // again at its first file, and a `current` given with it is an index into it; setting the + // kind puts the shape's other numbers back to that kind's, and those given with it are its. + let first = |k: &str| k == "queue" || k == "kind"; + let ordered = || values.iter().filter(|(k, _)| first(k)).chain(values.iter().filter(|(k, _)| !first(k))); let mut other = (!active).then(|| self.make_tool(id.unwrap_or_default())); let t = other.as_deref_mut().unwrap_or(self.tool.as_mut()); - for (k, v) in values { + for (k, v) in ordered() { t.set_option(k, v); } Self::store_tool_settings(&mut self.prefs, t); - let out = t.options(); + let mut out = t.options(); if let Some(other) = other { // The tool that lent a selection tool for a Cmd-drag is kept aside, not made again when // it is back: when it is the tool set, it takes the writes too (the Rounded Rectangle's @@ -1348,11 +1363,14 @@ impl Session { // active tool. if let Some(lender) = self.lender.as_deref_mut() { if lender.id() == other.id() { - for (k, v) in values { + for (k, v) in ordered() { lender.set_option(k, v); } } Self::restore_tool_settings(&self.prefs, lender); + if lender.id() == other.id() { + out = lender.options(); + } } // Only the stores it shares with the tool set: the active tool's own options stay as they // are, also in the middle of a drag that Escape can cancel. @@ -1364,21 +1382,28 @@ impl Session { /// `tool.setOption {tool?, key?, value?, values?}` (a command of the desktop app and of the /// headless host): set one option (`key`, `value`) or several (`values`) of `tool` (default: - /// the active tool) → its options. + /// the tool active when the call arrives, named before the edit in progress is finished) → its + /// options. With no option given, the options are read and nothing is set. Parameters that are + /// not an object are an error; none (null) read the options. Every option given is checked + /// first ([`vectorcraft_tools::Tool::check_option`]): an unknown option, a value of the wrong + /// type or a number out of range is an error that sets none of them. pub fn set_tool_option_cmd(&mut self, p: &Value) -> std::result::Result { - let tool = p.get("tool").and_then(Value::as_str); + let (tool, values) = vectorcraft_tools::option_check::set_option_params(p)?; if let Some(t) = tool && vectorcraft_tools::tool_info(t).is_none() { return Err(format!("unknown tool `{t}`")); } - let mut values = p.get("values").and_then(Value::as_object).cloned().unwrap_or_default(); - if let Some(k) = p.get("key").and_then(Value::as_str) { - values.insert(k.to_string(), p.get("value").cloned().unwrap_or(Value::Null)); + // The tool is named before the edit in progress is finished: finishing it can make a held + // Cmd press, which lends a selection tool and makes that the active tool. + let id = tool.unwrap_or(self.tool.id()); + let active = id == self.tool.id(); + if values.is_empty() { + return Ok(self.tool_options_of(id)); } // Every value is checked before any is set, so an invalid one changes nothing. - vectorcraft_tools::builder::check_builder_options(tool.unwrap_or(self.tool.id()), &values)?; - if tool.unwrap_or(self.tool.id()) == vectorcraft_tools::cropimage::ID { + vectorcraft_tools::builder::check_builder_options(id, &values)?; + if id == vectorcraft_tools::cropimage::ID { use vectorcraft_tools::cropimage as crop; // The most the selected image can be cropped to, when one is selected. let max = self.doc().ok().and_then(|st| { @@ -1397,7 +1422,7 @@ impl Session { crate::file_access::check_read(path)?; } } - if tool.unwrap_or(self.tool_id()) == "dimension" { + if id == "dimension" { if let Some(style) = values.get("style") { vectorcraft_doc::dimension::DimensionOptions::from_params(style.clone())?; } @@ -1407,11 +1432,16 @@ impl Session { return Err("Unknown dimension mode".into()); } } + if active { + vectorcraft_tools::option_check::check_values(self.tool.as_ref(), &values)?; + } else { + vectorcraft_tools::option_check::check_values(self.make_tool(id).as_ref(), &values)?; + } // The active tool's merge being computed is applied with the options it was started with. - if tool.is_none_or(|t| t == self.tool.id()) { + if active { self.finish_tool_edit_later().map_err(|e| e.to_string())?; } - Ok(self.set_tool_options(tool, &values)) + Ok(self.set_tool_options(Some(id), &values)) } /// Let the active tool finish work a command from outside it ended ([`vectorcraft_tools::Tool::after_command`]): diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index 0451692f16..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})), @@ -1273,6 +1276,36 @@ fn polygon_properties_junk() { assert!(failures.is_empty(), "{} failures:\n{}", failures.len(), failures.join("\n")); } +/// A live line's Line Properties with junk values (the fixtures have no line), on a line, a line +/// whose ends meet and one at the coordinate limit: never a panic, and the document stays sound. +#[test] +fn line_properties_junk() { + let mut cases: Vec = vec![json!({"lineLength": 4.0e6, "lineAngle": 45})]; + for key in ["lineLength", "lineAngle"] { + for v in junk_values() { + cases.push(json!({ key: v })); + } + } + let mut failures = vec![]; + for (a, b) in [((10.0, 20.0), (110.0, 70.0)), ((50.0, 50.0), (50.0, 50.0)), ((-4.0e6, 4.0e6), (4.0e6, -4.0e6))] { + for p in &cases { + let mut s = Fixture::Multi.session(); + let Ok(_) = no_panic(s.execute("shape.line", &json!({"x1": a.0, "y1": a.1, "x2": b.0, "y2": b.1}))) else { + continue; + }; + match catch_quiet(|| no_panic(s.execute("object.setLiveShape", p))) { + Err(m) => failures.push(format!("PANIC object.setLiveShape {p} [{a:?} {b:?}]: {m}")), + Ok(_) => { + if let Err(e) = catch_quiet(|| check_all(&mut s)).unwrap_or_else(|m| Err(format!("panic in checks: {m}"))) { + failures.push(format!("object.setLiveShape {p} [{a:?} {b:?}]: {e}")); + } + } + } + } + } + assert!(failures.is_empty(), "{} failures:\n{}", failures.len(), failures.join("\n")); +} + /// The params `fuzzed_calls_keep_documents_serializable` sends `c`: each key with each of the /// first junk values, a string under a file or folder key replaced by a location inside `path`'s /// folder. diff --git a/crates/engine/tests/it/dimensions.rs b/crates/engine/tests/it/dimensions.rs index 23bbdb0bee..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(); @@ -1971,9 +1994,15 @@ fn dimension_colours_follow_the_document_colour_model() { let black = colours(&s, id); assert!(!black.is_empty() && black.iter().all(|c| *c == vectorcraft_color::Color::cmyk(0.0, 0.0, 0.0, 1.0)), "{black:?}"); let pdf = pdf_content(&run(&mut s, "document.exportPdf", json!({"preset":"PDF/X-4:2010"}))); - // PDF/X-4 paints in the output intent's CMYK space: `/c0 CS 0 0 0 1 SCN` strokes, `scn` fills. - let operands = |op: &str| pdf.match_indices(op).map(|(i, _)| pdf[i.saturating_sub(7)..i].to_string()).collect::>(); - let (strokes, fills) = (operands(" SCN"), operands(" scn")); + // PDF/X-4 writes CMYK in the output intent's profile as DeviceCMYK: `0 0 0 1 K` strokes, `k` fills. + let words: Vec<&str> = pdf.split_whitespace().collect(); + let operands = |op: &str| { + (4..words.len()) + .filter(|&i| words[i] == op && words[i - 4..i].iter().all(|w| w.parse::().is_ok())) + .map(|i| words[i - 4..i].join(" ")) + .collect::>() + }; + let (strokes, fills) = (operands("K"), operands("k")); assert!(!strokes.is_empty() && !fills.is_empty(), "{pdf}"); assert!(strokes.iter().chain(&fills).all(|v| v == "0 0 0 1"), "K-only colours: {strokes:?} {fills:?}"); run(&mut s, "dimension.update", json!({"ids":[id],"options":{"lineColor":[255,0,0]}})); diff --git a/crates/engine/tests/path_fill_hits.rs b/crates/engine/tests/path_fill_hits.rs new file mode 100644 index 0000000000..f8dfebafaf --- /dev/null +++ b/crates/engine/tests/path_fill_hits.rs @@ -0,0 +1,244 @@ +//! Path fill hit testing follows the visible paint stack while transparent paint remains selectable. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::sync::Arc; + +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::hit::{HitKind, HitOptions, hit_test}; +use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, Node, NodeKind, StrokeLayer}; +use vectorcraft_geom::{Affine, FillRule, Point, Rect, shapes}; +use vectorcraft_render::{RenderOptions, Renderer}; + +fn fill(paint: Paint) -> FillLayer { + FillLayer::new(paint) +} + +fn rectangle(fills: Vec, stroke: bool) -> Document { + let mut doc = Document::new(128.0, 128.0); + let layer = doc.layers[0].id; + let id = doc.alloc_id(); + let mut appearance = Appearance::default(); + appearance.items.extend(fills.into_iter().map(AppearanceItem::Fill)); + if stroke { + appearance.items.push(AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::BLACK), 2.0))); + } + let path = shapes::rectangle(Rect::new(20.0, 20.0, 100.0, 100.0)); + doc.insert(Some(layer), usize::MAX, Node::path(id, path, appearance)).unwrap(); + doc +} + +fn compound(fills: Vec) -> Document { + let mut doc = Document::new(128.0, 128.0); + let layer = doc.layers[0].id; + let outer_id = doc.alloc_id(); + let inner_id = doc.alloc_id(); + let compound_id = doc.alloc_id(); + let children = vec![ + Arc::new(Node::path(outer_id, shapes::rectangle(Rect::new(20.0, 20.0, 100.0, 100.0)), Appearance::default())), + Arc::new(Node::path(inner_id, shapes::rectangle(Rect::new(50.0, 40.0, 70.0, 80.0)), Appearance::default())), + ]; + let mut appearance = Appearance::default(); + appearance.items.extend(fills.into_iter().map(AppearanceItem::Fill)); + appearance.items.push(AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::BLACK), 2.0))); + let mut node = Node::new(compound_id, NodeKind::Compound { children, rule: FillRule::EvenOdd }); + node.appearance = appearance.into(); + doc.insert(Some(layer), usize::MAX, node).unwrap(); + doc +} + +#[test] +fn hit_uses_the_visible_fill_stack() { + let black = || fill(Paint::solid(Color::BLACK)); + + let mut hidden = black(); + hidden.visible = false; + let mut transparent = black(); + transparent.opacity = 0.0; + let mut hidden_lower = black(); + hidden_lower.visible = false; + + let cases = vec![ + ("visible black fill", rectangle(vec![black()], true)), + ("lower black fill under a top None fill", rectangle(vec![black(), fill(Paint::None)], true)), + ("lower black fill under a top None fill without stroke", rectangle(vec![black(), fill(Paint::None)], false)), + ("only hidden non-None fill", rectangle(vec![hidden], true)), + ("basic Fill None", rectangle(vec![fill(Paint::None)], true)), + ("hidden lower black and top None fills", rectangle(vec![hidden_lower, fill(Paint::None)], true)), + ("visible fill at zero opacity", rectangle(vec![transparent], true)), + ]; + + let mut observed = Vec::new(); + for (name, doc) in cases { + let image = Renderer::new().render( + &doc, + 128, + 128, + Affine::IDENTITY, + &RenderOptions { background: None, artboards: false, ..RenderOptions::default() }, + ); + let center_alpha = image.pixel(60, 60)[3]; + let edge_alpha = image.pixel(100, 60)[3]; + let center = hit_test(&doc, Point::new(60.0, 60.0), HitOptions::default()).map(|hit| hit.kind); + let edge = hit_test(&doc, Point::new(100.5, 60.0), HitOptions::default()).map(|hit| hit.kind); + let outline = hit_test(&doc, Point::new(60.0, 60.0), HitOptions { outline: true, ..HitOptions::default() }).map(|hit| hit.kind); + let path_only = hit_test(&doc, Point::new(60.0, 60.0), HitOptions { path_only: true, ..HitOptions::default() }).map(|hit| hit.kind); + observed.push((name, center_alpha, edge_alpha, center, edge, outline, path_only)); + } + + let expected = vec![ + ("visible black fill", 255, 255, Some(HitKind::Fill), Some(HitKind::Stroke), None, None), + ("lower black fill under a top None fill", 255, 255, Some(HitKind::Fill), Some(HitKind::Stroke), None, None), + ("lower black fill under a top None fill without stroke", 255, 0, Some(HitKind::Fill), Some(HitKind::Outline), None, None), + ("only hidden non-None fill", 0, 255, None, Some(HitKind::Stroke), None, None), + ("basic Fill None", 0, 255, None, Some(HitKind::Stroke), None, None), + ("hidden lower black and top None fills", 0, 255, None, Some(HitKind::Stroke), None, None), + ("visible fill at zero opacity", 0, 255, Some(HitKind::Fill), Some(HitKind::Stroke), None, None), + ]; + assert_eq!(observed, expected, "render and hit-test observations by fill-stack case"); +} + +#[test] +fn compound_hit_uses_visible_fill_stack() { + let black = || fill(Paint::solid(Color::BLACK)); + + let mut hidden = black(); + hidden.visible = false; + let mut transparent = black(); + transparent.opacity = 0.0; + + let cases = vec![ + ("visible black fill", compound(vec![black()])), + ("lower black fill under a top None fill", compound(vec![black(), fill(Paint::None)])), + ("only hidden non-None fill", compound(vec![hidden])), + ("basic Fill None", compound(vec![fill(Paint::None)])), + ("visible fill at zero opacity", compound(vec![transparent])), + ]; + + let mut observed = Vec::new(); + for (name, doc) in cases { + let image = Renderer::new().render( + &doc, + 128, + 128, + Affine::IDENTITY, + &RenderOptions { background: None, artboards: false, ..RenderOptions::default() }, + ); + let ring_alpha = image.pixel(30, 60)[3]; + let hole_alpha = image.pixel(60, 60)[3]; + let edge_alpha = image.pixel(100, 60)[3]; + let ring = hit_test(&doc, Point::new(30.0, 60.0), HitOptions::default()).map(|hit| hit.kind); + let hole = hit_test(&doc, Point::new(60.0, 60.0), HitOptions::default()).map(|hit| hit.kind); + let edge = hit_test(&doc, Point::new(100.5, 60.0), HitOptions::default()).map(|hit| hit.kind); + let outline = hit_test(&doc, Point::new(30.0, 60.0), HitOptions { outline: true, ..HitOptions::default() }).map(|hit| hit.kind); + let path_only = hit_test(&doc, Point::new(30.0, 60.0), HitOptions { path_only: true, ..HitOptions::default() }).map(|hit| hit.kind); + observed.push((name, ring_alpha, hole_alpha, edge_alpha, ring, hole, edge, outline, path_only)); + } + + let expected = vec![ + ("visible black fill", 255, 0, 255, Some(HitKind::Fill), None, Some(HitKind::Stroke), None, None), + ("lower black fill under a top None fill", 255, 0, 255, Some(HitKind::Fill), None, Some(HitKind::Stroke), None, None), + ("only hidden non-None fill", 0, 0, 255, None, None, Some(HitKind::Stroke), None, None), + ("basic Fill None", 0, 0, 255, None, None, Some(HitKind::Stroke), None, None), + ("visible fill at zero opacity", 0, 0, 255, Some(HitKind::Fill), None, Some(HitKind::Stroke), None, None), + ]; + assert_eq!(observed, expected, "render and hit-test observations by Compound fill-stack case"); +} + +#[test] +fn hit_respects_open_stroke_caps_with_hidden_fill() { + use vectorcraft_doc::{LineCap, LineJoin}; + use vectorcraft_geom::{BezPath, PathData}; + + let mut observed = Vec::new(); + let mut expected = Vec::new(); + // Round and Square are legitimate controls before the Butt regression. + for (cap, endpoint_pixel, endpoint_hit) in [ + (LineCap::Round, [0, 0, 0, 255], Some(HitKind::Stroke)), + (LineCap::Square, [0, 0, 0, 255], Some(HitKind::Stroke)), + (LineCap::Butt, [255, 255, 255, 255], None), + ] { + for join in [LineJoin::Miter, LineJoin::Round] { + let mut hidden = fill(Paint::solid(Color::BLACK)); + hidden.visible = false; + for (name, fills) in [ + ("hidden painted fill", vec![hidden]), + ("absent fill", vec![]), + ("explicit Fill None", vec![fill(Paint::None)]), + ("visible fill on a zero-area line", vec![fill(Paint::solid(Color::BLACK))]), + ] { + let mut doc = Document::new(160.0, 96.0); + let layer = doc.layers[0].id; + let id = doc.alloc_id(); + let mut appearance = Appearance::default(); + appearance.items.extend(fills.into_iter().map(AppearanceItem::Fill)); + let mut stroke = StrokeLayer::new(Paint::solid(Color::BLACK), 10.0); + stroke.cap = cap; + stroke.join = join; + appearance.items.push(AppearanceItem::Stroke(stroke)); + let path = PathData::from_bezpath(&BezPath::from_svg("M24 48 L124 48").unwrap()); + doc.insert(Some(layer), usize::MAX, Node::path(id, path, appearance)).unwrap(); + let mut renderer = Renderer::new(); + renderer.threads = 0; + let image = renderer.render( + &doc, + 160, + 96, + Affine::IDENTITY, + &RenderOptions { background: Some([255, 255, 255, 255]), artboards: false, ..RenderOptions::default() }, + ); + let options = HitOptions { tol: 0.5, ..HitOptions::default() }; + let end = hit_test(&doc, Point::new(20.0, 48.0), options).map(|hit| hit.kind); + let body = hit_test(&doc, Point::new(60.0, 48.0), options).map(|hit| hit.kind); + assert_eq!(image.pixel(60, 48), [0, 0, 0, 255], "INPUT: {cap:?}/{join:?}/{name} stroke body must draw"); + assert_eq!(body, Some(HitKind::Stroke), "INPUT: {cap:?}/{join:?}/{name} stroke body must hit"); + observed.push((cap, join, name, image.pixel(20, 48), end, image.pixel(60, 48), body)); + expected.push((cap, join, name, endpoint_pixel, endpoint_hit, [0, 0, 0, 255], Some(HitKind::Stroke))); + } + } + } + assert_eq!(observed, expected, "visible stroke caps and hit testing must agree, including hidden-fill paths"); +} + +#[test] +fn hit_respects_hidden_fill_stroke_joins() { + use vectorcraft_doc::{LineCap, LineJoin}; + use vectorcraft_geom::{BezPath, PathData}; + + let mut observed = Vec::new(); + let mut expected = Vec::new(); + for (join, joint_painted, joint_hit) in + [(LineJoin::Round, true, Some(HitKind::Stroke)), (LineJoin::Miter, true, Some(HitKind::Stroke)), (LineJoin::Bevel, false, None)] + { + let mut doc = Document::new(160.0, 96.0); + let layer = doc.layers[0].id; + let id = doc.alloc_id(); + let mut hidden = fill(Paint::solid(Color::BLACK)); + hidden.visible = false; + let mut appearance = Appearance::default(); + appearance.items.push(AppearanceItem::Fill(hidden)); + let mut stroke = StrokeLayer::new(Paint::solid(Color::BLACK), 10.0); + stroke.cap = LineCap::Round; + stroke.join = join; + appearance.items.push(AppearanceItem::Stroke(stroke)); + let path = PathData::from_bezpath(&BezPath::from_svg("M32 64 L96 64 L96 24").unwrap()); + doc.insert(Some(layer), usize::MAX, Node::path(id, path, appearance)).unwrap(); + let mut renderer = Renderer::new(); + renderer.threads = 0; + let image = renderer.render( + &doc, + 160, + 96, + Affine::IDENTITY, + &RenderOptions { background: Some([255, 255, 255, 255]), artboards: false, ..RenderOptions::default() }, + ); + let options = HitOptions { tol: 0.5, ..HitOptions::default() }; + let joint = hit_test(&doc, Point::new(99.0, 67.0), options).map(|hit| hit.kind); + let body = hit_test(&doc, Point::new(60.0, 64.0), options).map(|hit| hit.kind); + assert_eq!(image.pixel(60, 64), [0, 0, 0, 255], "INPUT: {join:?} stroke body must draw"); + assert_eq!(body, Some(HitKind::Stroke), "INPUT: {join:?} stroke body must hit"); + // Round's corner pixel can be antialiased; only its visible paint is required. + observed.push((join, image.pixel(99, 67) != [255, 255, 255, 255], joint)); + expected.push((join, joint_painted, joint_hit)); + } + assert_eq!(observed, expected, "hidden-fill stroke joins must match actual CPU paint at the outer joint"); +} 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 aafdcac247..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] @@ -4197,6 +4324,165 @@ fn images_that_cant_be_decoded_are_mid_gray_boxes() { assert_eq!(paint(n.appearance.items[0].paint()), paint(&solid(Color::gray(0.5)))); } +/// A `w` × `h` RGB image whose pixels follow from `seed`, no two of its pixels gray. +fn seeded_png(seed: u32, (w, h): (u32, u32)) -> Vec { + let px = |x: u32, y: u32| { + let v = (x.wrapping_mul(73_856_093) ^ y.wrapping_mul(19_349_663) ^ seed.wrapping_mul(83_492_791)).to_le_bytes(); + image::Rgb([v[0], v[1] | 1, v[2] & 0xfe]) + }; + png_of(image::DynamicImage::ImageRgb8(image::RgbImage::from_fn(w, h, px))) +} + +/// A document placing `blobs` in turn on one layer, each `times` times: the first, the second and +/// so on, then the first again. Each blob is kept under `keys`' key at its index. +fn images_in_turn(blobs: &[ImageBlob], keys: &[&str], times: usize) -> Document { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + for (blob, key) in blobs.iter().zip(keys) { + doc.images.insert((*key).to_string(), blob.clone()); + } + for i in 0..times * blobs.len() { + let key = keys[i % blobs.len()].to_string(); + let xf = Affine::translate((f64::from(u32::try_from(i).unwrap()), 10.0)) * Affine::scale(2.0); + let im = ImageObject { key, width: 4, height: 4, xf, link: None, placement: Default::default(), pixels: None }; + let node = Node::new(doc.alloc_id(), NodeKind::Image(Box::new(im))); + doc.insert(Some(layer), usize::MAX, node).unwrap(); + } + doc +} + +/// `doc` written keeping the pixels of each image read (`last_only` false) or of the image read +/// last alone, and how many times an image's pixels were read. +fn export_reading(doc: &Document, last_only: bool) -> (AiEditingOutput, usize) { + writer::LAST_SAMPLES_ONLY.with(|l| l.set(last_only)); + writer::SAMPLE_READS.with(|n| n.set(0)); + let out = export_ai_editing(doc, &opts()); + writer::LAST_SAMPLES_ONLY.with(|l| l.set(false)); + (out.unwrap(), writer::SAMPLE_READS.with(std::cell::Cell::get)) +} + +/// `doc` written both ways ([`export_reading`]), the files and warnings compared whole, and the +/// reads of each way. +fn reads_for_the_same_file(doc: &Document) -> (usize, usize) { + let (kept, kept_reads) = export_reading(doc, false); + let (last, last_reads) = export_reading(doc, true); + assert!(kept.program == last.program, "the files differ"); + assert_eq!(kept.header, last.header); + assert_eq!(kept.warnings, last.warnings); + (kept_reads, last_reads) +} + +/// Two images placed one after the other 25 times each are each read once in a save, and the file +/// is the same as when only the image read last is kept. +#[test] +fn images_placed_in_turn_are_read_once_a_save() { + // GUARDS: each image was read again whenever the other was placed between its copies. + let blobs = [ImageBlob::png(seeded_png(1, (4, 4))), ImageBlob::png(seeded_png(2, (4, 4)))]; + let doc = images_in_turn(&blobs, &["a", "b"], 25); + assert_eq!(reads_for_the_same_file(&doc), (2, 50)); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(String::from_utf8_lossy(&out.program).matches("%AI5_BeginRaster").count(), 50); +} + +/// A document of one image placed many times reads it once, and one without images reads none. +#[test] +fn one_image_is_read_once_and_no_image_never() { + let doc = images_in_turn(&[ImageBlob::png(seeded_png(3, (4, 4)))], &["a"], 10); + assert_eq!(reads_for_the_same_file(&doc), (1, 1)); + assert_eq!(reads_for_the_same_file(&Document::new(200.0, 100.0)), (0, 0)); +} + +/// An image that can't be read, placed between copies of another, is read once too, and each copy +/// is still its gray outline with the same warning. +#[test] +fn an_image_that_cant_be_read_is_read_once_a_save() { + // GUARDS: an image that can't be read was read again whenever another image came between. + let blobs = [ImageBlob::png(b"not an image".to_vec()), ImageBlob::png(seeded_png(4, (4, 4)))]; + let doc = images_in_turn(&blobs, &["bad", "good"], 3); + assert_eq!(reads_for_the_same_file(&doc), (2, 6)); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(out.warnings, [writer::IMAGES]); + assert_eq!(String::from_utf8_lossy(&out.program).matches("%AI5_BeginRaster").count(), 3); +} + +/// The same data under two MIME types is two images: each is read once, apart from the other. +#[test] +fn the_same_data_of_another_type_is_read_apart() { + let png = ImageBlob::png(seeded_png(5, (4, 4))); + let other = ImageBlob { mime: "image/x-other".into(), ..png.clone() }; + assert!(Arc::ptr_eq(&png.bytes, &other.bytes)); + let doc = images_in_turn(&[png, other], &["png", "other"], 3); + assert_eq!(reads_for_the_same_file(&doc), (2, 6)); +} + +/// Past the limits on the samples kept (bytes and images), an image is kept beside them in place +/// of the one before it, and the others are read again where they come: what is kept stays within +/// both limits, and the file is the same. +#[test] +fn images_past_the_limits_are_read_again_and_written_the_same() { + // Images of 48, 75 and 108 bytes of samples, then two of 48: 123 bytes and two images fit. + let sizes = [(4, 4), (5, 5), (6, 6), (4, 4), (4, 4)]; + let blobs: Vec<_> = (0u32..).zip(sizes).map(|(i, s)| ImageBlob::png(seeded_png(10 + i, s))).collect(); + let doc = images_in_turn(&blobs, &["a", "b", "c", "d", "e"], 3); + for (limits, kept_most, reads) in [((130, 8), (123, 2), 2 + 3 * 3), ((10_000, 3), (48 + 75 + 108, 3), 3 + 2 * 3)] { + writer::SAMPLE_LIMITS.with(|l| l.set(limits)); + writer::SAMPLES_KEPT.with(|k| k.set((0, 0, false))); + let (kept_reads, last_reads) = reads_for_the_same_file(&doc); + let (bytes, images, beside) = writer::SAMPLES_KEPT.with(std::cell::Cell::get); + writer::SAMPLE_LIMITS.with(|l| l.set((256 << 20, 256))); + assert!(bytes <= limits.0 && images <= limits.1, "{limits:?}: kept {bytes} bytes of {images} images"); + assert_eq!((bytes, images, beside), (kept_most.0, kept_most.1, true), "{limits:?}"); + assert_eq!((kept_reads, last_reads), (reads, 15), "{limits:?}"); + } +} + +/// The time this thread has run, and how it was measured. +fn thread_time() -> (std::time::Duration, &'static str) { + if let Some(ns) = std::fs::read_to_string("/proc/thread-self/schedstat").ok().and_then(|s| s.split_whitespace().next()?.parse::().ok()) { + return (std::time::Duration::from_nanos(ns), "thread CPU time"); + } + static START: std::sync::OnceLock = std::sync::OnceLock::new(); + (START.get_or_init(std::time::Instant::now).elapsed(), "wall-clock time") +} + +/// The time to write two 2048 × 2048 images placed one after the other 25 times each, keeping the +/// pixels of each image read and of the image read last alone: the median of 7 runs of each, +/// alternating, with the files compared. Run with +/// `cargo test --release -p vectorcraft-eps --lib -- --ignored --nocapture images_placed_in_turn_are_written_quickly`. +#[test] +#[ignore = "timing"] +fn images_placed_in_turn_are_written_quickly() { + let blobs = [ImageBlob::png(seeded_png(1, (2048, 2048))), ImageBlob::png(seeded_png(2, (2048, 2048)))]; + let doc = images_in_turn(&blobs, &["a", "b"], 25); + let mut times = [vec![], vec![]]; + let mut files: [Option>; 2] = [None, None]; + let mut reads = [0, 0]; + let mut how = ""; + for _ in 0..7 { + for (k, last_only) in [false, true].into_iter().enumerate() { + let (start, h) = thread_time(); + let (out, n) = export_reading(&doc, last_only); + times[k].push(thread_time().0.saturating_sub(start)); + how = h; + reads[k] = n; + files[k].get_or_insert(out.program); + } + } + assert!(files[0] == files[1], "the files differ"); + assert_eq!(reads, [2, 50]); + for t in &mut times { + t.sort(); + } + let ms = |d: std::time::Duration| d.as_secs_f64() * 1000.0; + println!("50 placements of two 2048 x 2048 images, median of 7 runs ({how}):"); + println!("| pixels kept | images read | median (ms) | runs (ms) |"); + println!("|---|---:|---:|---|"); + for (k, label) in ["each image read", "the image read last"].into_iter().enumerate() { + let runs: Vec = times[k].iter().map(|d| format!("{:.0}", ms(*d))).collect(); + println!("| {label} | {} | {:.0} | {} |", reads[k], ms(times[k][3]), runs.join(", ")); + } +} + #[test] fn sixteen_bit_images_are_written_at_eight_bits() { let mut doc = Document::new(200.0, 100.0); @@ -7181,6 +7467,166 @@ fn art_styles_are_written_in_their_forms() { assert!(!two.contains("%AI9_BeginArtStyleList"), "{two}"); } +/// A document with `k` of each object a save checks a style on, on rows 20 pt apart: objects linked +/// to a new document's graphic style and to one of the document's own, objects with the same drop +/// shadow, two objects with different gradients under a drop shadow on the same outline, and paths +/// with a Calligraphic brush and a drop shadow. +fn checked_styles_document(k: usize) -> Document { + let mut doc = Document::new(400.0, 20.0 * k as f64 + 20.0); + vectorcraft_brush::store(&mut doc, &brush_library()); + let lit_ap = Appearance { effects: vec![drop_shadow()], ..Appearance::basic(solid(Color::rgb(0.2, 0.5, 0.9)), solid(Color::BLACK), 1.0) }; + let mut lit = vectorcraft_doc::GraphicStyle::new("Lit", lit_ap); + lit.id = 40; + doc.graphic_styles.push(lit); + let ramp = |c: Color| { + let stops = vec![GradientStop::new(0.0, Color::WHITE), GradientStop::new(1.0, c)]; + Paint::Gradient(Box::new(GradientPaint::new(Gradient { kind: GradientKind::Linear, stops, ..Gradient::default() }))) + }; + for i in 0..k { + let y = 10.0 + 20.0 * i as f64; + for (x, name) in [(10.0, "Sunshine"), (60.0, "Lit")] { + let g = doc.graphic_style(name).unwrap().clone(); + let ap = g.appearance_on(&Node::group(vectorcraft_doc::NodeId(0), vec![])).into_owned(); + let mut n = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(x, y, x + 40.0, y + 15.0)), ap); + n.extras_mut().graphic_style = Some(g.id); + put(&mut doc, n); + } + let n = styled_rect(&mut doc, "Shadowed", Rect::new(110.0, y, 150.0, y + 15.0), solid(Color::BLACK), Paint::None, vec![drop_shadow()]); + put(&mut doc, n); + for c in [Color::BLACK, Color::rgb(0.9, 0.2, 0.1)] { + let n = styled_rect(&mut doc, "Graded", Rect::new(160.0, y, 200.0, y + 15.0), ramp(c), Paint::None, vec![drop_shadow()]); + put(&mut doc, n); + } + let stroke = Appearance::basic(Paint::None, solid(Color::rgb(1.0, 0.0, 0.0)), 2.0); + let mut line = Node::path(doc.alloc_id(), shapes::line((210.0, y).into(), (380.0, y + 10.0).into()), stroke); + line.appearance.stroke_mut().unwrap().brush = Some("Nib".into()); + line.appearance.effects = vec![drop_shadow()]; + put(&mut doc, line); + } + doc +} + +/// A save parses each style text once, however many objects it checks with it: the panel's styles, +/// objects linked to them, objects with the same style of their own and brushed paths. Each object +/// is still checked: every linked object keeps its link, each graded object reads back with its own +/// gradient, and each brushed path with its brush. +#[test] +fn a_save_parses_each_style_text_once() { + let parses = |doc: &Document| { + crate::import::ART_STYLE_PARSES.set(0); + let out = export_ai_editing(doc, &opts()).unwrap(); + (crate::import::ART_STYLE_PARSES.get(), String::from_utf8(out.program).unwrap().replace("\r\n", "\n")) + }; + let (one, _) = parses(&checked_styles_document(1)); + let doc = checked_styles_document(4); + let (four, p) = parses(&doc); + assert!(one > 0); + assert_eq!(four, one, "parses with one of each object and with four"); + for linked in ["1 (Sunshine) XW\n", "1 (Lit) XW\n"] { + assert_eq!(p.matches(linked).count(), 4, "{linked}"); + } + let back = read_back(&doc); + let kids = back.layers[0].children().unwrap(); + let paints: Vec<&Paint> = + kids.iter().filter(|n| n.name.as_deref() == Some("Graded")).filter_map(|n| n.appearance.fill().map(|f| &f.paint)).collect(); + let graded: Vec<&Paint> = doc.layers[0] + .children() + .unwrap() + .iter() + .filter(|n| n.name.as_deref() == Some("Graded")) + .map(|n| &n.appearance.fill().unwrap().paint) + .collect(); + assert_eq!(paints.len(), 8); + for (got, want) in paints.iter().zip(&graded) { + let (Paint::Gradient(got), Paint::Gradient(want)) = (got, want) else { panic!("a gradient fill: {got:?}") }; + assert_eq!(got.gradient.stops, want.gradient.stops); + } + let brushed: Vec<&Arc> = kids.iter().filter(|n| n.appearance.stroke().and_then(|s| s.brush.as_deref()) == Some("Nib")).collect(); + assert_eq!(brushed.len(), 4); + assert!(brushed.iter().all(|n| n.appearance.effects.len() == 1 && matches!(n.kind, NodeKind::Path { .. }))); +} + +/// A save that keeps each style text's parse writes the same program, header, warnings and private +/// data as one that parses the text again at every check. +#[test] +fn a_save_writes_the_same_with_each_style_text_parsed_once() { + let save = |doc: &Document, reparse: bool| { + writer::REPARSE.set(reparse); + let out = export_ai_editing(doc, &opts()).unwrap(); + let private = private_data(doc, &opts()).unwrap(); + writer::REPARSE.set(false); + (out.program, out.header, out.warnings, private.0.data, private.1) + }; + for doc in [styles_document(), checked_styles_document(4), brushes_document()] { + let (once, again) = (save(&doc, false), save(&doc, true)); + assert!(once == again, "{}", String::from_utf8_lossy(&once.0)); + } +} + +/// The CPU time of saving a document with 40 graphic styles, 20,000 rectangles linked to them in +/// turn and 5,000 paths with an Outer Glow of their own in 20 settings, with each style text's parse +/// kept and with the text parsed again at every check: the median of 7 runs of each, alternating. +/// Run with `cargo test -p vectorcraft-eps --lib -- --ignored --nocapture style_parse_time`. +#[test] +#[ignore = "timing; run by hand"] +fn style_parse_time() { + let mut doc = Document::new(2000.0, 2000.0); + let mut ids = vec![]; + for i in 0..40u32 { + let shade = i as f32 / 40.0; + let mut ap = Appearance::basic(solid(Color::rgb(shade, 0.4, 1.0 - shade)), solid(Color::BLACK), 1.0 + f64::from(i % 4)); + let round = fx("stylize.roundCorners", serde_json::json!({"radius": 2.0 + f64::from(i % 5)})); + ap.effects = vec![fx("stylize.dropShadow", serde_json::json!({"x": f64::from(i % 7), "y": 4.0})), round]; + let mut g = vectorcraft_doc::GraphicStyle::new(format!("Style {i}"), ap); + g.id = 100 + i; + ids.push(g.id); + doc.graphic_styles.push(g); + } + for i in 0..20_000usize { + let g = doc.graphic_style_by_id(ids[i % ids.len()]).unwrap().clone(); + let ap = g.appearance_on(&Node::group(vectorcraft_doc::NodeId(0), vec![])).into_owned(); + let (x, y) = ((i % 200) as f64 * 10.0, (i / 200) as f64 * 10.0); + let mut n = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(x, y, x + 8.0, y + 8.0)), ap); + n.extras_mut().graphic_style = Some(g.id); + put(&mut doc, n); + } + for i in 0..5_000usize { + let glow = fx("stylize.outerGlow", serde_json::json!({"blur": 1.0 + (i % 20) as f64})); + let (x, y) = ((i % 100) as f64 * 20.0, 1000.0 + (i / 100) as f64 * 20.0); + let n = styled_rect(&mut doc, "Glow", Rect::new(x, y, x + 15.0, y + 15.0), solid(Color::BLACK), Paint::None, vec![glow]); + put(&mut doc, n); + } + // The CPU time this thread has run, in nanoseconds: Linux's scheduler statistics, else the clock. + let start = std::time::Instant::now(); + let cpu = || { + std::fs::read_to_string("/proc/thread-self/schedstat") + .ok() + .and_then(|s| s.split_whitespace().next().and_then(|n| n.parse::().ok())) + .unwrap_or_else(|| u64::try_from(start.elapsed().as_nanos()).unwrap_or(u64::MAX)) + }; + let mut times: [Vec; 2] = [vec![], vec![]]; + let mut parses = [0, 0]; + let mut outputs: [Vec; 2] = [vec![], vec![]]; + for _ in 0..7 { + for (k, reparse) in [(0, true), (1, false)] { + writer::REPARSE.set(reparse); + crate::import::ART_STYLE_PARSES.set(0); + let t = cpu(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + times[k].push(cpu() - t); + parses[k] = crate::import::ART_STYLE_PARSES.get(); + outputs[k] = out.program; + } + } + writer::REPARSE.set(false); + assert!(outputs[0] == outputs[1]); + for (k, label) in [(0, "parsed at every check"), (1, "parsed once")] { + times[k].sort_unstable(); + let ms: Vec = times[k].iter().map(|t| format!("{:.1}", *t as f64 / 1e6)).collect(); + println!("{label}: median {:.1} ms CPU, {} parses, runs {}", times[k][3] as f64 / 1e6, parses[k], ms.join(" ")); + } +} + /// Objects whose appearance the reader wouldn't read with their style are written as their /// drawn look, with the warnings they were written with before; graphic styles it wouldn't read /// are left out with a warning; and a document without effects or styles of its own has no art @@ -9758,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]), }), }, @@ -9864,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); @@ -10193,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![ @@ -10255,6 +10719,40 @@ fn brush_art_of_a_straight_line_comes_back_as_the_line() { } } +/// A Scatter brush's art is written turned over into its section (y up), so the side that is down the +/// page in the brush's copies is up in the section: a triangle with its point down comes out with +/// its point above its base, and comes back with its point down. +#[test] +fn a_scatter_brushs_art_is_written_turned_over() { + use vectorcraft_brush::{Brush, BrushKind, Scatter}; + use vectorcraft_geom::{Point, SubPath}; + let point_down = PathData { subpaths: vec![SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(40.0, 0.0), Point::new(20.0, 10.0)], true)] }; + let art = Node::path(vectorcraft_doc::NodeId(1), point_down, Appearance::basic(black_fill(), Paint::None, 0.0)); + let lib = vec![Brush { name: "Wedge".into(), kind: BrushKind::Scatter(Scatter { art, ..Scatter::default() }) }]; + let mut doc = Document::new(300.0, 200.0); + vectorcraft_brush::store(&mut doc, &lib); + let text = program(&doc); + let start = text.find("%AI8_BeginBrushPattern").unwrap(); + let end = start + text[start..].find("%AI8_EndBrushPattern").unwrap(); + // The points of the frame and the triangle: the triangle's point is the one between the + // frame's left and right edges. + let points: Vec<(f64, f64)> = text[start..end] + .lines() + .filter_map(|l| l.strip_suffix(" m").or_else(|| l.strip_suffix(" L"))) + .filter_map(|l| { + let mut n = l.split_whitespace().map(|v| v.parse::().ok()); + Some((n.next()??, n.next()??)) + }) + .collect(); + let (left, right) = points.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(l, r), p| (l.min(p.0), r.max(p.0))); + let bottom = points.iter().map(|p| p.1).fold(f64::INFINITY, f64::min); + let tip: Vec = points.iter().filter(|p| p.0 > left + 1e-3 && p.0 < right - 1e-3).map(|p| p.1).collect(); + assert!(!tip.is_empty() && tip.iter().all(|y| (y - bottom - 10.0).abs() < 1e-3), "the point is 10 above the base in the section: {points:?}"); + let back = vectorcraft_brush::library(&read_back(&doc)); + let (BrushKind::Scatter(got), BrushKind::Scatter(want)) = (&back[0].kind, &lib[0].kind) else { panic!("{back:?}") }; + assert!(same_tree(&art_tree(&got.art), &art_tree(&want.art)), "{:#?}", got.art); +} + /// Brush art of a path with several subpaths is written as a compound path, which the reader reads as /// a compound path of one path for each subpath, and is weighed as the reader weighs that against the /// art it copies into one file's brushes: of two Art brushes whose art is a path of 30,000 squares, @@ -11041,6 +11539,192 @@ fn variable_font_instances_name_their_design_space() { ); } +/// Style 12 pt black in family `family` and style `style`, with the Variable Font settings `axes`. +fn font_style(family: &str, style: &str, axes: &[(&str, f64)]) -> vectorcraft_doc::CharStyle { + vectorcraft_doc::CharStyle { + font_family: family.into(), + font_style: style.into(), + font_axes: axes.iter().map(|(t, v)| (t.to_string(), *v)).collect(), + ..style_of(12.0) + } +} + +/// A document of `k` rows 30 pt apart, each with point type in three runs (Source Sans 3 Regular +/// and Bold, and the variable test font's Bold at a weight of 650), point type in four (Inter +/// Medium, the variable test font's Bold at 500 and at a weight that differs from 500 by less than +/// the font record's precision, and a family that isn't installed), and area type threaded through +/// two frames in Bold and the variable test font's Regular. +fn fonted_document(k: usize) -> Document { + use vectorcraft_doc::{TextKind, TextObject, TextRun}; + use vectorcraft_geom::Point; + use vectorcraft_text::test_fonts::{VARIABLE_FAMILY, variable_font}; + vectorcraft_text::FontDb::global().add_font(variable_font().unwrap()); + let (regular, bold) = (style_of(12.0), font_style("Source Sans 3", "Bold", &[])); + let mut doc = Document::new(400.0, 30.0 * k as f64 + 30.0); + let layer = doc.layers[0].id; + for i in 0..k { + let y = 20.0 + 30.0 * i as f64; + let mut three = TextObject::point(Point::new(10.0, y), "", regular.clone()); + three.runs = vec![ + TextRun::new("One ", regular.clone()), + TextRun::new("two ", bold.clone()), + TextRun::new("three", font_style(VARIABLE_FAMILY, "Bold", &[("wght", 650.0)])), + ]; + let mut four = TextObject::point(Point::new(100.0, y), "", regular.clone()); + four.runs = vec![ + TextRun::new("four ", font_style("Inter", "Medium", &[])), + TextRun::new("five ", font_style(VARIABLE_FAMILY, "Bold", &[("wght", 500.0)])), + TextRun::new("six ", font_style(VARIABLE_FAMILY, "Bold", &[("wght", 500.000_001)])), + TextRun::new("seven", font_style("No Such Family", "Bold", &[])), + ]; + let mut first = TextObject::point(Point::ZERO, "", bold.clone()); + first.runs = vec![TextRun::new("eight nine ", bold.clone()), TextRun::new("ten", font_style(VARIABLE_FAMILY, "Regular", &[]))]; + first.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(250.0, y - 10.0, 315.0, y + 10.0)) }; + first.xf = Affine::IDENTITY; + let mut second = first.clone(); + second.runs = vec![TextRun::new("", bold.clone())]; + second.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(325.0, y - 10.0, 390.0, y + 10.0)) }; + let nodes = [text_node(&mut doc, three), text_node(&mut doc, four), text_node(&mut doc, first), text_node(&mut doc, second)]; + doc.text_threads.push(vec![nodes[2].id, nodes[3].id]); + for n in nodes { + doc.insert(Some(layer), usize::MAX, n).unwrap(); + } + } + doc +} + +/// A save resolves the font of each style once, however many runs are set in it: as many fonts are +/// resolved (font records and checks that a font comes back) for one row of type as for four. Two +/// weights of a variable font that the font record writes as one number are one font written. +#[test] +fn a_save_resolves_each_font_once() { + // How many fonts a save of `doc` resolves, in a save during which the font database didn't change. + let resolves = |doc: &Document| { + let db = vectorcraft_text::FontDb::global(); + for _ in 0..20 { + let before = db.generation(); + writer::FONT_RESOLVES.set(0); + export_ai_editing(doc, &opts()).unwrap(); + if db.generation() == before { + return writer::FONT_RESOLVES.get(); + } + } + panic!("the font database changed during every save"); + }; + let one = resolves(&fonted_document(1)); + let doc = fonted_document(4); + let four = resolves(&doc); + assert!(one > 0); + assert_eq!(four, one, "fonts resolved with one row of type and with four"); + let td = text_document(&program(&doc)); + // 650 × 65536 and 500 × 65536. + assert_eq!(td.matches("VaritestSans-Bold) /2 1 /4 [ 42598400 ]").count(), 1, "{td}"); + assert_eq!(td.matches("VaritestSans-Bold) /2 1 /4 [ 32768000 ]").count(), 1, "{td}"); + assert_eq!(td.matches("/CoolTypeFont").count(), 8, "seven fonts and the hidden characters' font: {td}"); +} + +/// A save that resolves each style's font once writes the same program, header, warnings and private +/// data as one that resolves the font of every run again: with type in many fonts, threaded type, +/// type in envelopes, and type taken out again when an envelope is written as its art. +#[test] +fn a_save_writes_the_same_with_each_font_resolved_once() { + use vectorcraft_doc::live::EnvelopeKind; + let save = |doc: &Document, each_run: bool| { + writer::RESOLVE_EACH_RUN.set(each_run); + let out = export_ai_editing(doc, &opts()).unwrap(); + let private = private_data(doc, &opts()).unwrap(); + writer::RESOLVE_EACH_RUN.set(false); + (out.program, out.header, out.warnings, private.0.data, private.1) + }; + let mut docs = vec![sample(), typed(), fonted_document(3)]; + for (_, kind) in live_envelope_kinds() { + for editing in [false, true] { + let mut doc = Document::new(200.0, 100.0); + let envelope = typed_envelope_node(&mut doc, kind.clone(), editing); + docs.push(alone(envelope)); + } + } + for doc in &docs { + let (once, again) = (save(doc, false), save(doc, true)); + assert!(once == again, "{}", String::from_utf8_lossy(&once.0)); + } + // An envelope of type one object short of room: it is written as its art, and its story and fonts + // are taken out again. + let kind = EnvelopeKind::Mesh { rows: 2, cols: 3, points: envelope_points(2, 3), handles: vec![] }; + let mut doc = Document::new(200.0, 100.0); + let envelope = typed_envelope_node(&mut doc, kind, false); + let doc = alone(envelope); + let read = crate::import::objects_read(&export_ai_editing(&doc, &opts()).unwrap().program).unwrap(); + let within = |each_run: bool| { + writer::RESOLVE_EACH_RUN.set(each_run); + let out = export_within(&doc, &opts(), read - 1).unwrap(); + writer::RESOLVE_EACH_RUN.set(false); + (out.program, out.warnings) + }; + let (once, again) = (within(false), within(true)); + assert!(once.1.iter().any(|w| w == writer::OBJECT_LIMIT), "{:?}", once.1); + assert!(once == again, "{}", String::from_utf8_lossy(&once.0)); +} + +/// The CPU time of saving a document of 10,000 point type objects, each in three runs drawn in turn +/// from four fonts (Source Sans 3 Regular and Bold, Inter Medium, and the variable test font's Bold +/// at a weight of 650), with each style's font resolved once and with the font of every run +/// resolved again: the median of 7 runs of each, alternating. +/// Run with `cargo test -p vectorcraft-eps --lib -- --ignored --nocapture font_resolve_time`. +#[test] +#[ignore = "timing; run by hand"] +fn font_resolve_time() { + use vectorcraft_doc::{TextObject, TextRun}; + use vectorcraft_text::test_fonts::{VARIABLE_FAMILY, variable_font}; + vectorcraft_text::FontDb::global().add_font(variable_font().unwrap()); + let fonts = [ + style_of(12.0), + font_style("Source Sans 3", "Bold", &[]), + font_style("Inter", "Medium", &[]), + font_style(VARIABLE_FAMILY, "Bold", &[("wght", 650.0)]), + ]; + let mut doc = Document::new(2000.0, 2000.0); + let layer = doc.layers[0].id; + for i in 0..10_000usize { + let (x, y) = ((i % 100) as f64 * 20.0, (i / 100) as f64 * 20.0 + 10.0); + let mut t = TextObject::point(vectorcraft_geom::Point::new(x, y), "", fonts[0].clone()); + t.runs = (0..3).map(|r| TextRun::new(["ab ", "cd ", "ef"][r], fonts[(i + r) % fonts.len()].clone())).collect(); + let n = text_node(&mut doc, t); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + } + // The CPU time this thread has run, in nanoseconds: Linux's scheduler statistics, else the clock. + let start = std::time::Instant::now(); + let cpu = || { + std::fs::read_to_string("/proc/thread-self/schedstat") + .ok() + .and_then(|s| s.split_whitespace().next().and_then(|n| n.parse::().ok())) + .unwrap_or_else(|| u64::try_from(start.elapsed().as_nanos()).unwrap_or(u64::MAX)) + }; + // A first save loads the faces the document names. + export_ai_editing(&doc, &opts()).unwrap(); + let mut times: [Vec; 2] = [vec![], vec![]]; + let mut resolves = [0, 0]; + let mut outputs: [Vec; 2] = [vec![], vec![]]; + for _ in 0..7 { + for (k, each_run) in [(0, true), (1, false)] { + writer::RESOLVE_EACH_RUN.set(each_run); + writer::FONT_RESOLVES.set(0); + let t = cpu(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + times[k].push(cpu() - t); + resolves[k] = writer::FONT_RESOLVES.get(); + outputs[k] = out.program; + } + } + writer::RESOLVE_EACH_RUN.set(false); + assert!(outputs[0] == outputs[1]); + for (k, label) in [(0, "resolved for every run"), (1, "resolved once")] { + times[k].sort_unstable(); + let ms: Vec = times[k].iter().map(|t| format!("{:.1}", *t as f64 / 1e6)).collect(); + println!("{label}: median {:.1} ms CPU, {} fonts resolved, runs {}", times[k][3] as f64 / 1e6, resolves[k], ms.join(" ")); + } +} + fn style_of(size: f64) -> vectorcraft_doc::CharStyle { style(size, Color::BLACK) } diff --git a/crates/eps/src/ai_editing/writer.rs b/crates/eps/src/ai_editing/writer.rs index f268bcbaf6..41254840cb 100644 --- a/crates/eps/src/ai_editing/writer.rs +++ b/crates/eps/src/ai_editing/writer.rs @@ -37,20 +37,21 @@ pub(super) use envelopes::ENVELOPES; pub(super) use meshes::MESHES; pub(super) use styles::{LARGE_CANVAS_STYLES, style_links, styled_definitions, styled_objects}; #[cfg(test)] -pub(super) use styles::{PANEL_EMPTY, PANEL_STYLES, STYLE_LINKS, WARPED_IMAGES, same_appearance}; +pub(super) use styles::{PANEL_EMPTY, PANEL_STYLES, REPARSE, STYLE_LINKS, WARPED_IMAGES, same_appearance}; pub(super) use texts::wraps_held; pub(super) use images::PAYLOAD; #[cfg(test)] -pub(super) use images::{IMAGE_DEPTH, IMAGES, LINKS_EMBEDDED}; +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}; #[cfg(test)] -pub(super) use texts::TYPE_ATTRIBUTES; +pub(super) use texts::{FONT_RESOLVES, RESOLVE_EACH_RUN, TYPE_ATTRIBUTES}; #[cfg(test)] pub(super) use variables::{ACTIVE, BINDINGS, LIMITS, VALUES}; @@ -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. @@ -320,9 +321,9 @@ pub(super) struct Writer<'a> { /// How many more envelopes and images with a Warp may be written live: as many as the reader /// checks in one file ([`crate::import::ENVELOPE_CHECKS`]), which it spends on both. checks_left: usize, - /// The image read last and its pixels ([`images::Samples::of`], `None` when they can't be - /// read): the pieces of a warped image, which follow one another, read them once. - last_samples: Option<(vectorcraft_doc::ImageBlob, Option)>, + /// The images read so far and their pixels: an image placed again, and each piece of a warped + /// image, is read once. + read_samples: images::SampleCache, /// The images written whole so far, by the address of their data (which each entry keeps), each /// with the index of its samples in [`Self::payloads`]. whole_images: HashMap>, usize)>, @@ -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, @@ -422,7 +423,7 @@ impl<'a> Writer<'a> { definition_links: 0, definition_symbol_nodes: 0, max_objects: crate::import::MAX_EDITING_OBJECTS, - last_samples: None, + read_samples: images::SampleCache::default(), whole_images: HashMap::new(), shown: vec![], windowed: None, @@ -1604,7 +1605,7 @@ impl<'a> Writer<'a> { let placed = self.texts.thread(doc, thread, n.id, self.canvas, &|id| !cut_to_clipping_object(doc, id), &self.wraps_held); placed.map(|p| (p, self.texts.take_lost())) } else { - self.texts.add(t, self.canvas).map(|story| ((story, 0), texts::loses(t))) + self.texts.add(t, self.canvas).map(|story| ((story, 0), self.texts.loses(t))) }; let Some(((story, frame), lost)) = placed else { // The text document can't hold it: the outlines count their own objects. diff --git a/crates/eps/src/ai_editing/writer/brushes.rs b/crates/eps/src/ai_editing/writer/brushes.rs index 986d60ef9c..ac7ca48ac8 100644 --- a/crates/eps/src/ai_editing/writer/brushes.rs +++ b/crates/eps/src/ai_editing/writer/brushes.rs @@ -401,11 +401,12 @@ impl Writer<'_> { fn brush_out(&mut self, b: &Brush) -> Option { let plugin = crate::import::brush_plugin_name(&b.kind); let section = format!("Brush Art {}", self.brush_set.sections + 1); - // The art as the reader reads it: a section is read with y down, and an Art brush's art is - // turned over after that (its section's y up is the right of the path). + // The art as the reader reads it: a section is read with y down, and a Scatter or Art + // brush's art is turned over after that (its section's y up is down the page in each + // Scatter copy and the right of the path in Art). let (params, art) = match &b.kind { BrushKind::Calligraphic(c) => (calligraphic_params(c), None), - BrushKind::Scatter(s) => (scatter_params(s, §ion)?, Some((s.art.clone(), Affine::FLIP_Y))), + BrushKind::Scatter(s) => (scatter_params(s, §ion)?, Some((s.art.clone(), Affine::IDENTITY))), BrushKind::Art(a) => (art_params(a, §ion)?, Some((a.art.clone(), Affine::IDENTITY))), BrushKind::Pattern(_) | BrushKind::Bristle(_) => return None, }; @@ -565,14 +566,14 @@ impl Writer<'_> { /// Does the reader read the brushed strokes of style text `text` with their brushes on them? pub(super) fn brushed_style_reads(&mut self, text: &str) -> bool { self.brush_set(); - let section = super::styles::known_style("x", text); + let Some(parsed) = self.styles.parsed.get(text) else { return false }; let written = &self.brush_set.written; let read = self.brush_set.read.get_or_insert_with(|| { let brushes: Vec<(&str, &str, &str, Option<&Node>)> = written.iter().map(|b| (b.plugin, b.brush.name.as_str(), b.params.as_str(), b.art.as_ref())).collect(); crate::import::BrushesRead::new(&brushes) }); - read.style_reads(section.as_bytes(), "x") + read.style_reads(parsed) } /// The brushes' art in a non-printing block, then the brush manager's order and the brushes in diff --git a/crates/eps/src/ai_editing/writer/images.rs b/crates/eps/src/ai_editing/writer/images.rs index 3813deccf9..408827663f 100644 --- a/crates/eps/src/ai_editing/writer/images.rs +++ b/crates/eps/src/ai_editing/writer/images.rs @@ -1,6 +1,9 @@ //! Images: embedded ones as a raster with its samples, linked ones as a placed file with a preview //! (see [`crate::ai_editing`] for the form). +#[cfg(test)] +use std::cell::Cell; +use std::collections::HashMap; use std::fmt::Write; use std::sync::Arc; @@ -30,6 +33,87 @@ pub(super) const SAMPLES_LINE: &str = "XI\u{1}"; /// An image's pixels as the data holds them, and whether it had 16 bits a channel ([`Samples::of`]). pub(super) type Read = Arc<(Samples, bool)>; +/// The most bytes of samples a save keeps read ([`SampleCache`]): color and alpha together. +const KEPT_SAMPLE_BYTES: usize = 256 << 20; +/// The most images whose samples a save keeps read ([`SampleCache`]), those that can't be read +/// included. +const KEPT_IMAGES: usize = 256; + +#[cfg(test)] +thread_local! { + /// How many times [`Samples::of`] has read an image on this thread. + pub(in crate::ai_editing) static SAMPLE_READS: Cell = const { Cell::new(0) }; + /// Whether [`Writer::samples`] keeps only the image read last on this thread, to compare its + /// file with the one [`SampleCache`] gives. + pub(in crate::ai_editing) static LAST_SAMPLES_ONLY: Cell = const { Cell::new(false) }; + /// The bytes of samples and the images [`SampleCache`] keeps at most on this thread. + pub(in crate::ai_editing) static SAMPLE_LIMITS: Cell<(usize, usize)> = const { Cell::new((KEPT_SAMPLE_BYTES, KEPT_IMAGES)) }; + /// The most bytes of samples and images a [`SampleCache`] kept on this thread, and whether one + /// held an image beside them. + pub(in crate::ai_editing) static SAMPLES_KEPT: Cell<(usize, usize, bool)> = const { Cell::new((0, 0, false)) }; +} + +/// The bytes of samples and the images [`SampleCache`] keeps at most. +#[cfg(not(test))] +const fn sample_limits() -> (usize, usize) { + (KEPT_SAMPLE_BYTES, KEPT_IMAGES) +} + +#[cfg(test)] +fn sample_limits() -> (usize, usize) { + SAMPLE_LIMITS.with(Cell::get) +} + +/// The images read during a save and their pixels ([`Samples::of`], `None` when they can't be +/// read), so that an image placed again is read once: up to [`KEPT_IMAGES`] images and +/// [`KEPT_SAMPLE_BYTES`] of samples, and beside them the image read last that they have no room +/// for. An image is known by the address of its data and its MIME type; each entry keeps the +/// image, so no other data takes that address while the entry is kept. +#[derive(Default)] +pub(super) struct SampleCache { + /// By the address of the image's data, each image with that data and its pixels. + kept: HashMap)>>, + /// How many images `kept` holds. + images: usize, + /// The bytes of samples `kept` holds. + bytes: usize, + /// The image read last that `kept` had no room for, and its pixels. + last: Option<(ImageBlob, Option)>, +} + +/// Whether `a` is the image `b`: the same data and MIME type. +fn same_image(a: &ImageBlob, b: &ImageBlob) -> bool { + Arc::ptr_eq(&a.bytes, &b.bytes) && a.mime == b.mime +} + +impl SampleCache { + /// The pixels kept for `blob`, when it was read. + fn get(&self, blob: &ImageBlob) -> Option> { + let kept = self.kept.get(&(Arc::as_ptr(&blob.bytes) as usize)).and_then(|v| v.iter().find(|(b, _)| same_image(b, blob))); + kept.or(self.last.as_ref().filter(|(b, _)| same_image(b, blob))).map(|(_, read)| read.clone()) + } + + /// Keep `read`, the pixels of `blob`: with the others while both limits allow, else beside them + /// in place of the image read last. + fn keep(&mut self, blob: &ImageBlob, read: Option) { + let size = read.as_deref().map_or(0, |(s, _)| s.color.len().saturating_add(s.alpha.as_ref().map_or(0, Vec::len))); + let (most_bytes, most_images) = sample_limits(); + match self.bytes.checked_add(size).filter(|b| *b <= most_bytes) { + Some(bytes) if self.images < most_images => { + self.bytes = bytes; + self.images += 1; + self.kept.entry(Arc::as_ptr(&blob.bytes) as usize).or_default().push((blob.clone(), read)); + } + _ => self.last = Some((blob.clone(), read)), + } + #[cfg(test)] + SAMPLES_KEPT.with(|k| { + let (b, n, last) = k.get(); + k.set((b.max(self.bytes), n.max(self.images), last || self.last.is_some())); + }); + } +} + /// A copy of an image written as the part of it that its regions show ([`Writer::image`]). pub(super) struct Windowed { /// Where its raster is in the body. @@ -61,6 +145,8 @@ impl Samples { /// or RGB samples, with an alpha channel when they need one. `None` when they can't be decoded or are more than /// [`MAX_PIXELS`]; the flag is set when the image had 16 bits a channel. fn of(blob: &ImageBlob) -> Option<(Samples, bool)> { + #[cfg(test)] + SAMPLE_READS.with(|n| n.set(n.get() + 1)); // The header's size is checked before the inks are decoded. if blob.is_cmyk() && blob.header_size().is_some_and(|(w, h)| u64::from(w) * u64::from(h) <= MAX_PIXELS) @@ -301,17 +387,26 @@ impl Writer<'_> { ); } - /// The pixels of `blob` ([`Samples::of`]), read once for images that follow one another with - /// the same data. + /// The pixels of `blob` ([`Samples::of`]), read once in a save for each image the + /// [`SampleCache`] has room for. fn samples(&mut self, blob: &ImageBlob) -> Option { - if let Some((last, read)) = &self.last_samples - && Arc::ptr_eq(&last.bytes, &blob.bytes) - && last.mime == blob.mime - { - return read.clone(); + #[cfg(test)] + if LAST_SAMPLES_ONLY.with(Cell::get) { + if let Some((last, read)) = &self.read_samples.last + && Arc::ptr_eq(&last.bytes, &blob.bytes) + && last.mime == blob.mime + { + return read.clone(); + } + let read = Samples::of(blob).map(Arc::new); + self.read_samples.last = Some((blob.clone(), read.clone())); + return read; + } + if let Some(read) = self.read_samples.get(blob) { + return read; } let read = Samples::of(blob).map(Arc::new); - self.last_samples = Some((blob.clone(), read.clone())); + self.read_samples.keep(blob, read.clone()); read } 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/ai_editing/writer/styles.rs b/crates/eps/src/ai_editing/writer/styles.rs index 50aa4df931..df153c236e 100644 --- a/crates/eps/src/ai_editing/writer/styles.rs +++ b/crates/eps/src/ai_editing/writer/styles.rs @@ -2,9 +2,10 @@ //! object itself on `%_` lines and `1 (style) XW`; the styles they name and the Graphic Styles //! panel's styles in `%AI9_BeginArtStyles`, and the panel's order in `%AI9_BeginArtStyleList` (see //! [`crate::ai_editing`] for the form). Each style is read back before it is written -//! ([`crate::import::read_art_style`]: the `.ai` reader's style parser and its reading of a graphic +//! ([`crate::import::read_parsed_style`]: the `.ai` reader's style parser and its reading of a graphic //! style, with the object's own gradient): one that reads back differently is not written, and the -//! object is written as its drawn look alone. +//! object is written as its drawn look alone. Style texts are kept parsed for the save, up to a +//! limit ([`Parsed`]). use std::collections::{HashMap, HashSet}; use std::fmt::Write; @@ -126,7 +127,7 @@ fn candidate(n: &Node) -> bool { /// Is `n` an image, embedded or linked, without an opacity mask whose appearance is one Warp, with /// no fills or strokes that paint and no effects on them: an image the reader reads with its Warp -/// live ([`crate::import::read_art_style`]'s `image_warp`)? +/// live ([`crate::import::read_parsed_style`]'s `image_warp`)? fn warped_image(n: &Node) -> bool { matches!(n.kind, NodeKind::Image(_)) && n.extras().mask.is_none() @@ -162,8 +163,8 @@ fn plain_member(n: &Node) -> bool { pub(in crate::ai_editing) struct Styles { /// Every style, in the order written: its name and text. known: Vec<(String, String)>, - /// The panel's styles written, by the graphic style's id. - panel: HashMap, + /// The panel's styles written, by the graphic style's id: each one's place in [`Self::known`]. + panel: HashMap, /// The panel's styles written, in its order. listed: Vec, /// The names styles have, and the name of each object style by its text. @@ -172,6 +173,54 @@ pub(in crate::ai_editing) struct Styles { next_anon: u64, /// How many objects were written with the graphic style they are linked to. pub(super) links_written: usize, + /// The style texts checked so far, as the reader parses them. + pub(super) parsed: Parsed, +} + +/// The most style texts [`Parsed`] keeps parsed in one save. +const MAX_PARSED: usize = 4096; +/// The most bytes of style text [`Parsed`] keeps parsed in one save. +const MAX_PARSED_BYTES: usize = 8 << 20; + +/// Style texts as the reader parses them ([`crate::import::parse_art_style`]). The first +/// [`MAX_PARSED`] texts, up to [`MAX_PARSED_BYTES`] bytes in all, are each parsed once however many +/// styles and objects are checked with them; a text the reader doesn't parse is kept as `None`. +/// Past that, only the last text checked is kept, and each other text is parsed again when checked. +#[derive(Default)] +pub(super) struct Parsed { + kept: HashMap>, + /// The bytes of the texts in `kept`. + bytes: usize, + /// The last text checked that `kept` doesn't hold, with its parse. + last: Option<(String, Option)>, +} + +#[cfg(test)] +thread_local! { + /// While set on this thread, [`Parsed`] keeps nothing: every check parses its style text again. + pub(in crate::ai_editing) static REPARSE: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +impl Parsed { + /// Style text `text` as the reader parses it (`None` when it doesn't). + pub(super) fn get(&mut self, text: &str) -> Option<&crate::import::ParsedStyle> { + #[cfg(test)] + let reparse = REPARSE.get(); + #[cfg(not(test))] + let reparse = false; + if !reparse && self.kept.contains_key(text) { + return self.kept.get(text).and_then(Option::as_ref); + } + if reparse || self.last.as_ref().is_none_or(|(last, _)| last != text) { + let parsed = crate::import::parse_art_style(known_style("x", text).as_bytes(), "x"); + if !reparse && self.kept.len() < MAX_PARSED && self.bytes.saturating_add(text.len()) <= MAX_PARSED_BYTES { + self.bytes += text.len(); + return self.kept.entry(text.to_owned()).or_insert(parsed).as_ref(); + } + self.last = Some((text.to_owned(), parsed)); + } + self.last.as_ref().and_then(|(_, parsed)| parsed.as_ref()) + } } impl Styles { @@ -652,7 +701,7 @@ impl Writer<'_> { continue; } let xy = Xy { blend: g.blend, opacity: g.opacity.clamp(0.0, 1.0), isolate: g.isolate, knockout: g.knockout, shape: false }; - let text = self.style_text(&g.appearance, xy, None).filter(|t| panel_reads(g, t)); + let text = self.style_text(&g.appearance, xy, None).filter(|t| panel_reads(g, t, &mut self.styles.parsed)); let Some(text) = text else { self.warn(PANEL_STYLES); continue; @@ -669,7 +718,7 @@ impl Writer<'_> { continue; } if g.id != 0 { - self.styles.panel.insert(g.id, g.name.clone()); + self.styles.panel.insert(g.id, self.styles.known.len()); } self.styles.listed.push(g.name.clone()); self.styles.known.push((g.name.clone(), text)); @@ -701,14 +750,13 @@ impl Writer<'_> { } let doc = self.doc; if let Some(id) = orig.extras().graphic_style - && let Some(name) = self.styles.panel.get(&id).cloned() + && let Some((name, text)) = self.styles.panel.get(&id).and_then(|i| self.styles.known.get(*i)) && let Some(g) = doc.graphic_style_by_id(id) && g.transparency_matches(orig) && g.appearance_on(orig).approx_eq(&orig.appearance) - && let Some(text) = self.styles.known.iter().find(|(n, _)| *n == name).map(|(_, t)| t.clone()) - && object_reads(orig, &text) + && object_reads(orig, text, &mut self.styles.parsed) { - return Some(name); + return Some(name.clone()); } let brushed = brushed(orig); if (orig.appearance.effects.is_empty() && !brushed) || !(own_style_holds(&orig.appearance) || warped_image(orig)) { @@ -720,7 +768,7 @@ impl Writer<'_> { let rule = object_rule(orig); let text = self .style_text(&orig.appearance, Xy::of(orig), path.as_ref().map(|p| (p, rule))) - .filter(|t| object_reads(orig, t) && (!brushed || self.brushed_style_reads(t))); + .filter(|t| object_reads(orig, t, &mut self.styles.parsed) && (!brushed || self.brushed_style_reads(t))); let Some(text) = text else { if let Some(mark) = saved.0 { self.gradient_rollback(mark); @@ -784,7 +832,12 @@ impl Writer<'_> { if !self.take_objects(1 + own) { return; } - let linked = orig.extras().graphic_style.and_then(|id| self.styles.panel.get(&id)).is_some_and(|p| p == name); + let linked = orig + .extras() + .graphic_style + .and_then(|id| self.styles.panel.get(&id)) + .and_then(|i| self.styles.known.get(*i)) + .is_some_and(|(p, _)| p == name); if linked { self.styles.links_written += 1; } else if brushed(orig) { @@ -937,13 +990,12 @@ fn own_style_holds(ap: &Appearance) -> bool { } /// Does the reader read graphic style `g` from style text `text` as it is? It leaves out a graphic -/// style with a brush on a stroke that paints. -fn panel_reads(g: &GraphicStyle, text: &str) -> bool { +/// style with a brush on a stroke that paints. `parsed` holds the texts already parsed. +fn panel_reads(g: &GraphicStyle, text: &str, parsed: &mut Parsed) -> bool { if g.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(s) if s.brush.is_some() && !s.paint.is_none())) { return false; } - let section = known_style("x", text); - let Some(read) = crate::import::read_art_style(section.as_bytes(), "x", None) else { return false }; + let Some(read) = parsed.get(text).and_then(|st| crate::import::read_parsed_style(st, None)) else { return false }; // The opacity within the written number's precision. read.transparency.is_some_and(|t| (t.0 - g.opacity).abs() <= 1e-4 && (t.1, t.2, t.3) == (g.blend, g.isolate, g.knockout)) && same_appearance(&read.appearance, &g.appearance) @@ -952,19 +1004,20 @@ fn panel_reads(g: &GraphicStyle, text: &str) -> bool { /// Does the reader read object `n` written with style text `text` as it is: a path or compound /// path with a style it reads on any object, filled by the non-zero rule when the style fills it, /// or a group with no fills or strokes of its own, with effects that move the outline only where the -/// reader reads them ([`crate::import::style_moves_with`]), or an image ([`warped_image`]) with a +/// reader reads them ([`crate::import::parsed_moves_with`]), or an image ([`warped_image`]) with a /// style of one Warp? The reader takes such an image's Warp where it draws as its drawn look. -fn object_reads(n: &Node, text: &str) -> bool { - let section = known_style("x", text); +/// `parsed` holds the texts already parsed. +fn object_reads(n: &Node, text: &str, parsed: &mut Parsed) -> bool { + let Some(st) = parsed.get(text) else { return false }; let own = n.appearance.fill().map(|f| &f.paint).filter(|p| matches!(p, Paint::Gradient(_))); - let Some(mut read) = crate::import::read_art_style(section.as_bytes(), "x", own) else { return false }; + let Some(mut read) = crate::import::read_parsed_style(st, own) else { return false }; let group = matches!(n.kind, NodeKind::Group { .. }); let image = matches!(n.kind, NodeKind::Image(_)); if (image && !(read.image_warp && warped_image(n))) || (!image && !read.simple) || (group && !read.appearance.items.is_empty()) || (!group && read.pathfinder) - || !crate::import::style_moves_with(section.as_bytes(), "x", n) + || !crate::import::parsed_moves_with(st, n) { return false; } @@ -1038,3 +1091,52 @@ pub(super) fn near(a: &Value, b: &Value) -> bool { _ => a == b, } } + +#[cfg(test)] +mod tests { + use super::*; + + /// A style text after its name: a stroke `width` pt wide. + fn stroke_style(width: usize) -> String { + format!( + "/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/BasicFilter :\n(Stroke Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + 2 /FillOrStroke ,\n/Dictionary : /NotRecorded ,\n/StrokeStyle : 0 R\n0 0 0 0 0 0 1 XA\n0 J 0 j {width} w 10 M []0 d\n0 XR\n1 0 Xd\n/Def ;\n (StrokeStyle) ,\n\ + ; /Dict ;\n /Part ,\n/BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n;\n" + ) + } + + /// `text` parsed on its own, as the reader parses it. + fn fresh(text: &str) -> String { + format!("{:?}", crate::import::parse_art_style(known_style("x", text).as_bytes(), "x")) + } + + /// A save that checks more distinct style texts than [`Parsed`] keeps, stroke styles and texts + /// that aren't styles, keeps at most [`MAX_PARSED`] texts and [`MAX_PARSED_BYTES`] bytes, and each + /// check still gives the text's own parse, kept or not, the first time and again. + #[test] + fn parsed_styles_kept_in_a_save_stay_within_the_limits() { + let mut parsed = Parsed::default(); + for i in 0..MAX_PARSED + 100 { + let text = if i % 2 == 0 { stroke_style(i + 1) } else { format!("not a style {i}") }; + let got = format!("{:?}", parsed.get(&text).cloned()); + assert_eq!(got, fresh(&text), "{i}"); + assert_eq!(format!("{:?}", parsed.get(&text).cloned()), got, "{i}"); + assert!(parsed.kept.len() <= MAX_PARSED && parsed.bytes <= MAX_PARSED_BYTES, "{i}: {} texts", parsed.kept.len()); + } + assert_eq!(parsed.kept.len(), MAX_PARSED); + for i in [0, 1, MAX_PARSED - 1, MAX_PARSED, MAX_PARSED + 98, MAX_PARSED + 99] { + let text = if i % 2 == 0 { stroke_style(i + 1) } else { format!("not a style {i}") }; + assert_eq!(format!("{:?}", parsed.get(&text).cloned()), fresh(&text), "{i}"); + } + + let mut parsed = Parsed::default(); + let long = |i: usize| format!("{i} {}", "x".repeat(1 << 20)); + for i in 0..MAX_PARSED_BYTES / (1 << 20) + 4 { + assert_eq!(format!("{:?}", parsed.get(&long(i)).cloned()), fresh(&long(i)), "{i}"); + assert!(parsed.bytes <= MAX_PARSED_BYTES, "{i}: {} bytes", parsed.bytes); + assert_eq!(parsed.bytes, parsed.kept.keys().map(String::len).sum::()); + } + assert!(parsed.kept.len() < MAX_PARSED_BYTES / (1 << 20)); + } +} diff --git a/crates/eps/src/ai_editing/writer/texts.rs b/crates/eps/src/ai_editing/writer/texts.rs index 51ef99de2b..2372003cca 100644 --- a/crates/eps/src/ai_editing/writer/texts.rs +++ b/crates/eps/src/ai_editing/writer/texts.rs @@ -445,8 +445,9 @@ fn held_aki(v: f64) -> f64 { if v.is_nan() { 0.0 } else { v.clamp(0.0, MAX_AKI) } } -/// Has type `t` attributes the text document leaves out ([`TYPE_ATTRIBUTES`])? -pub(in crate::ai_editing) fn loses(t: &TextObject) -> bool { +/// Has type `t` attributes the text document leaves out ([`TYPE_ATTRIBUTES`])? `fonts` holds the +/// fonts already resolved. +fn loses(t: &TextObject, fonts: &mut ResolvedFonts) -> bool { // Small capitals are read back at Document Setup's default size. let default_small_caps = vectorcraft_doc::DocSetup::default().small_caps_size; // A run's style as the text document holds it: every other attribute at its default. A color @@ -484,7 +485,7 @@ pub(in crate::ai_editing) fn loses(t: &TextObject) -> bool { ..CharStyle::default() } }; - let run_lost = |s: &CharStyle| { + let mut run_lost = |s: &CharStyle| { let stroked = !s.stroke.is_none(); // Without a stroke, its weight, cap, join and miter limit draw nothing: nothing is lost. let unstroked = CharStyle::default(); @@ -501,7 +502,7 @@ pub(in crate::ai_editing) fn loses(t: &TextObject) -> bool { }; // A Lab color is written as RGB. let lab = |p: &Paint| matches!(p, Paint::Solid { color: Color::Lab { .. }, .. }); - s != held_char(&s) || lab(&s.fill) || lab(&s.stroke) || !font_kept(&s) + s != held_char(&s) || lab(&s.fill) || lab(&s.stroke) || !fonts.kept(&s) }; // A paragraph's style as the text document holds it, and its text: aligned to the start of // its direction (Auto) without a direction of its own, it comes back aligned left, which @@ -669,6 +670,84 @@ fn font_kept(st: &CharStyle) -> bool { && face(&family, &style, read.as_deref()) == face(&st.font_family, &st.font_style, st.font_version.as_deref()) } +/// The font fields of a style, as [`ResolvedFonts`] keeps what they resolve to: the family, style +/// and version, and each Variable Font setting as the bits of its value, so two settings that +/// differ are two keys even where they are written as one number. +#[derive(PartialEq, Eq, Hash)] +struct FontKey { + family: String, + style: String, + version: Option, + axes: Vec<(String, u64)>, +} + +impl FontKey { + fn of(st: &CharStyle) -> Self { + FontKey { + family: st.font_family.clone(), + style: st.font_style.clone(), + version: st.font_version.clone(), + axes: st.font_axes.iter().map(|(tag, v)| (tag.clone(), v.to_bits())).collect(), + } + } +} + +/// What one style's font fields resolved to, each with the font database's generation +/// ([`vectorcraft_text::FontDb::generation`]) when it was resolved. +#[derive(Default)] +struct Resolved { + /// Its font record ([`font_name`]). + record: Option<(u64, FontRecord)>, + /// Whether its font comes back as itself ([`font_kept`]). + kept: Option<(u64, bool)>, +} + +/// The fonts of the styles written so far, each resolved once for the whole save. A value is used +/// again only while the font database's generation is the one it was resolved in: fonts added or +/// loaded since then resolve it again. +#[derive(Default)] +struct ResolvedFonts(HashMap); + +#[cfg(test)] +thread_local! { + /// While set on this thread, [`ResolvedFonts`] keeps nothing: every run's font is resolved again. + pub(in crate::ai_editing) static RESOLVE_EACH_RUN: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// How many times [`ResolvedFonts`] has resolved a font record or checked a font on this thread. + pub(in crate::ai_editing) static FONT_RESOLVES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +impl ResolvedFonts { + /// The value `slot` holds for the font of style `st` when it was resolved in the font + /// database's current generation, else `resolve(st)`, kept for later runs. + fn get(&mut self, st: &CharStyle, slot: fn(&mut Resolved) -> &mut Option<(u64, T)>, resolve: fn(&CharStyle) -> T) -> &T { + let now = vectorcraft_text::FontDb::global().generation(); + let held = slot(self.0.entry(FontKey::of(st)).or_default()); + #[cfg(test)] + if RESOLVE_EACH_RUN.get() { + *held = None; + } + if held.as_ref().is_some_and(|(generation, _)| *generation != now) { + *held = None; + } + let (_, value) = held.get_or_insert_with(|| { + #[cfg(test)] + FONT_RESOLVES.set(FONT_RESOLVES.get() + 1); + (now, resolve(st)) + }); + value + } + + /// The font record of style `st` ([`font_name`]). + fn record(&mut self, st: &CharStyle) -> &FontRecord { + self.get(st, |r| &mut r.record, font_name) + } + + /// Whether the font of style `st` comes back as itself ([`font_kept`]). + fn kept(&mut self, st: &CharStyle) -> bool { + *self.get(st, |r| &mut r.kept, font_kept) + } +} + /// Whether `c` is a strong right-to-left letter (`Some(true)`: Hebrew, Arabic, Syriac, Thaana, NKo /// and their presentation forms) or a strong left-to-right one (`Some(false)`: any other letter). fn strong_direction(c: char) -> Option { @@ -761,6 +840,8 @@ pub(in crate::ai_editing) struct TextDoc { /// reader counts in them. doc_bytes: usize, doc_values: usize, + /// The fonts of the styles written so far, as they resolve. + resolved: ResolvedFonts, } impl TextDoc { @@ -768,9 +849,14 @@ impl TextDoc { self.stories.is_empty() } + /// Has type `t` attributes the text document leaves out ([`loses`])? + pub(in crate::ai_editing) fn loses(&mut self, t: &TextObject) -> bool { + loses(t, &mut self.resolved) + } + /// The index of the font of `st` in the font set. fn font(&mut self, st: &CharStyle) -> i64 { - let font = font_name(st); + let font = self.resolved.record(st); // Two installed versions of one font are two fonts, so each keeps its own `/5`. let same = |f: &FontRecord| { f.name == font.name && f.version == font.version && f.design.iter().map(|v| fixed(*v)).eq(font.design.iter().map(|v| fixed(*v))) @@ -778,7 +864,7 @@ impl TextDoc { let i = match self.fonts.iter().position(same) { Some(i) => i, None => { - self.fonts.push(font); + self.fonts.push(font.clone()); self.fonts.len() - 1 } }; @@ -1157,7 +1243,7 @@ impl TextDoc { if !whole.runs.iter().any(|r| r.text.chars().any(|c| !c.is_whitespace())) || !self.room(&whole, texts.len()) { return None; } - let lost = split_differs || texts.iter().any(|t| loses(t)); + let lost = split_differs || texts.iter().any(|t| loses(t, &mut self.resolved)); let frames: Vec = texts.iter().map(|t| self.frame(t, canvas, scale)).collect(); let story = self.story(&whole, &frames, scale); if !self.fits(mark) { @@ -1352,3 +1438,58 @@ pub(in crate::ai_editing) fn stub(s: &mut String, story: usize, frame: usize, t: } s.push_str("2 /TextAntialiasing ,\n;\n"); } + +#[cfg(test)] +mod tests { + use super::*; + + /// A style's font resolved through [`ResolvedFonts`], the first time and again, is the font + /// record and the check [`font_name`] and [`font_kept`] give for it: static and variable fonts, + /// a version of their own, Variable Font settings within and outside the axis's range, not a + /// number, +0 and -0, an axis the font doesn't have, and a family that isn't installed. A font + /// resolved before the font database last changed is resolved again. + #[test] + fn resolved_fonts_are_the_fonts_resolved_for_each_run() { + use vectorcraft_text::test_fonts::{VARIABLE_FAMILY, variable_font}; + vectorcraft_text::FontDb::global().add_font(variable_font().unwrap()); + let font = |family: &str, style: &str, version: Option<&str>, axes: &[(&str, f64)]| CharStyle { + font_family: family.into(), + font_style: style.into(), + font_version: version.map(str::to_owned), + font_axes: axes.iter().map(|(t, v)| (t.to_string(), *v)).collect(), + ..CharStyle::default() + }; + let styles = [ + CharStyle::default(), + font("Source Sans 3", "Bold", None, &[]), + font("Inter", "Medium", None, &[]), + font(VARIABLE_FAMILY, "Regular", None, &[]), + font(VARIABLE_FAMILY, "Bold", Some("Version 1.000"), &[]), + font(VARIABLE_FAMILY, "Bold", None, &[("wght", 650.0)]), + font(VARIABLE_FAMILY, "Bold", None, &[("wght", 900.0)]), + font(VARIABLE_FAMILY, "Bold", None, &[("wght", f64::NAN)]), + font(VARIABLE_FAMILY, "Bold", None, &[("wght", 0.0)]), + font(VARIABLE_FAMILY, "Bold", None, &[("wght", -0.0)]), + font(VARIABLE_FAMILY, "Bold", None, &[("wdth", 80.0), ("wght", 500.0)]), + font("No Such Family", "Bold", None, &[]), + font("No Such Family", "", Some("2.0"), &[]), + ]; + let mut fonts = ResolvedFonts::default(); + for round in ["first", "again"] { + for st in &styles { + assert_eq!(fonts.record(st), &font_name(st), "{round}: {st:?}"); + assert_eq!(fonts.kept(st), font_kept(st), "{round}: {st:?}"); + } + } + assert_eq!(fonts.0.len(), styles.len(), "each style's font fields are a key of their own"); + // What was resolved before the font database last changed is resolved again. + let stale = vectorcraft_text::FontDb::global().generation().wrapping_sub(1); + let wrong = FontRecord { name: "Wrong".into(), truetype: false, design: vec![], version: String::new() }; + for st in &styles { + let held = fonts.0.entry(FontKey::of(st)).or_default(); + (held.record, held.kept) = (Some((stale, wrong.clone())), Some((stale, !font_kept(st)))); + assert_eq!(fonts.record(st), &font_name(st), "{st:?}"); + assert_eq!(fonts.kept(st), font_kept(st), "{st:?}"); + } + } +} diff --git a/crates/eps/src/import.rs b/crates/eps/src/import.rs index 0d451ec9da..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; @@ -89,14 +91,14 @@ use obj::PsError; pub use ai::NameEncoding; #[cfg(test)] pub(crate) use ai::objects_read; +#[cfg(test)] +pub(crate) use ai::{ART_STYLE_PARSES, ENVELOPE_DRAWN, ENVELOPE_TYPE_DRAWN}; pub(crate) use ai::{ BLEND_BUDGET, BLEND_PLUGIN, BRUSH_MANAGER, BrushesRead, DEFORM_PLUGIN, EnvelopeGridPoint, MAX_BLEND_KEYS, MAX_BLEND_OBJECTS, - MAX_CHECKED as ENVELOPE_CHECKS, MAX_EDITING_OBJECTS, MAX_GRADIENT_STOPS, MAX_LISTED, MAX_LISTED_NAME, MAX_MESH_SIDE, MAX_SYMBOLS, blend_reads, - brush_plugin_name, brushes_kept, envelope_outline, envelope_upright, mesh_reads, read_art_style, read_brush_object, read_style_list, - style_moves_with, symbol_art_member, turn_brush_art_over, warp_number, + MAX_CHECKED as ENVELOPE_CHECKS, MAX_EDITING_OBJECTS, MAX_GRADIENT_STOPS, MAX_LISTED, MAX_LISTED_NAME, MAX_MESH_SIDE, MAX_SYMBOLS, ParsedStyle, + blend_reads, brush_plugin_name, brushes_kept, envelope_outline, envelope_upright, mesh_reads, parse_art_style, parsed_moves_with, + read_brush_object, read_parsed_style, read_style_list, symbol_art_member, turn_brush_art_over, warp_number, }; -#[cfg(test)] -pub(crate) use ai::{ENVELOPE_DRAWN, ENVELOPE_TYPE_DRAWN}; pub(crate) use ate::{MAX_BYTES as MAX_TEXT_DOCUMENT, MAX_FRAMES, MAX_SEGMENTS, MAX_STORY, MAX_VALUES as MAX_TEXT_VALUES, record_version}; pub use native::{AiLayers, ai_alone, ai_alone_on_page, ai_alone_with, ai_layers_alone, ai_opened_artboard, is_loss, layered_ai, layered_ai_from}; pub(crate) use native::{MAX_TEXT, MAX_WRAP_WORK, scale_document, scale_symbols}; diff --git a/crates/eps/src/import/ai.rs b/crates/eps/src/import/ai.rs index 78990f9db7..5b170b239e 100644 --- a/crates/eps/src/import/ai.rs +++ b/crates/eps/src/import/ai.rs @@ -57,13 +57,15 @@ pub use read::read; #[cfg(test)] pub(crate) use read::with_image_limits; pub(crate) use read::{ - BLEND_BUDGET, MAX_NODES as MAX_EDITING_OBJECTS, MAX_SYMBOLS, join_and, read_art_style, read_over_page, read_program, read_style_list, slot_frame, - slot_of, style_moves_with, symbol_art_member, + BLEND_BUDGET, MAX_NODES as MAX_EDITING_OBJECTS, MAX_SYMBOLS, ParsedStyle, join_and, parse_art_style, parsed_moves_with, read_over_page, + read_parsed_style, read_program, read_style_list, slot_frame, slot_of, symbol_art_member, }; pub use read::{ BindingRef, Brushes, PaletteSwatches, PlacedPage, Structure, Symbols, active_artboard, artboards, bindings_note, brushes, graphic_styles, palette, read_beside, read_in, symbols, variables, }; +#[cfg(test)] +pub(crate) use style::ART_STYLE_PARSES; pub(crate) use read::is_look_slot; pub(crate) use style::{MAX_LISTED, MAX_LISTED_NAME, warp_number}; diff --git a/crates/eps/src/import/ai/brush.rs b/crates/eps/src/import/ai/brush.rs index ef45364de5..da7f4c3576 100644 --- a/crates/eps/src/import/ai/brush.rs +++ b/crates/eps/src/import/ai/brush.rs @@ -63,7 +63,7 @@ use std::sync::Arc; use kurbo::Affine; use vectorcraft_brush::{ArtBrush, ArtScale, Bristle, Brush, BrushKind, Calligraphic, Colorization, Scatter, Variation}; use vectorcraft_color::Paint; -use vectorcraft_doc::{AppearanceItem, Node, NodeKind}; +use vectorcraft_doc::{AppearanceItem, Node, NodeKind, Scaling}; use super::lex::{Lexer, Tok}; use super::obj::Names; @@ -475,10 +475,11 @@ pub(super) fn parse_tool_object(kind: Tool, name: &str, params: &str) -> Result< Ok(BrushDraft { name: name.to_string(), kind }) } -/// Turn `art` over (y for -y) with the art of all its opacity masks, those that don't move with -/// their objects too: the art changes the space it is in, and no object moves over its mask. +/// Turn `art` over (y for -y) with its pattern fills' tiles and the art of all its opacity masks, +/// those that don't move with their objects too: the art changes the space it is in, and no object +/// moves over its tiles or its mask. pub(crate) fn turn_over(art: &mut Node) { - art.transform(Affine::scale_non_uniform(1.0, -1.0), false); + art.transform(Affine::scale_non_uniform(1.0, -1.0), Scaling { patterns: true, ..Scaling::default() }); turn_unlinked_masks(art); } @@ -574,7 +575,12 @@ pub(super) fn finish_brushes_within( let kind = match d.kind { _ if !kept => None, DraftKind::Calligraphic(c) => Some(BrushKind::Calligraphic(c)), - DraftKind::Scatter { brush, art: name } => copy(&name).map(|a| BrushKind::Scatter(Scatter { art: a, ..brush })), + DraftKind::Scatter { brush, art: name } => copy(&name).map(|mut a| { + // Each copy is the section turned over: its side with y up draws down the page + // before the copy's rotation, and a brush draws art's y (down here) down the page. + turn_over(&mut a); + BrushKind::Scatter(Scatter { art: a, ..brush }) + }), DraftKind::Art { mut brush, art: name, settings } => copy(&name).map(|mut a| { // The side of the section with y up draws on the right of the path, and a brush // draws art's y (down here) on the left of the path. @@ -799,14 +805,16 @@ impl BrushesRead { Self { drafts, by_name, bending } } - /// Does the reader read every stroke of art style `style` in `section` (the text between - /// `%AI9_BeginArtStyles` and its end) that names a brush with that brush on it, at the brush's - /// own settings? A style the reader doesn't read, or that names a brush no object gives, or an - /// Art brush in a style with effects, isn't read so. - pub(crate) fn style_reads(&self, section: &[u8], style: &str) -> bool { + /// Does the reader read every stroke of art style `parsed` ([`crate::import::parse_art_style`]) + /// that names a brush with that brush on it, at the brush's own settings? A style the reader + /// doesn't read, or that names a brush no object gives, or an Art brush in a style with effects, + /// isn't read so. + pub(crate) fn style_reads(&self, parsed: &crate::import::ParsedStyle) -> bool { use super::style::StyleItem; - let styles = super::style::art_styles(section); - let Some(st) = styles.get(style).filter(|st| st.plain) else { return false }; + let st = &parsed.style; + if !st.plain { + return false; + } st.items.iter().all(|item| match item { StyleItem::Stroke { brush: Some((name, settings)), .. } => { let Some(draft) = self.by_name.get(name).and_then(|i| self.drafts.get(*i)) else { return false }; diff --git a/crates/eps/src/import/ai/read.rs b/crates/eps/src/import/ai/read.rs index 27a10033db..cc43157bcb 100644 --- a/crates/eps/src/import/ai/read.rs +++ b/crates/eps/src/import/ai/read.rs @@ -155,7 +155,7 @@ pub use document::{ }; pub(crate) use document::{slot_frame, slot_of}; use graph::Graph; -pub(crate) use ops::{read_art_style, read_style_list, style_moves_with}; +pub(crate) use ops::{ParsedStyle, parse_art_style, parsed_moves_with, read_parsed_style, read_style_list}; #[cfg(test)] pub(crate) use raster::with_image_limits; pub(crate) use types::BLEND_BUDGET; diff --git a/crates/eps/src/import/ai/read/ops.rs b/crates/eps/src/import/ai/read/ops.rs index 39499b064d..5283762a51 100644 --- a/crates/eps/src/import/ai/read/ops.rs +++ b/crates/eps/src/import/ai/read/ops.rs @@ -1453,16 +1453,30 @@ pub(crate) fn read_style_list(section: &[u8]) -> Vec { crate::import::ai::style::art_style_list(section).iter().map(|raw| obj::text(raw)).filter(|name| !name.is_empty()).collect() } -/// Art style `name` of `section` as the reader reads it ([`StyleRead`]): [`appearance_from_art_style`], -/// with a style's one gradient fill as `own_gradient`, the object's own gradient, as [`styled`] reads -/// it on objects other than type. A stroke that names a brush is read with that brush's name, as -/// [`styled`] reads it on a path or compound path when the Brushes panel keeps that brush at those -/// settings, which [`crate::import::ai::brush::BrushesRead::style_reads`] checks. `None` when the section -/// doesn't define it, the reader doesn't read it, or it paints with a pattern or a gradient that -/// isn't the object's own. -pub(crate) fn read_art_style(section: &[u8], name: &str, own_gradient: Option<&Paint>) -> Option { +/// An art style as the reader parses it ([`parse_art_style`]), which a writer reads on any number of +/// objects ([`read_parsed_style`], [`parsed_moves_with`], +/// [`crate::import::ai::brush::BrushesRead::style_reads`]). +#[derive(Clone, Debug)] +pub(crate) struct ParsedStyle { + pub(in crate::import::ai) style: crate::import::ai::style::ArtStyle, +} + +/// Art style `name` of `section` (the text between `%AI9_BeginArtStyles` and its end) as the reader +/// parses it. `None` when the section doesn't define it. +pub(crate) fn parse_art_style(section: &[u8], name: &str) -> Option { + crate::import::ai::style::art_styles(section).remove(name).map(|style| ParsedStyle { style }) +} + +/// Art style `parsed` as the reader reads it ([`StyleRead`]): [`appearance_from_art_style`], with a +/// style's one gradient fill as `own_gradient`, the object's own gradient, as [`styled`] reads it on +/// objects other than type. A stroke that names a brush is read with that brush's name, as [`styled`] +/// reads it on a path or compound path when the Brushes panel keeps that brush at those settings, +/// which [`crate::import::ai::brush::BrushesRead::style_reads`] checks. `None` when the reader doesn't +/// read it, or it paints with a pattern or a gradient that isn't the object's own. `parsed` is left as +/// it is, for the next object. +pub(crate) fn read_parsed_style(parsed: &ParsedStyle, own_gradient: Option<&Paint>) -> Option { use crate::import::ai::style::StyleItem; - let mut st = crate::import::ai::style::art_styles(section).remove(name)?; + let mut st = parsed.style.clone(); if st.items.iter().filter(|i| matches!(i, StyleItem::Gradient { .. })).count() == 1 { let own = own_gradient?; for item in &mut st.items { @@ -1491,11 +1505,10 @@ pub(crate) fn read_art_style(section: &[u8], name: &str, own_gradient: Option<&P Some(StyleRead { appearance, simple: st.simple, image_warp: st.image_warp, pathfinder: st.pathfinder, transparency: st.transparency }) } -/// Is art style `name` of `section` read on `object` as far as an effect that moves the outline -/// goes: the style has none, or `object` is one [`moves_with`] reads it on, as [`styled`] checks? -/// `false` when the section doesn't define it. -pub(crate) fn style_moves_with(section: &[u8], name: &str, object: &Node) -> bool { - crate::import::ai::style::art_styles(section).remove(name).is_some_and(|st| !st.moves_outline() || moves_with(object, &st)) +/// Is art style `parsed` read on `object` as far as an effect that moves the outline goes: the style +/// has none, or `object` is one [`moves_with`] reads it on, as [`styled`] checks? +pub(crate) fn parsed_moves_with(parsed: &ParsedStyle, object: &Node) -> bool { + !parsed.style.moves_outline() || moves_with(object, &parsed.style) } /// A style's stroke as an appearance item (`None` for a fill). diff --git a/crates/eps/src/import/ai/style.rs b/crates/eps/src/import/ai/style.rs index e0068a52be..0d87028ec0 100644 --- a/crates/eps/src/import/ai/style.rs +++ b/crates/eps/src/import/ai/style.rs @@ -419,8 +419,16 @@ fn closes(data: &[u8]) -> bool { false } +#[cfg(test)] +thread_local! { + /// How many times [`art_styles`] has parsed a section on this thread. + pub(crate) static ART_STYLE_PARSES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// [`art_styles_in`], names read in the default encoding. pub(super) fn art_styles(data: &[u8]) -> HashMap { + #[cfg(test)] + ART_STYLE_PARSES.set(ART_STYLE_PARSES.get() + 1); art_styles_in(data, &mut Names::default()) } diff --git a/crates/eps/src/import/ai/style/tests.rs b/crates/eps/src/import/ai/style/tests.rs index c4b006fe2a..2b48fd268b 100644 --- a/crates/eps/src/import/ai/style/tests.rs +++ b/crates/eps/src/import/ai/style/tests.rs @@ -1445,7 +1445,8 @@ fn warp_numbers_are_the_dialogs_order() { /// and nothing for styles it doesn't read. #[test] fn a_style_is_read_as_a_writer_checks_it() { - let read = |data: &str, own: Option<&Paint>| crate::import::read_art_style(data.as_bytes(), "Odd", own); + let parse = |data: &str, name: &str| crate::import::parse_art_style(data.as_bytes(), name); + let read = |data: &str, own: Option<&Paint>| parse(data, "Odd").and_then(|st| crate::import::read_parsed_style(&st, own)); let style = |kids: &[String]| format!("/KnownStyle :\n(Odd) /Name ,\n/ActiveStyle :\n{}", compound("Chain Style Filter", kids)); let gradient = fill("Bb\n1 (G) 0 0 0 1 1 0 0 1 0 0 1 Bg\n0 BB"); let stack = compound("Stack Style Filter", std::slice::from_ref(&gradient)); @@ -1456,11 +1457,18 @@ fn a_style_is_read_as_a_writer_checks_it() { assert_eq!(got.appearance.items[0].paint(), &own); assert_eq!(got.transparency.map(|t| (t.0, t.1)), Some((0.5, BlendMode::Multiply))); assert!(got.simple && !got.pathfinder); + // One parse read on two objects: each takes its own gradient, and the parse is left as it was. + let parsed = parse(&data, "Odd").unwrap(); + let black = Paint::solid(vectorcraft_color::Color::BLACK); + let first = crate::import::read_parsed_style(&parsed, Some(&own)).unwrap(); + let second = crate::import::read_parsed_style(&parsed, Some(&black)).unwrap(); + assert_eq!((first.appearance.items[0].paint(), second.appearance.items[0].paint()), (&own, &black)); + assert_eq!(parsed.style, parse(&data, "Odd").unwrap().style); // A gradient that isn't the object's own, a pattern, another name, two gradients: nothing. assert!(read(&data, None).is_none()); let pattern = style(&[compound("Stack Style Filter", &[fill("(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p")])]); assert!(read(&pattern, None).is_none()); - assert!(crate::import::read_art_style(data.as_bytes(), "Even", Some(&own)).is_none()); + assert!(parse(&data, "Even").is_none()); assert!(read(&style(&[compound("Stack Style Filter", &[gradient.clone(), gradient])]), Some(&own)).is_none()); // Damaged text: every cut of the style, and stray bytes, without a panic. for cut in 0..data.len() { diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index 5b3f62f03e..f9ed3601d2 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -10483,11 +10483,11 @@ fn a_brushs_art_places_a_version_7_patterns_tiles_with_its_operands() { }; let plain = placed("0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0]"); // The operands and the move they make from the plain placement (a b c d e f): those of - // `a_pattern_fill_applies_its_offset_scale_rotation_reflection_and_shear` with y down, as the - // art's space has it. + // `a_pattern_fill_applies_its_offset_scale_rotation_reflection_and_shear` in the file's own + // space (y up), since a Scatter brush's art is turned over with its tiles. let cases = [ - ("10 15 1 1 0 0 0 0 0 [1 0 0 1 0 0]", [1.0, 0.0, 0.0, 1.0, 10.0, -15.0]), - ("-5 7 2 .5 -45 0 0 -15 45 [1 0 0 1 0 0]", [1.793151, 0.353553, -1.035276, 0.353553, -5.0, -7.0]), + ("10 15 1 1 0 0 0 0 0 [1 0 0 1 0 0]", [1.0, 0.0, 0.0, 1.0, 10.0, 15.0]), + ("-5 7 2 .5 -45 0 0 -15 45 [1 0 0 1 0 0]", [1.793151, -0.353553, 1.035276, 0.353553, -5.0, 7.0]), ]; for (ops, want) in cases { let got = (placed(ops) * plain.inverse()).as_coeffs(); @@ -11325,6 +11325,103 @@ fn type_with_an_art_brush_keeps_its_drawn_look() { assert_eq!(brushed, 0, "{:?}", r.warnings); } +/// Each copy a Scatter brush places is its section's art turned over before the copy's rotation: +/// the side of the section with y up goes down the page with the rotation at 0° to the page, and +/// to the right of the path's direction when the rotation follows the path. A rotation turns the +/// copy counterclockwise on the page, from the page or from the path's direction. +#[test] +fn a_scatter_brushs_copies_are_its_art_turned_over() { + // Size, spacing 100% and scatter 0%, fixed; the rotation 0° or 90°, to the page or following + // the path. + let still = "2 /Lopsided art/ 5 1 0 0 / 0 1 1 0 1 1 0 0 0 0 0 0 0 0 0"; + let turned = "2 /Lopsided art/ 5 1 0 0 / 0 1 1 0 1 1 0 0 0 0 90 90 0 0 0"; + let along = "2 /Lopsided art/ 5 1 0 0 / 0 1 1 0 1 1 0 0 0 0 0 0 0 1 0"; + let def = format!( + "{}{}{}{}", + lopsided_art("Lopsided art"), + plugin_object(SCATTER, "Still", still), + plugin_object(SCATTER, "Turned", turned), + plugin_object(SCATTER, "Along", along) + ); + let r = read_ok(&format!("{def}{}", layer(&(rect_path(0.0, 0.0, 10.0, 10.0) + "f\n")))); + let lib = vectorcraft_brush::library(&r.doc); + let stroke = vectorcraft_doc::StrokeLayer::new(Paint::solid(Color::BLACK), 1.0); + // The art is 40 by 8, so copies are 40 apart along a line 100 long, centered at 20, 60 and 100 + // from its start. + let pieces = |name: &str, from: (f64, f64), to: (f64, f64)| { + let b = lib.iter().find(|b| b.name == name).unwrap(); + let line = kurbo::BezPath::from_vec(vec![kurbo::PathEl::MoveTo(Point::new(from.0, from.1)), kurbo::PathEl::LineTo(Point::new(to.0, to.1))]); + vectorcraft_brush::stroke_pieces(&r.doc, b, &line, &stroke) + }; + let filled = |pieces: &[Node], x: f64, y: f64| { + pieces.iter().any(|n| { + let mut hit = false; + n.walk(&mut |c| hit |= c.path_data().is_some_and(|p| kurbo::Shape::winding(&p.to_bezpath(), Point::new(x, y)) != 0)); + hit + }) + }; + let still = pieces("Still", (0.0, 0.0), (100.0, 0.0)); + assert_eq!(still.len(), 3, "{still:#?}"); + // The copy at 60 spans 40 to 80: the narrow block is its first 10, the wide block all of it. + assert!(filled(&still, 70.0, -2.0) && !filled(&still, 70.0, 2.0), "the wide block is above the line"); + assert!(filled(&still, 45.0, 2.0), "the narrow block is below it"); + // Turned 90° to the page, the copy at 60 stands across the line from 40 above it to 80 below + // it: the wide block on the left, the narrow block on the right at its bottom 10. + let turned = pieces("Turned", (0.0, 0.0), (100.0, 0.0)); + assert_eq!(turned.len(), 3, "{turned:#?}"); + assert!(filled(&turned, 58.0, 0.0) && !filled(&turned, 62.0, 0.0), "the wide block is left of the copy's middle"); + assert!(filled(&turned, 62.0, 15.0) && !filled(&turned, 62.0, -15.0), "the narrow block is at its bottom"); + // Right to left with the rotation following the path, the copy at 40 (20 to 60) is turned half + // way round: its narrow block is its last 10. + let along = pieces("Along", (100.0, 0.0), (0.0, 0.0)); + assert_eq!(along.len(), 3, "{along:#?}"); + assert!(filled(&along, 30.0, 2.0) && !filled(&along, 30.0, -2.0), "the wide block is below the line"); + assert!(filled(&along, 55.0, -2.0), "the narrow block is above it, at the copy's other end"); + // Up the page with the rotation following the path, the copy at y 40 (20 to 60) is turned a + // quarter round: the wide block on the left of the line, the narrow block on its right at its + // bottom 10, where the line starts. + let up = pieces("Along", (0.0, 100.0), (0.0, 0.0)); + assert_eq!(up.len(), 3, "{up:#?}"); + assert!(filled(&up, -2.0, 40.0) && !filled(&up, 2.0, 40.0), "the wide block is left of the line"); + assert!(filled(&up, 2.0, 55.0) && !filled(&up, 2.0, 25.0), "the narrow block is right of it, at the copy's bottom"); +} + +/// A pattern fill in a Scatter or Art brush's art is turned over with the art: the tiles keep their +/// place on the art. The section fills a 40 by 8 rectangle with an 8-point tile placed with the +/// identity, so the tile's top left is at the rectangle's top left in the section (y up). +#[test] +fn a_pattern_fill_in_brush_art_turns_over_with_the_art() { + let still = "2 /Tiled art/ 5 1 0 0 / 0 1 1 0 1 1 0 0 0 0 0 0 0 0 0"; + let ribbon = "2 / Tiled art/ / / / / 0 0/ 5 0 0 0 / 1 1 1 0 1 0 0 0 1 1 0 0 0 0 1"; + let section = format!( + "%AI8_BeginBrushPattern\n(Tiled art)\n0 A\n(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n{}f\n%AI8_EndBrushPattern\n", + rect_path(0.0, 0.0, 40.0, 8.0) + ); + let def = format!("{DOTS}{section}{}{}", plugin_object(SCATTER, "Spray", still), plugin_object(ART_BRUSH, "Ribbon", ribbon)); + let r = read_ok(&format!("{def}{}", layer(&(rect_path(0.0, 0.0, 10.0, 10.0) + "f\n")))); + let lib = vectorcraft_brush::library(&r.doc); + for name in ["Spray", "Ribbon"] { + let b = lib.iter().find(|b| b.name == name).unwrap_or_else(|| panic!("{name}: {lib:?}")); + let art = match &b.kind { + vectorcraft_brush::BrushKind::Scatter(s) => &s.art, + vectorcraft_brush::BrushKind::Art(a) => &a.art, + k => panic!("{name}: {k:?}"), + }; + let mut found = None; + art.walk(&mut |n| { + if let (Some(_), Paint::Pattern { xf, .. }) = (n.path_data(), fill(n)) { + found = Some((n.geometric_bounds(), xf)); + } + }); + let Some((Some(bounds), xf)) = found else { panic!("{name}: {art:#?}") }; + // The art is turned over (y up again): the tile's top left (0, 0) and its dot (4, 4), in + // the tile's space with y down, are at the rectangle's top left and 4 below it. + assert_eq!(bounds, Rect::new(0.0, 0.0, 40.0, 8.0), "{name}"); + assert!((xf * Point::ZERO - Point::new(0.0, bounds.y1)).hypot() < 1e-9, "{name}: {xf:?}"); + assert!((xf * Point::new(4.0, 4.0) - Point::new(4.0, bounds.y1 - 4.0)).hypot() < 1e-9, "{name}: {xf:?}"); + } +} + use read::{GRAPH_PLAIN, GRAPH_UNENDED}; use vectorcraft_doc::{GraphKind, TickLength}; diff --git a/crates/eps/src/import/ate.rs b/crates/eps/src/import/ate.rs index 5fdd5859a9..96a408ae7d 100644 --- a/crates/eps/src/import/ate.rs +++ b/crates/eps/src/import/ate.rs @@ -65,6 +65,14 @@ impl Val { } } + /// Removes the entry `key` of a dictionary and returns it, without copying it. + fn take(&mut self, key: &str) -> Option { + match self { + Val::Dict(d) => d.remove(key), + _ => None, + } + } + fn num(&self) -> Option { match self { Val::Num(n) if n.is_finite() => Some(*n), @@ -86,6 +94,14 @@ impl Val { } } + /// [`Self::list`] as an owned vector, without copying the items: empty when this isn't a list. + fn into_list(self) -> Vec { + match self { + Val::List(l) => l, + _ => Vec::new(), + } + } + fn nums(&self) -> Option> { self.list().iter().map(Val::num).collect() } @@ -661,20 +677,30 @@ impl Texts { }) .collect(); let main = doc.get("1")?; + main.get("1")?; + main.get("2")?; + doc.get("0")?.get("8")?.get("0")?; let sheets = |key: &str| -> Vec { let list = doc.get("0").and_then(|d| d.get(key)).and_then(|s| s.get("0")).map(Val::list).unwrap_or_default(); list.iter().take(MAX_SHEETS).map(|s| s.get("0").cloned().unwrap_or(Val::Dict(BTreeMap::new()))).collect() }; + let char_sheets = sheets("5"); + let para_sheets = sheets("6"); + let kinsoku_sets = kinsoku_sets(&doc); + // Every path is there (looked up above), so the stories, defaults and frames move out of the + // document without a copy. + let mut doc = doc; + let mut main = doc.take("1")?; Some(Texts { - stories: main.get("1")?.list().to_vec(), + stories: main.take("1")?.into_list(), fonts, - defaults: main.get("2")?.clone(), - para_defaults: main.get("3").cloned().unwrap_or(Val::Dict(BTreeMap::new())), - char_sheets: sheets("5"), - para_sheets: sheets("6"), - frames: doc.get("0")?.get("8")?.get("0")?.list().to_vec(), + defaults: main.take("2")?, + para_defaults: main.take("3").unwrap_or(Val::Dict(BTreeMap::new())), + char_sheets, + para_sheets, + frames: doc.take("0")?.take("8")?.take("0")?.into_list(), patterns: HashMap::new(), - kinsoku_sets: kinsoku_sets(&doc), + kinsoku_sets, }) } @@ -3086,4 +3112,100 @@ mod tests { let (placed, at, _) = first(&s, true); assert!(placed && at.is_some_and(|x| (x - (own + 3.0)).abs() < 1e-6), "{at:?} for {}", own + 3.0); } + + /// [`Val::take`] and [`Val::into_list`] hand over the value they find without copying it. + #[test] + fn taking_a_value_keeps_its_storage() { + let mut v = read(b"/1 [ (a story) << /0 (its frame) >> ] /2 (defaults)").unwrap(); + let (Some(Val::List(l)), Some(Val::Str(s))) = (v.get("1"), v.get("2")) else { panic!("a list and a string") }; + let (list, string) = (l.as_ptr(), s.as_ptr()); + let taken = v.take("1").unwrap().into_list(); + assert_eq!(taken.as_ptr(), list); + assert_eq!(taken.len(), 2); + let Some(Val::Str(s)) = v.take("2") else { panic!("a string") }; + assert_eq!(s.as_ptr(), string); + assert_eq!(v, Val::Dict(BTreeMap::new())); + assert_eq!(v.take("1"), None); + assert_eq!(Val::Num(1.0).take("1"), None); + assert_eq!(Val::Str("x".into()).into_list(), Vec::new()); + } + + /// [`Texts::read`] gives the same stories, defaults, frames, styles, Kinsoku sets and fonts as + /// copying each of them out of the parsed document does, and reads nothing where that finds + /// nothing. + #[test] + fn the_text_document_reads_the_same_as_copying_its_parts() { + type Parts = (Vec, Val, Val, Vec, Vec, Vec, Vec>, Vec<(String, Option)>); + let copied = |document: &str| -> Option { + let doc = names::numbered(read(document.as_bytes())?); + let fonts = doc.get("0")?.get("1")?.get("0")?.list(); + let fonts = fonts + .iter() + .map(|f| { + let record = f.get("0").and_then(|f| f.get("0")); + let text = |k: &str| record.and_then(|r| r.get(k)).and_then(Val::str); + (text("0").unwrap_or_default().to_string(), text("5").and_then(record_version).map(str::to_string)) + }) + .collect(); + let main = doc.get("1")?; + let sheets = |key: &str| -> Vec { + let list = doc.get("0").and_then(|d| d.get(key)).and_then(|s| s.get("0")).map(Val::list).unwrap_or_default(); + list.iter().take(MAX_SHEETS).map(|s| s.get("0").cloned().unwrap_or(Val::Dict(BTreeMap::new()))).collect() + }; + Some(( + main.get("1")?.list().to_vec(), + main.get("2")?.clone(), + main.get("3").cloned().unwrap_or(Val::Dict(BTreeMap::new())), + doc.get("0")?.get("8")?.get("0")?.list().to_vec(), + sheets("5"), + sheets("6"), + kinsoku_sets(&doc), + fonts, + )) + }; + let read_parts = |document: &str| -> Option { + // Padded so that the data's end, `~>`, stays on one line. + let mut document = document.to_string(); + while crate::import::tests_native::native_with_text("", &document).contains("\n%>\n") { + document.push('\n'); + } + let t = Texts::read(crate::import::tests_native::native_with_text("", &document).as_bytes())?; + let fonts = t.fonts.iter().map(|f| (f.name.clone(), f.version.clone())).collect(); + Some((t.stories, t.defaults, t.para_defaults, t.frames, t.char_sheets, t.para_sheets, t.kinsoku_sets, fonts)) + }; + let plain = crate::import::tests_native::text_document(&[ + ("First story", 0, (10.0, 20.0), (1.0, 2.0), 0.0), + ("Second, longer story", 2, (30.0, 40.0), (3.0, 4.0), 5.0), + ("Third", 1, (50.0, 60.0), (5.0, 6.0), 0.0), + ]); + let full = plain + .replacen( + "/8 << /0 [", + "/4 << /0 [ << /0 << /0 (PhotoshopKinsokuHard) >> >> << /0 << /0 (Own) >> >> ] >> \ + /5 << /0 [ << /0 << /0 (Normal) /6 << /1 9.0 >> >> >> << /1 0 >> ] >> \ + /6 << /0 [ << /0 << /0 (Body) /5 << /0 2 >> >> >> ] >> /8 << /0 [", + 1, + ) + .replacen("/2 << /1 12.0 >>", "/2 << /1 12.0 /0 1 >> /3 << /0 2 /33 1 >>", 1); + let cases = [ + ("every part", full.clone(), true), + ("no paragraph defaults", plain.clone(), true), + ("stories that aren't a list", full.replacen("\n/1 << /1 [", "\n/1 << /1 5 /7 [", 1), true), + ("frames that aren't a list", full.replacen("/8 << /0 [", "/8 << /0 5 /7 [", 1), true), + ("no defaults", full.replacen("/2 << /1 12.0 /0 1 >>", "", 1), false), + ("no frames", full.replacen("/8 << /0 [", "/9 << /0 [", 1), false), + ("no stories", full.replacen("\n/1 << /1 [", "\n/1 << /7 [", 1), false), + ("no fonts", full.replacen("/0 << /1 << /0 [", "/0 << /1 << /7 [", 1), false), + ]; + for (case, document, reads) in cases { + assert!(case == "every part" || document != full, "{case} changes the document"); + let want = copied(&document); + assert_eq!(want.is_some(), reads, "{case}"); + assert_eq!(read_parts(&document), want, "{case}"); + } + let Some((stories, defaults, para_defaults, frames, char_sheets, para_sheets, kinsoku, fonts)) = read_parts(&full) else { panic!("read") }; + assert_eq!((stories.len(), frames.len(), char_sheets.len(), para_sheets.len(), fonts.len()), (3, 3, 2, 1, 1)); + assert_eq!(kinsoku, [Some(Kinsoku::Hard), None]); + assert!(defaults.get("0").is_some() && para_defaults.get("33").is_some()); + } } 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/geom/src/shapes.rs b/crates/geom/src/shapes.rs index 76b9b71798..838015115b 100644 --- a/crates/geom/src/shapes.rs +++ b/crates/geom/src/shapes.rs @@ -355,6 +355,18 @@ pub fn circle_through(a: Point, b: Point, c: Point) -> Option<(Point, f64)> { (center.is_finite() && radius.is_finite()).then_some((center, radius)) } +/// The circle through two or three points: two are the ends of a diameter, and three lie on its +/// edge ([`circle_through`]). Its center and radius; `None` for any other number of points, for +/// points that are the same, for three on one line, and for a center or radius that is not finite. +pub fn circle_through_points(points: &[Point]) -> Option<(Point, f64)> { + let circle = match *points { + [a, b] if a != b => Some((a.midpoint(b), a.distance(b) / 2.0)), + [a, b, c] => circle_through(a, b, c), + _ => None, + }; + circle.filter(|(c, r)| c.is_finite() && r.is_finite() && *r > 0.0) +} + /// Regular polygon with `sides` (≥ 3), first vertex straight up from the centre. pub fn polygon(center: Point, radius: f64, sides: u32, rotation_deg: f64) -> PathData { let n = sides.max(3); @@ -756,6 +768,19 @@ mod tests { assert_eq!(circle_through(a, b, Point::new(f64::NAN, 0.0)), None); } + /// Two points are the ends of a diameter, three are on the edge; one, four, two that are the + /// same and a point that is not finite give no circle. + #[test] + fn the_circle_through_two_or_three_points() { + let (a, b, c) = (Point::new(8.0, 0.0), Point::new(0.0, 6.0), Point::ORIGIN); + assert_eq!(circle_through_points(&[a, b]), Some((Point::new(4.0, 3.0), 5.0))); + let (center, r) = circle_through_points(&[a, b, c]).unwrap(); + assert!(center.distance(Point::new(4.0, 3.0)) < 1e-12 && (r - 5.0).abs() < 1e-12, "{center:?} {r}"); + for points in [&[a][..], &[a, b, c, a], &[a, a], &[a, Point::new(f64::INFINITY, 0.0)], &[], &[a, b, a.midpoint(b)]] { + assert_eq!(circle_through_points(points), None, "{points:?}"); + } + } + /// Nearly on one line: a point 10⁻⁴ off a chord 2000 long still gives the circle (its sagitta /// formula `r = (h² + (L/2)²) / 2h`), and its center sits on the chord's perpendicular /// bisector; a point 10⁻¹² off it does not. diff --git a/crates/mcp/src/headless.rs b/crates/mcp/src/headless.rs index cbd2e8ca87..db6c51d47d 100644 --- a/crates/mcp/src/headless.rs +++ b/crates/mcp/src/headless.rs @@ -53,7 +53,7 @@ const HOST_COMMANDS: &[(&str, &str, &str)] = &[ ( "tool.setOption", "Tool Option", - "{key?, value? | values?: {key: value…}, tool?: id (default: the active tool)} → the tool's options (`{}` reads them); kept options last across tool switches", + "{key?, value? | values?: {key: value…}, tool?: id (default: the active tool)} → the tool's options (`{}` or no params reads them; params that are not an object are an error); kept options last across tool switches", ), ]; diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index 7aba7acc78..a8d6cc86e6 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -17,6 +17,7 @@ mod limits; mod links; mod liquify; mod livepaint; +mod move_offsets; mod pen; mod persp; mod place; @@ -1635,6 +1636,54 @@ 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(); + let path = id_of(&call(&mut s, 1, "draw_path", json!({"d": "M40 400 C150 300 250 500 360 400 Z"}))); + let before = call(&mut s, 2, "doc_inspect", json!({})); + for (args, message) in [ + (json!({"text": "Type", "path": path, "pathEffect": "not-an-effect"}), "not-an-effect"), + (json!({"text": "Type", "path": path, "pathEffect": 42}), "must be a string"), + (json!({"text": "Type", "path": path, "mode": "area", "pathEffect": "skew"}), "requires type on a path"), + (json!({"text": "Type", "x": 10, "y": 20, "pathEffect": "skew"}), "requires type on a path"), + ] { + let reply = call(&mut s, 3, "add_text", args); + assert_eq!(reply["isError"], true, "{reply}"); + assert!(text_of(&reply).contains(message), "{reply}"); + assert_eq!(call(&mut s, 4, "doc_inspect", json!({})), before, "path, selection and history must stay intact"); + } + let made = call(&mut s, 5, "add_text", json!({"text": "Type", "path": path, "pathEffect": "skew"})); + assert_eq!(made["isError"], false, "{made}"); + assert!(doc_json(&mut s).to_string().contains("\"pathEffect\":\"skew\"")); +} + #[test] fn text_effect_pathfinder_transform_graph_and_wrap_tools() { let mut s = server(); @@ -2210,3 +2259,55 @@ fn add_text_reports_overflow_and_takes_a_fit() { let point = made(&call(&mut s, 3, "add_text", json!({"text": "NEON DRIVE", "x": 0, "y": 300, "size": 60}))); assert!(point.get("overflow").is_none(), "{point}"); } + +#[test] +fn transform_rejects_nonnumeric_steps_before_editing() { + let inspect = |s: &mut Server, id| serde_json::from_str::(&text_of(&call(s, id, "doc_inspect", json!({})))).unwrap(); + let mut s = server(); + let first = id_of(&call(&mut s, 1, "draw_path", json!({"d": "M10 10 L30 10 L30 25 Z"}))); + let second = id_of(&call(&mut s, 2, "draw_path", json!({"d": "M40 40 L60 40 L60 55 Z"}))); + let before = inspect(&mut s, 3); + assert_eq!(before["selection"], json!([second])); + + let cases = [ + ("rotate", json!({"dx": 10, "rotate": "bad"})), + ("scale", json!({"dx": 10, "scale": "bad"})), + ("scaleX", json!({"dx": 10, "scaleX": "bad", "scaleY": 150})), + ("scaleY", json!({"dx": 10, "scaleX": 150, "scaleY": "bad"})), + ("shear", json!({"dx": 10, "shear": "bad"})), + ]; + for (index, (field, mut args)) in cases.into_iter().enumerate() { + args["ids"] = json!([first]); + let request_id = 4 + index as u64 * 2; + let rejected = call(&mut s, request_id, "transform", args); + assert_eq!(rejected["isError"], true, "{field}: {rejected}"); + assert!(text_of(&rejected).contains(field), "{field}: {rejected}"); + assert_eq!(inspect(&mut s, request_id + 1), before, "{field}"); + } + + let applied = call(&mut s, 14, "transform", json!({"ids": [first], "dx": 10, "rotate": null, "scale": 150, "scaleX": 125})); + assert_eq!(applied["isError"], false, "{applied}"); + let applied: Value = serde_json::from_str(&text_of(&applied)).unwrap(); + assert_eq!(applied["applied"], json!(["move", "scale"])); + let after = inspect(&mut s, 15); + assert_ne!(after, before); + assert_eq!(after["objects"], before["objects"]); + assert_eq!(after["selection"], json!([first])); + let bounds = &after["selectionBounds"]; + assert!((bounds["width"].as_f64().unwrap() - 25.0).abs() < 1e-6, "{bounds}"); + assert!((bounds["height"].as_f64().unwrap() - 22.5).abs() < 1e-6, "{bounds}"); + assert!(after["history"].as_array().unwrap().contains(&json!("Move"))); + assert!(after["history"].as_array().unwrap().contains(&json!("Scale"))); + + let applied = call(&mut s, 16, "transform", json!({"ids": [second], "dx": 10, "rotate": 90, "origin": [0, 0]})); + assert_eq!(applied["isError"], false, "{applied}"); + let applied: Value = serde_json::from_str(&text_of(&applied)).unwrap(); + assert_eq!(applied["applied"], json!(["move", "rotate"])); + let after = inspect(&mut s, 17); + assert_eq!(after["selection"], json!([second])); + let bounds = &after["selectionBounds"]; + for (field, expected) in [("x", 40.0), ("y", -70.0), ("width", 15.0), ("height", 20.0)] { + assert!((bounds[field].as_f64().unwrap() - expected).abs() < 1e-6, "{field}: {bounds}"); + } + assert!(after["history"].as_array().unwrap().ends_with(&[json!("Move"), json!("Rotate")])); +} diff --git a/crates/mcp/src/tests/liquify.rs b/crates/mcp/src/tests/liquify.rs index 4760380bc2..793f16efee 100644 --- a/crates/mcp/src/tests/liquify.rs +++ b/crates/mcp/src/tests/liquify.rs @@ -28,6 +28,36 @@ fn tool_options_are_set_headless_and_kept_across_tool_switches() { assert_eq!(command(&mut h, "tool.setOption", json!({}))["detail"], json!(6.0)); } +/// A value the tool refuses is an error result naming the tool and the option, and the options +/// stay as they were, the good value given with it included. +#[test] +fn a_refused_option_value_is_an_error_result() { + let mut h = Headless::with_document(); + command(&mut h, "tool.select", json!({"tool": "warp"})); + let before = command(&mut h, "tool.setOption", json!({})); + for values in [json!({"width": 64, "detail": 99}), json!({"width": 64, "detail": "fine"})] { + let r = call_tool(&mut h, "run_command", &json!({"command": "tool.setOption", "params": {"values": values}})); + assert!(r.is_error, "{r:?}"); + assert!(format!("{:?}", r.content).contains("tool `warp`: `detail` must be a number from 1 to 10"), "{r:?}"); + } + assert_eq!(command(&mut h, "tool.setOption", json!({})), before); +} + +/// `tool.setOption` with params that are not an object is an error result that sets nothing; +/// without params it reads the options, as `{}` does. +#[test] +fn set_option_params_that_are_not_an_object_are_an_error_result() { + let mut h = Headless::with_document(); + command(&mut h, "tool.select", json!({"tool": "warp"})); + let before = command(&mut h, "tool.setOption", json!({})); + for params in [json!(true), json!(7), json!([]), json!("x")] { + let r = call_tool(&mut h, "run_command", &json!({"command": "tool.setOption", "params": params})); + assert!(r.is_error, "{params}: {r:?}"); + } + assert_eq!(ok(&mut h, "run_command", json!({"command": "tool.setOption"})), before); + assert_eq!(command(&mut h, "tool.setOption", json!({})), before); +} + #[test] fn pointer_gestures_carry_pen_pressure() { let bloat = |pressure: f64| { diff --git a/crates/mcp/src/tests/move_offsets.rs b/crates/mcp/src/tests/move_offsets.rs new file mode 100644 index 0000000000..77fb8860a2 --- /dev/null +++ b/crates/mcp/src/tests/move_offsets.rs @@ -0,0 +1,67 @@ +use serde_json::{Value, json}; + +use super::{Server, call, id_of, server, text_of}; + +fn inspect(s: &mut Server, id: u64) -> Value { + serde_json::from_str(&text_of(&call(s, id, "doc_inspect", json!({})))).unwrap() +} + +fn path(s: &mut Server, id: u64, d: &str) -> u64 { + id_of(&call(s, id, "draw_path", json!({"d": d}))) +} + +fn child(doc: &Value, id: u64) -> Value { + doc["layers"][0]["children"].as_array().unwrap().iter().find(|node| node["id"] == id).unwrap().clone() +} + +#[test] +fn transform_rejects_malformed_move_offsets_before_selection_or_copy() { + let mut s = server(); + let first = path(&mut s, 1, "M40 40 L60 40 L60 60 L40 60 Z"); + let second = path(&mut s, 2, "M100 100 L130 100 L130 140 L100 140 Z"); + let before = inspect(&mut s, 3); + assert_eq!(before["selection"], json!([second])); + + let cases = [("dx", json!({"ids": [first], "dx": "bad", "copy": true})), ("dy", json!({"ids": [first], "dx": 10, "dy": "bad", "copy": true}))]; + for (index, (field, args)) in cases.into_iter().enumerate() { + let request_id = 4 + index as u64 * 2; + let result = call(&mut s, request_id, "transform", args); + assert_eq!(result["isError"], true, "{field}: {result}"); + assert!(text_of(&result).contains(field), "{field}: {result}"); + assert_eq!(inspect(&mut s, request_id + 1), before, "{field}"); + } + + // The recorded request omits dx and must still move a copy down by 10 points. + let result = call(&mut s, 8, "transform", json!({"ids": [first], "dy": 10, "copy": true})); + assert_eq!(result["isError"], false, "{result}"); + let reply: Value = serde_json::from_str(&text_of(&result)).unwrap(); + assert_eq!(reply["applied"], json!(["move"])); + let after = inspect(&mut s, 9); + let copied = after["selection"][0].as_u64().unwrap(); + assert_ne!(copied, first); + assert_ne!(copied, second); + let original_before = child(&before, first); + let original_after = child(&after, first); + let second_after = child(&after, second); + let copy_after = child(&after, copied); + assert_eq!(original_after["bounds"], original_before["bounds"]); + assert_eq!(second_after["bounds"], child(&before, second)["bounds"]); + assert_eq!(copy_after["bounds"]["x"], original_before["bounds"]["x"]); + assert_eq!(copy_after["bounds"]["y"], original_before["bounds"]["y"].as_f64().unwrap() + 10.0); + assert_eq!(copy_after["bounds"]["width"], original_before["bounds"]["width"]); + assert_eq!(copy_after["bounds"]["height"], original_before["bounds"]["height"]); + let before_history = before["history"].as_array().unwrap(); + let after_history = after["history"].as_array().unwrap(); + assert_eq!(after_history.len(), before_history.len() + 1); + assert_eq!(after_history.last(), Some(&json!("Move"))); + + // Null keeps the engine's optional-number default while a negative numeric offset is applied. + let result = call(&mut s, 10, "transform", json!({"ids": [second], "dx": null, "dy": -7})); + assert_eq!(result["isError"], false, "{result}"); + let after_null = inspect(&mut s, 11); + let moved = child(&after_null, second); + let second_before = child(&before, second); + assert_eq!(moved["bounds"]["x"], second_before["bounds"]["x"]); + assert_eq!(moved["bounds"]["y"], second_before["bounds"]["y"].as_f64().unwrap() - 7.0); + assert_eq!(after_null["history"].as_array().unwrap().last(), Some(&json!("Move"))); +} 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/dispatch.rs b/crates/mcp/src/tools/dispatch.rs index 2ee9f01759..95c8e8671d 100644 --- a/crates/mcp/src/tools/dispatch.rs +++ b/crates/mcp/src/tools/dispatch.rs @@ -275,7 +275,15 @@ fn dispatch(b: &mut dyn Backend, name: &str, a: &Args) -> Result j(transform(b, a)?), + "transform" => { + // Validate all numeric steps before the handler changes selection or runs a step. + for field in ["dx", "dy", "rotate", "scale", "scaleX", "scaleY", "shear"] { + if a.get(field).is_some_and(|value| !value.is_null() && value.as_f64().is_none()) { + return Err(format!("`{field}` must be a number")); + } + } + j(transform(b, a)?) + } "create_graph" => { let mut p = Value::Object(a.clone()); if p.get("type").is_none() { diff --git a/crates/mcp/src/tools/handlers.rs b/crates/mcp/src/tools/handlers.rs index 717c641e19..619af2e12e 100644 --- a/crates/mcp/src/tools/handlers.rs +++ b/crates/mcp/src/tools/handlers.rs @@ -247,6 +247,16 @@ pub(super) fn select_ids(b: &mut dyn Backend, a: &Args) -> Result<(), String> { pub(super) fn add_text(b: &mut dyn Backend, a: &Args) -> Result { let text = a.get("text").and_then(Value::as_str).ok_or("missing string argument `text`")?; + // Creating type on a path replaces the path. Refuse an invalid effect before editing. + let path_effect = match a.get("pathEffect") { + None | Some(Value::Null) => None, + Some(Value::String(effect)) if vectorcraft_doc::PathEffect::parse(effect).is_some() => Some(effect), + Some(Value::String(effect)) => return Err(format!("unknown path effect `{effect}`")), + Some(_) => return Err("`pathEffect` must be a string".into()), + }; + if path_effect.is_some() && (!a.contains_key("path") || a.get("mode").is_some_and(|m| !matches!(m.as_str(), Some("onPath" | "path")))) { + return Err("`pathEffect` requires type on a path".into()); + } let mut style = json!({}); for k in ["size", "font", "color", "justify", "vertical"] { if let Some(v) = a.get(k) { @@ -276,12 +286,12 @@ pub(super) fn add_text(b: &mut dyn Backend, a: &Args) -> Result { } exec(b, "text.create", p)? }; - if let Some(e) = a.get("pathEffect").and_then(Value::as_str) { + if let Some(e) = path_effect { exec(b, "type.pathOptions", json!({"effect": e}))?; } let mut made = json!({"id": r.get("id")}); // A path effect is applied after the text is made: ask again how it fits then. - let overflow = match r.get("id").filter(|_| a.get("pathEffect").is_some()) { + let overflow = match r.get("id").filter(|_| path_effect.is_some()) { Some(id) => exec(b, "document.node", json!({"id": id, "summary": true}))?.get("overflow").and_then(Value::as_bool) == Some(true), None => r.get("overflow").is_some(), }; @@ -292,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)); @@ -312,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 da9ed36a18..4ff7aacecd 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -143,7 +143,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} opens SVG Options; with params = document.export {path?, svg?: {…SVG options}, range?…} (a .svgz path writes it gzipped)", ), - ("file.export.png", "Export As PNG…", "", "{path?, …document.export options}; no path: pick the file, then PNG Options"), + ( + "file.export.png", + "Export As PNG…", + "", + "{path?, …document.export options}; no path: pick the file, then PNG Options with supplied options retained and defaults for omitted options", + ), ( "file.exportForScreens", "Export for Screens…", @@ -161,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", @@ -846,7 +857,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "tool.setOption", "Tool Option", "", - "{key, value} | {values: {key: value…}}, tool?: id (default: the active tool) → the tool's options (`{}` reads them). The options a tool keeps (Liquify brush and tool options, Mirror & Cut, Puppet Warp, drawing tools…) last across tool switches and are saved with the preferences; another tool's are stored for when it is chosen", + "{key, value} | {values: {key: value…}}, tool?: id (default: the active tool) → the tool's options (`{}` or no params reads them; params that are not an object are an error). The options a tool keeps (Liquify brush and tool options, Mirror & Cut, Puppet Warp, drawing tools…) last across tool switches and are saved with the preferences; another tool's are stored for when it is chosen. Every option is checked before any is set: an option the tool doesn't have, a value of the wrong type, a number out of the tool's range or an unknown choice is an error naming the tool and the option, and nothing changes. The Live Paint tools' width and the Shape Builder's gapLength are set to the nearest end of their range instead", ), ( "tool.toggleTouchMode", @@ -889,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…", @@ -942,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", @@ -996,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/metafile/src/lib.rs b/crates/metafile/src/lib.rs index 1ba560d05e..8e5f53ce41 100644 --- a/crates/metafile/src/lib.rs +++ b/crates/metafile/src/lib.rs @@ -1,6 +1,7 @@ //! Windows metafiles: hand-written EMF and WMF writers and readers. //! -//! [`export`] writes the visible art over one region of a document (an artboard) as a metafile: +//! [`export`] writes the visible art over one region of a document (an artboard) as a metafile, +//! and [`export_regions`] one metafile per region: //! //! - **EMF**: paths keep their Bézier curves, fills are solid brushes, strokes geometric pens with //! their width, caps, joins, miter limit and dashes; strokes a pen can't draw (aligned inside or @@ -81,20 +82,36 @@ pub struct Output { /// not); template layers, hidden objects and guides are left out. Raster effects should be turned /// into images before (the engine does); the ones left are reported and left out. pub fn export(doc: &Document, region: Rect, kind: Kind) -> Result { - let r = region.abs(); - if ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) || r.width() <= 0.0 || r.height() <= 0.0 { + Ok(export_regions(doc, &[region], kind)?.pop().unwrap_or_default()) +} + +/// Write the visible art of `doc` over each of `regions` as `kind`, one metafile per region in the +/// same order, each as [`export`] writes it over that region. The live effects are applied once +/// for all of them. When any region is empty, nothing is written and the result is an error. +pub fn export_regions(doc: &Document, regions: &[Rect], kind: Kind) -> Result, String> { + let regions: Vec = regions.iter().map(|r| r.abs()).collect(); + if regions.iter().any(|r| ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) || r.width() <= 0.0 || r.height() <= 0.0) { return Err("the export region is empty".into()); } + if regions.is_empty() { + return Ok(Vec::new()); + } // The scene writes layers that do not print and leaves hidden layers and objects out. let layers = vectorcraft_effects::WrittenLayers { hidden: false, non_printing: true, hidden_objects: false }; let baked = vectorcraft_effects::bake_document_placing_symbols(doc, kind == Kind::Emf, layers); let doc = baked.as_ref().unwrap_or(doc); - let (ops, mut warnings) = scene::Scene::new(doc, r, kind == Kind::Emf).run(); - let bytes = match kind { - Kind::Emf => emf::write(&ops, r, doc.info_title()), - Kind::Wmf => wmf::write(&ops, r, &mut warnings), - }; - Ok(Output { bytes, warnings }) + let outputs = regions + .into_iter() + .map(|r| { + let (ops, mut warnings) = scene::Scene::new(doc, r, kind == Kind::Emf).run(); + let bytes = match kind { + Kind::Emf => emf::write(&ops, r, doc.info_title()), + Kind::Wmf => wmf::write(&ops, r, &mut warnings), + }; + Output { bytes, warnings } + }) + .collect(); + Ok(outputs) } /// A metafile read into a document. diff --git a/crates/metafile/src/tests.rs b/crates/metafile/src/tests.rs index 2314ccb637..658628f107 100644 --- a/crates/metafile/src/tests.rs +++ b/crates/metafile/src/tests.rs @@ -396,6 +396,177 @@ fn hidden_and_offboard_art_is_left_out() { assert!(export(&d, Rect::new(0.0, 0.0, 0.0, 10.0), Kind::Emf).is_err(), "an empty region"); } +/// One metafile of `doc` over `region`, applying the live effects for this region alone: what +/// [`export`] did for each region before [`export_regions`] applied them once for all regions. +fn export_baking_each_region(doc: &Document, region: Rect, kind: Kind) -> Result { + let r = region.abs(); + if ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) || r.width() <= 0.0 || r.height() <= 0.0 { + return Err("the export region is empty".into()); + } + let layers = vectorcraft_effects::WrittenLayers { hidden: false, non_printing: true, hidden_objects: false }; + let baked = vectorcraft_effects::bake_document_placing_symbols(doc, kind == Kind::Emf, layers); + let doc = baked.as_ref().unwrap_or(doc); + let (ops, mut warnings) = crate::scene::Scene::new(doc, r, kind == Kind::Emf).run(); + let bytes = match kind { + Kind::Emf => crate::emf::write(&ops, r, doc.info_title()), + Kind::Wmf => crate::wmf::write(&ops, r, &mut warnings), + }; + Ok(Output { bytes, warnings }) +} + +/// A Zig Zag effect with its default settings. +fn zig_zag() -> vectorcraft_doc::Effect { + vectorcraft_doc::Effect { id: "distort.zigZag".into(), params: Default::default(), visible: true } +} + +/// `boards` 100 pt squares side by side, each holding `paths` rectangles with a live Zig Zag +/// and a gradient-filled one, and every second one an instance of a symbol whose art has a Zig +/// Zag too; `boards` regions, one over each square. +fn zig_zag_boards(boards: usize, paths: usize) -> (Document, Vec) { + let mut d = Document::new(100.0 * boards as f64, 100.0); + let mut art = path(shapes::rectangle(Rect::new(0.0, 0.0, 30.0, 20.0)), blue(), red(), 1.0); + art.appearance.effects.push(zig_zag()); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Zig".into(), art: Arc::new(art) }); + let g = Paint::Gradient(Box::new(GradientPaint::new(Gradient::default()))); + for b in 0..boards { + let x = 100.0 * b as f64; + for i in 0..paths { + let at = (i % 9) as f64 * 9.0; + let mut n = path(shapes::rectangle(Rect::new(x + at + 2.0, at + 2.0, x + at + 20.0, at + 15.0)), red(), blue(), 0.5); + n.appearance.effects.push(zig_zag()); + add(&mut d, n); + } + add(&mut d, path(shapes::rectangle(Rect::new(x + 60.0, 60.0, x + 90.0, 90.0)), g.clone(), Paint::None, 0.0)); + if b % 2 == 1 { + let inst = Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: "Zig".into(), xf: Affine::translate((x + 50.0, 10.0)) }); + add(&mut d, inst); + } + } + let regions = (0..boards).map(|b| Rect::new(100.0 * b as f64, 0.0, 100.0 * (b + 1) as f64, 100.0)).collect(); + (d, regions) +} + +/// Each region's metafile is byte for byte, and warning for warning, what a separate export of +/// that region writes, in EMF and WMF, in the regions' order and in reverse. +#[test] +fn export_regions_writes_what_each_region_writes_alone() { + let (d, mut regions) = zig_zag_boards(3, 2); + let layers = vectorcraft_effects::WrittenLayers { hidden: false, non_printing: true, hidden_objects: false }; + assert!(vectorcraft_effects::bake_document_placing_symbols(&d, true, layers).is_some(), "the document has live effects to apply"); + for _ in 0..2 { + for kind in [Kind::Emf, Kind::Wmf] { + let outs = export_regions(&d, ®ions, kind).unwrap(); + assert_eq!(outs.len(), regions.len()); + for (r, out) in regions.iter().zip(&outs) { + let alone = export_baking_each_region(&d, *r, kind).unwrap(); + assert!(out.bytes == alone.bytes, "{kind:?} over {r:?}: the bytes differ"); + assert_eq!(out.warnings, alone.warnings, "{kind:?} over {r:?}"); + let one = export(&d, *r, kind).unwrap(); + assert!(one.bytes == alone.bytes, "{kind:?} over {r:?}: export's bytes differ"); + assert_eq!(one.warnings, alone.warnings, "{kind:?} over {r:?}"); + } + if kind == Kind::Wmf { + assert!(outs.iter().all(|o| o.warnings.iter().any(|w| w.contains("gradients"))), "{:?}", outs[0].warnings); + } + } + regions.reverse(); + } +} + +/// An empty region among valid ones writes nothing and is the one error; no region writes no +/// metafile. +#[test] +fn export_regions_with_an_empty_region_writes_nothing() { + let (d, regions) = zig_zag_boards(2, 1); + for kind in [Kind::Emf, Kind::Wmf] { + for empty in [Rect::new(10.0, 10.0, 10.0, 50.0), Rect::new(0.0, 0.0, f64::NAN, 10.0), Rect::new(0.0, 0.0, f64::INFINITY, 10.0)] { + let with_empty = [regions[0], empty, regions[1]]; + assert_eq!(export_regions(&d, &with_empty, kind).map(|o| o.len()), Err("the export region is empty".to_string()), "{kind:?}"); + } + assert!(export_regions(&d, &[], kind).unwrap().is_empty(), "{kind:?}"); + // A region given right to left or bottom to top is the same region. + let flipped = Rect::new(regions[1].x1, regions[1].y1, regions[1].x0, regions[1].y0); + let outs = export_regions(&d, &[flipped], kind).unwrap(); + assert!(outs[0].bytes == export(&d, regions[1], kind).unwrap().bytes, "{kind:?}"); + } +} + +/// The CPU time all of this process's threads have used, from Linux's scheduler statistics; `None` +/// elsewhere. +fn process_cpu() -> Option { + let mut ns = 0u64; + for task in std::fs::read_dir("/proc/self/task").ok()? { + let stat = std::fs::read_to_string(task.ok()?.path().join("schedstat")).ok()?; + ns += stat.split_whitespace().next()?.parse::().ok()?; + } + Some(std::time::Duration::from_nanos(ns)) +} + +/// The time `f` takes: this process's CPU time where Linux reports it, otherwise the wall clock. +fn time(f: impl FnOnce() -> T) -> (std::time::Duration, T) { + match process_cpu() { + Some(before) => { + let t = f(); + (process_cpu().map_or(std::time::Duration::ZERO, |after| after.saturating_sub(before)), t) + } + None => { + let start = std::time::Instant::now(); + let t = f(); + (start.elapsed(), t) + } + } +} + +/// Timings of an export of 1, 2 and 8 artboards that applies the live effects once for each +/// artboard and of [`export_regions`], which applies them once, in EMF and WMF: 500 rectangles with +/// a live Zig Zag on each artboard. The two take turns going first, 7 runs each, and every run's +/// files are compared. Ignored by default; it prints the median, fastest and slowest run and sets +/// no bound on them: +/// `cargo test --release -p vectorcraft-metafile --lib export_regions_perf -- --ignored --nocapture`. +#[test] +#[ignore = "a benchmark: run with --ignored --nocapture"] +fn export_regions_perf() { + const RUNS: usize = 7; + let ms = |d: std::time::Duration| d.as_secs_f64() * 1000.0; + eprintln!("export_regions_perf: {}", if process_cpu().is_some() { "process CPU time" } else { "wall clock" }); + eprintln!("export_regions_perf: {:>6} {:<4} {:>32} {:>32}", "boards", "kind", "bake per board ms (min-max)", "bake once ms (min-max)"); + for boards in [1, 2, 8] { + let (d, regions) = zig_zag_boards(boards, 500); + for kind in [Kind::Emf, Kind::Wmf] { + let each = || regions.iter().map(|r| export_baking_each_region(&d, *r, kind).unwrap()).collect::>(); + let once = || export_regions(&d, ®ions, kind).unwrap(); + let (mut old, mut new) = (Vec::new(), Vec::new()); + for run in 0..RUNS { + let ((to, a), (tn, b)) = if run % 2 == 0 { + let o = time(each); + (o, time(once)) + } else { + let n = time(once); + (time(each), n) + }; + old.push(to); + new.push(tn); + assert_eq!(a.len(), b.len()); + for (a, b) in a.iter().zip(&b) { + assert!(a.bytes == b.bytes && a.warnings == b.warnings, "{boards} boards, {kind:?}"); + } + } + old.sort(); + new.sort(); + eprintln!( + "export_regions_perf: {boards:>6} {:<4} {:>12.1} ({:>8.1}-{:>8.1}) {:>12.1} ({:>8.1}-{:>8.1})", + kind.id(), + ms(old[RUNS / 2]), + ms(old[0]), + ms(old[RUNS - 1]), + ms(new[RUNS / 2]), + ms(new[0]), + ms(new[RUNS - 1]), + ); + } + } +} + #[test] fn an_instance_whose_art_reaches_the_artboard_is_written() { // The symbol's red rectangle, (100, 100) to (140, 140), drawn from (-50, -50): on the artboard, 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 e11cda9acd..bd241421c7 100644 --- a/crates/pdf/src/export/writer.rs +++ b/crates/pdf/src/export/writer.rs @@ -64,14 +64,16 @@ 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(); - // Tagged CMYK colours need the profile (PDF/A tags every colour). - let cmyk_profile = if out.tagged { out.cmyk_icc() } else { None }; - if out.tagged && cmyk_profile.is_none() { + // Tagged CMYK colours need the profile (PDF/A tags every colour). When CMYK colors are + // DeviceCMYK (`device_cmyk`), the writer gets no CMYK profile. + let tags_cmyk = out.tagged && !out.device_cmyk(); + let cmyk_profile = if tags_cmyk { out.cmyk_icc() } else { None }; + if tags_cmyk && cmyk_profile.is_none() { warnings.push(format!("the CMYK profile {} can't be embedded: CMYK colours are written untagged", out.cmyk_profile())); } let version = match set.compatibility { @@ -109,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), @@ -271,8 +277,15 @@ impl Writer { PdfError::from(e) })?; if self.cmyk { - let profile = self.out.tagged.then(|| vectorcraft_color::cms::icc_bytes(self.out.cmyk_profile()).ok()).flatten(); - cmyk_blending(&mut bytes, self.out.tagged, profile.as_deref(), self.out.standard != Standard::PdfA2b); + let device = self.out.device_cmyk(); + let profile = (self.out.tagged && !device).then(|| vectorcraft_color::cms::icc_bytes(self.out.cmyk_profile()).ok()).flatten(); + let without = match (&profile, self.out.standard != Standard::PdfA2b) { + _ if device => Without::AlwaysDeviceCmyk, + (None, _) => Without::FirstCmyk, + (Some(_), true) => Without::DeviceCmyk, + (Some(_), false) => Without::Rgb, + }; + cmyk_blending(&mut bytes, self.out.tagged, profile.as_deref(), without); } let lab = !self.lab_spots.is_empty() && !self.out.standard.cmyk_only(); let bytes = if lab { crate::lab_spot::lab_alternates(bytes, &self.lab_spots) } else { bytes }; @@ -287,19 +300,12 @@ impl Writer { /// are rewritten in place to DeviceCMYK (or the CMYK profile's space), keeping their length so the /// cross-reference offsets stay valid. Luminosity masks' groups keep RGB: mask luminance is that /// of screen colours, as on screen. Tagged groups blend in the space of CMYK profile `profile` -/// (the one that tags CMYK colours) when the file has one. When its only CMYK spaces are of other -/// profiles (images' own), they blend in DeviceCMYK where `device` allows it, else they keep RGB; -/// without `profile`, they blend in the first CMYK space. -fn cmyk_blending(pdf: &mut [u8], tagged: bool, profile: Option<&[u8]>, device: bool) { +/// (the one that tags CMYK colours) when the file has one; otherwise they blend as `without` says. +fn cmyk_blending(pdf: &mut [u8], tagged: bool, profile: Option<&[u8]>, without: Without) { let masks = luminosity_mask_groups(pdf); let mut spaces = vec![("/CS/DeviceRGB".to_string(), "/CS/DeviceCMYK".to_string())]; if tagged { let own = profile.and_then(|icc| crate::output::tagging_stream(pdf, &crate::patch::Xref::read(pdf)?, icc)); - let without = match (profile, device) { - (None, _) => Without::FirstCmyk, - (Some(_), true) => Without::DeviceCmyk, - (Some(_), false) => Without::Rgb, - }; spaces.extend(icc_spaces(pdf, own, without)); } let mut from = 0; @@ -316,11 +322,15 @@ fn cmyk_blending(pdf: &mut [u8], tagged: bool, profile: Option<&[u8]>, device: b /// What tagged groups blend in when the file holds no space of the document's CMYK profile. #[derive(Clone, Copy, Debug, PartialEq)] enum Without { - /// The first ICC-based CMYK space of the file. + /// The first ICC-based CMYK space of the file (the document's profile isn't known). FirstCmyk, + /// DeviceCMYK when the file has an ICC-based CMYK space (images' own profiles), outside PDF/A. DeviceCmyk, - /// The RGB space they have. + /// The RGB space they have (PDF/A, which allows no DeviceCMYK next to images' own profiles). Rgb, + /// DeviceCMYK, also when the file has no ICC-based CMYK space: CMYK colors are DeviceCMYK + /// ([`crate::output::ColorOut::device_cmyk`]). + AlwaysDeviceCmyk, } /// The ICC-based RGB colour spaces of `pdf`, each with the ICC-based CMYK one to blend in instead, @@ -352,6 +362,7 @@ fn icc_spaces(pdf: &[u8], own: Option, without: Without) -> Vec<(String, St Without::FirstCmyk => cmyk, Without::DeviceCmyk => cmyk.map(|_| "/CS/DeviceCMYK".to_string()), Without::Rgb => None, + Without::AlwaysDeviceCmyk => Some("/CS/DeviceCMYK".to_string()), }); let Some(cmyk) = cmyk else { return vec![] }; rgb.into_iter().map(|r| (r, cmyk.clone())).collect() @@ -435,6 +446,11 @@ mod tests { // profile's space; the first CMYK space when the document's profile isn't known. assert_eq!(icc_spaces(SPACES, None, Without::DeviceCmyk), [(rgb.clone(), "/CS/DeviceCMYK".to_string())]); assert_eq!(icc_spaces(SPACES, None, Without::Rgb), []); - assert_eq!(icc_spaces(SPACES, None, Without::FirstCmyk), [(rgb, "/CS 2 0 R".to_string())]); + assert_eq!(icc_spaces(SPACES, None, Without::FirstCmyk), [(rgb.clone(), "/CS 2 0 R".to_string())]); + // CMYK colors written as DeviceCMYK: groups blend there, with or without a CMYK ICC space. + assert_eq!(icc_spaces(SPACES, None, Without::AlwaysDeviceCmyk), [(rgb.clone(), "/CS/DeviceCMYK".to_string())]); + let rgb_only = b"%PDF-1.7\n1 0 obj\n[/ICCBased 4 0 R]\nendobj\n4 0 obj\n<>stream\n\nendstream\nendobj\n"; + assert_eq!(icc_spaces(rgb_only, None, Without::DeviceCmyk), []); + assert_eq!(icc_spaces(rgb_only, None, Without::AlwaysDeviceCmyk), [(rgb, "/CS/DeviceCMYK".to_string())]); } } diff --git a/crates/pdf/src/import/builder.rs b/crates/pdf/src/import/builder.rs index a9cd9ada7c..eb8742f2db 100644 --- a/crates/pdf/src/import/builder.rs +++ b/crates/pdf/src/import/builder.rs @@ -43,6 +43,7 @@ impl<'p> Builder<'p> { image_keys: HashMap::new(), raster_scales: HashMap::new(), cmyk_keys: HashSet::new(), + intent_cmyk: None, separation_paints: HashMap::new(), opaque: HashSet::new(), warnings: vec![], diff --git a/crates/pdf/src/import/device.rs b/crates/pdf/src/import/device.rs index 45ca7f7081..452090c6b6 100644 --- a/crates/pdf/src/import/device.rs +++ b/crates/pdf/src/import/device.rs @@ -1,4 +1,4 @@ -use super::entry::{INVISIBLE_TEXT_NOTE, MAX_NESTED, OUTLINED_TEXT_NOTE, UNSORTED, WHITE_KEY}; +use super::entry::{INTENT_KEY, INVISIBLE_TEXT_NOTE, MAX_NESTED, OUTLINED_TEXT_NOTE, UNSORTED, WHITE_KEY}; use super::state::{ Builder, Decoded, Frame, FrameKind, GlyphRun, blend, fill_rule, gray_png, line_width, mean_scale, resize_alpha, rgb_png, rgba_png, same_outline, stroke_layer, stroke_outline, @@ -242,8 +242,11 @@ impl<'a> Device<'a> for Builder<'_> { match image { Image::Raster(r) => { let white = self.white_images; + // A DeviceCMYK image takes the output intent's profile only where no DefaultCMYK + // replaces DeviceCMYK, so it is cached apart from the same image drawn where one does. + let intent = !white && self.intent_cmyk.is_some() && self.scan.cmyk_defaults.get(&r.stream().dict().obj_id()) == Some(&false); // Inside an alpha mask the same image is read again, white (its own cache key). - let key = craft_pdf::interpret::CacheKey::cache_key(&r) ^ if white { WHITE_KEY } else { 0 }; + let key = craft_pdf::interpret::CacheKey::cache_key(&r) ^ if white { WHITE_KEY } else { 0 } ^ if intent { INTENT_KEY } else { 0 }; let st = r.stream(); let (w, h) = (r.width(), r.height()); // CMYK images keep their samples (read once per image). @@ -251,7 +254,8 @@ impl<'a> Device<'a> for Builder<'_> { let cmyk = if known || white { None } else { - crate::import_image::cmyk(st, w, h).unwrap_or_else(|why| { + let intent = self.intent_cmyk.as_deref().filter(|_| intent); + crate::import_image::cmyk(st, w, h, intent).unwrap_or_else(|why| { self.warn(why); None }) diff --git a/crates/pdf/src/import/entry.rs b/crates/pdf/src/import/entry.rs index 8f84b9a332..5b945c6b25 100644 --- a/crates/pdf/src/import/entry.rs +++ b/crates/pdf/src/import/entry.rs @@ -9,6 +9,9 @@ use super::{ /// Mixed into an image's cache key when it is read white inside an alpha soft mask. pub(super) const WHITE_KEY: u128 = 0x7717_e000_a1fa; +/// Mixed into an image's cache key when a DeviceCMYK image there takes the output intent's profile. +pub(super) const INTENT_KEY: u128 = 0x1e7e_0c3c_0b5a; + /// The name of the paths text imports as. pub(super) const TEXT_OUTLINES: &str = ""; @@ -281,6 +284,7 @@ fn read_opened( b.unsure = route && ocgs.list.iter().any(|g| (all_on && !g.on) || !g.print); b.taken = taken; b.warnings = notes; + b.intent_cmyk = crate::import_image::output_intent_cmyk(pdf); b.colors.uncalibrated_rgb = opts.uncalibrated_rgb && picked.iter().filter_map(|&n| pages.get(n)).any(crate::pages::has_private_data); let cache = InterpreterCache::new(); let mut x = 0.0; diff --git a/crates/pdf/src/import/state.rs b/crates/pdf/src/import/state.rs index ba0c23a808..d8068279cf 100644 --- a/crates/pdf/src/import/state.rs +++ b/crates/pdf/src/import/state.rs @@ -103,6 +103,9 @@ pub(super) struct Builder<'p> { pub(super) raster_scales: HashMap, /// The images kept with their CMYK samples ([`crate::import_image`]). pub(super) cmyk_keys: HashSet, + /// The file's PDF/X output intent profile of CMYK, which DeviceCMYK images are tagged with + /// ([`crate::import_image::output_intent_cmyk`]). + pub(super) intent_cmyk: Option>, /// Images in a Separation space, by key: the paint of their ink, or `None` when they open in /// RGB (an ink that can't be told, tints that can't be read). pub(super) separation_paints: HashMap>, diff --git a/crates/pdf/src/import_image.rs b/crates/pdf/src/import_image.rs index cafae6d448..ecab9e6e08 100644 --- a/crates/pdf/src/import_image.rs +++ b/crates/pdf/src/import_image.rs @@ -5,15 +5,17 @@ //! ([`ImageBlob::cmyk_tiff`]). An ICC-based image keeps the CMYK profile its color space holds //! ([`icc_profile`]): the TIFF carries it, and a kept JPEG carries it in place of its own //! ([`jpeg_with_icc`]), or, when its segments can't hold it, is stored as a CMYK TIFF carrying it. +//! In a file with a PDF/X output intent of CMYK, a DeviceCMYK image keeps that intent's profile +//! the same way ([`output_intent_cmyk`]), since the intent describes DeviceCMYK there. //! A mask (`/SMask`, `/Mask`) doesn't change that: the importer //! carries it as the image's opacity mask ([`has_mask`]). A DeviceN image of process plates only //! keeps them the same way, as a CMYK image ([`process_devicen`]). An image of one ink (a //! Separation, or a DeviceN of one colorant) keeps it: its tints are read as a grayscale image //! ([`tint_gray`]) that the ink colorizes. Every other image is read as RGB by the interpreter. -use craft_pdf::syntax::Filter; use craft_pdf::syntax::object::stream::{ImageColorSpace, ImageDecodeParams}; use craft_pdf::syntax::object::{Array, Dict, Name, Stream}; +use craft_pdf::syntax::{Filter, Pdf}; use vectorcraft_doc::ImageBlob; use vectorcraft_doc::cmyk::{Inks, MAX_CMYK_PIXELS, jpeg_components, jpeg_with_icc}; @@ -55,7 +57,11 @@ fn icc_profile(d: &Dict<'_>) -> Option> { if it.next::>()?.as_ref() != b"ICCBased" { return None; } - let s = it.next::>()?; + cmyk_profile(&it.next::>()?) +} + +/// The four-component CMYK profile stream `s` holds, when an image can be tagged with it. +fn cmyk_profile(s: &Stream<'_>) -> Option> { if s.dict().get::(b"N") != Some(4) { return None; } @@ -64,6 +70,23 @@ fn icc_profile(d: &Dict<'_>) -> Option> { valid_icc(&icc, *b"CMYK").then(|| icc.into_owned()) } +/// The CMYK profile of the catalog's PDF/X output intent (`/S /GTS_PDFX` with a four-component +/// `DestOutputProfile`), which DeviceCMYK colors are in. `None` without one. +pub(crate) fn output_intent_cmyk(pdf: &Pdf) -> Option> { + let xref = pdf.xref(); + let intents = xref.get::>(xref.root_id())?.get::>(b"OutputIntents")?; + let pdfx = intents.iter::>().take(MAX_INTENTS).find(|i| i.get::>(b"S").is_some_and(|s| s.as_ref() == b"GTS_PDFX"))?; + cmyk_profile(&pdfx.get::>(b"DestOutputProfile")?) +} + +/// The output intents read before giving up on finding the PDF/X one. +const MAX_INTENTS: usize = 16; + +/// Is the image's color space DeviceCMYK (or its inline abbreviation)? +fn device_cmyk(d: &Dict<'_>) -> bool { + d.get::>(key(d, b"ColorSpace", b"CS")).is_some_and(|n| matches!(n.as_ref(), b"DeviceCMYK" | b"CMYK")) +} + /// Each component's Decode range (`[0 1]` each when the array is missing or malformed). fn decode_ranges(d: &Dict<'_>) -> [(f32, f32); 4] { let mut out = [(0.0, 1.0); 4]; @@ -78,14 +101,15 @@ fn decode_ranges(d: &Dict<'_>) -> [(f32, f32); 4] { } /// The image `st` (`width` × `height` pixels) in CMYK: `Ok(None)` when it isn't a CMYK image, -/// `Err` (a warning) when it is one that is read as RGB. -pub(crate) fn cmyk(st: &Stream<'_>, width: u32, height: u32) -> Result, &'static str> { +/// `Err` (a warning) when it is one that is read as RGB. `intent` is the file's PDF/X output intent +/// profile of CMYK ([`output_intent_cmyk`]), which a DeviceCMYK image is tagged with. +pub(crate) fn cmyk(st: &Stream<'_>, width: u32, height: u32, intent: Option<&[u8]>) -> Result, &'static str> { let d = st.dict(); if !cmyk_space(d) { return process_devicen(st, width, height); } let ranges = decode_ranges(d); - let icc = icc_profile(d); + let icc = icc_profile(d).or_else(|| intent.filter(|_| device_cmyk(d)).map(<[u8]>::to_vec)); let filters = st.filters(); if ranges == INVERTED && matches!(filters.as_slice(), [Filter::DctDecode]) { let raw = st.raw_data(); diff --git a/crates/pdf/src/import_scan.rs b/crates/pdf/src/import_scan.rs index b65254eafa..7f2e9cc161 100644 --- a/crates/pdf/src/import_scan.rs +++ b/crates/pdf/src/import_scan.rs @@ -280,6 +280,10 @@ pub(crate) struct Scan { /// Something overprints with overprint mode 0, where a `DeviceCMYK` colour's zero components /// knock out; the document's overprint is the nonzero one (mode 1). pub zero_mode: bool, + /// The images the page draws (image XObjects by object, inline images as `None`), each with + /// whether it is drawn where a `/DefaultCMYK` is in scope, which replaces DeviceCMYK there + /// (ISO 32000-2 §8.6.5.6). An image drawn both ways is `true`. + pub cmyk_defaults: HashMap, bool>, /// The colorant names of the Separation and DeviceN spaces the page sets (`cs`, `CS`), and of /// those of the shading patterns it sets (`scn`, `SCN`) and of the shadings it draws (`sh`), /// each once (none when the page uses more than [`MAX_INKS`] inks or changes ink more than @@ -663,53 +667,23 @@ impl Walker<'_, '_> { self.out.type3_cache_map.insert(hash, (f_key, to_unicode)); } } - let is_colour = if is_type3 { - let mut colour = false; - let mut seen_streams = HashSet::new(); - let mut decoded_bytes = 0usize; - const MAX_CHARPROC_BYTES: usize = 16 << 20; - if let Some(char_procs) = f.get::>(b"CharProcs") { - for key in char_procs.keys() { - if let Some(stream) = char_procs.get::>(key.as_ref()) { - if !seen_streams.insert(stream.cache_key()) { - continue; - } - if decoded_bytes >= MAX_CHARPROC_BYTES { - colour = true; - break; - } - if let Ok(data) = stream.decoded_within(MAX_CHARPROC_BYTES.saturating_sub(decoded_bytes)) { - decoded_bytes = decoded_bytes.saturating_add(data.len()); - let mut iter = TypedIter::new(data.as_ref()); - while let Some(op) = iter.next() { - match op { - TypedInstruction::ColorGlyph(_) => { - colour = true; - break; - } - TypedInstruction::ShapeGlyph(_) => break, - _ => {} - } - } - if colour { - break; - } - } - } - } - } - colour - } else { - false - }; + // A font is noted once for the document, so its glyph procedures are read only the + // first time any page or form lists it. self.fonts.entry(f_key).or_insert_with(|| { let embedded = embeds_glyphs(&f); + let is_colour = is_type3 && sets_glyph_colors(&f); FontNote { name, embedded, vertical: vertical_metrics(&f, embedded), is_type3, to_unicode, is_colour } }); } } } + /// An image drawn with `res` in scope, as the interpreter looks up its `/DefaultCMYK`. + fn drawn_image(&mut self, id: Option, res: &Resources<'_>) { + let default = res.get_color_space(&Name::new_unescaped(b"DefaultCMYK")).is_some(); + *self.out.cmyk_defaults.entry(id).or_default() |= default; + } + fn walk(&mut self, data: &[u8], res: &Resources<'_>, depth: u32) { let mut iter = TypedIter::new(data); self.note_fonts(res); @@ -874,12 +848,17 @@ impl Walker<'_, '_> { | TypedInstruction::ShowTexts(_) | TypedInstruction::NextLineAndShowText(_) | TypedInstruction::ShowTextWithParameters(_) => self.shown(), + TypedInstruction::InlineImage(_) => self.drawn_image(None, res), TypedInstruction::XObject(x) => { if !self.is_visible() { continue; } let Some(s) = res.get_x_object(x.0) else { continue }; let d = s.dict(); + if d.get::>(b"Subtype").as_deref() == Some(b"Image") { + self.drawn_image(d.obj_id(), res); + continue; + } if d.get::>(b"Subtype").as_deref() != Some(b"Form") || d.get::<[f32; 4]>(b"BBox").is_none() { continue; } @@ -1108,6 +1087,48 @@ fn font_name(f: &Dict<'_>) -> Option { Some(stripped.unwrap_or(base)) } +/// The most bytes of a Type 3 font's glyph procedures decoded to look for colored glyphs. +const MAX_CHARPROC_BYTES: usize = 16 << 20; + +// The glyph procedures decoded by `sets_glyph_colors` on this thread. +#[cfg(test)] +thread_local! { + pub(crate) static TEST_CHARPROC_DECODES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Whether Type 3 font `f` has a glyph procedure that sets its own color (`d0`, ISO 32000-1 +/// §9.6.5): its procedures are read until one starts with `d0`, each up to its `d0` or `d1`. Past +/// [`MAX_CHARPROC_BYTES`] of them the font is taken to have one. +fn sets_glyph_colors(f: &Dict<'_>) -> bool { + let Some(char_procs) = f.get::>(b"CharProcs") else { return false }; + let mut seen_streams = HashSet::new(); + let mut decoded_bytes = 0usize; + for key in char_procs.keys() { + if let Some(stream) = char_procs.get::>(key.as_ref()) { + if !seen_streams.insert(stream.cache_key()) { + continue; + } + if decoded_bytes >= MAX_CHARPROC_BYTES { + return true; + } + #[cfg(test)] + TEST_CHARPROC_DECODES.with(|n| n.set(n.get() + 1)); + if let Ok(data) = stream.decoded_within(MAX_CHARPROC_BYTES.saturating_sub(decoded_bytes)) { + decoded_bytes = decoded_bytes.saturating_add(data.len()); + let mut iter = TypedIter::new(data.as_ref()); + while let Some(op) = iter.next() { + match op { + TypedInstruction::ColorGlyph(_) => return true, + TypedInstruction::ShapeGlyph(_) => break, + _ => {} + } + } + } + } + } + false +} + /// Whether font `f` carries its own glyphs: a font program in its descriptor (a composite font's in /// its descendant's), or a Type 3 font's glyph procedures. A font that doesn't is drawn with a /// stand-in, whose glyphs say nothing about which installed face the document means. diff --git a/crates/pdf/src/output.rs b/crates/pdf/src/output.rs index f5e4bb6e36..83104215c2 100644 --- a/crates/pdf/src/output.rs +++ b/crates/pdf/src/output.rs @@ -25,12 +25,17 @@ //! document's), RGB with sRGB (colours of another RGB space as their sRGB equivalents) and grey //! with the sRGB tone curve. Otherwise they are device colours. PDF/A, PDF/X-3 and PDF/X-4 //! always tag them, whatever `profiles` says; PDF/X-1a never does, and always converts to a -//! CMYK destination (see [`crate::pdfx`]). A CMYK image that keeps its numbers is tagged with -//! the CMYK profile it carries, if any, with `all` and `taggedSource`, and in PDF/A, PDF/X-3 -//! and PDF/X-4 unless `profiles` is `destination` ([`ColorOut::cmyk_image_icc`]). When +//! CMYK destination (see [`crate::pdfx`]). In PDF/X-3 and PDF/X-4, CMYK colors in the profile +//! of a CMYK output intent are DeviceCMYK, and so are all CMYK colors with `none`, unless +//! colors are converted to a CMYK destination of another profile ([`ColorOut::device_cmyk`]). +//! A CMYK image that keeps +//! its numbers is tagged with the CMYK profile it carries, if any, with `all` and +//! `taggedSource`, and in PDF/A, PDF/X-3 and PDF/X-4 unless `profiles` is `destination` +//! ([`ColorOut::cmyk_image_icc`]); not when that profile is a DeviceCMYK output intent's. When //! `profiles` isn't set, colors are written as with `none` and gray and RGB images keep the //! profiles they carry (but in PDF/X-1a); when it is set to `none`, no image keeps its own -//! profile, a JPEG's `ICC_PROFILE` segments included, except in PDF/A, PDF/X-3 and PDF/X-4 +//! profile, a JPEG's `ICC_PROFILE` segments included, except in PDF/A, PDF/X-3 and PDF/X-4, +//! where CMYK images lose theirs only when CMYK colors are DeviceCMYK //! ([`ColorOut::source_profiles`]). //! - Output intent: the profile `outputIntent` names, embedded as the `/GTS_PDFX` output intent //! of the catalog with the condition, identifier and registry; Trapped goes in the document @@ -82,6 +87,13 @@ pub(crate) struct ColorOut { no_profiles: bool, /// The CMYK profile that tags CMYK colours. cmyk_profile: String, + /// CMYK colors are written as DeviceCMYK although colors are tagged + /// ([`Self::device_cmyk`]): the profile of the CMYK output intent they are in, embedded once + /// as its `DestOutputProfile`. + device_icc: Option>, + /// With [`Self::device_icc`], CMYK images are untagged too, whatever profile they carry + /// (`profiles` is `none`). + untag_cmyk_images: bool, /// Tagged RGB colours are written as their sRGB equivalents: why (a warning), when their RGB /// space isn't sRGB. pub srgb_note: Option, @@ -132,6 +144,8 @@ impl Default for ColorOut { image_icc: false, no_profiles: false, cmyk_profile, + device_icc: None, + untag_cmyk_images: false, srgb_note: None, pixels: OnceLock::new(), tagged_pixels: OnceLock::new(), @@ -290,9 +304,32 @@ impl ColorOut { } out.catalog = catalog(set, &out.cmyk_profile); out.standard = set.standard; + // In PDF/X-3 and PDF/X-4 the CMYK output intent characterizes DeviceCMYK: CMYK colors in + // its profile are written as DeviceCMYK, and with `none` every CMYK color is, unless + // colors are converted to a CMYK destination of another profile. Files without a standard + // keep the tags that `profiles` asks for. + let intent_cmyk = out.catalog.as_ref().and_then(|c| c.intent.as_ref()?.profile.as_ref()).filter(|(_, n)| *n == 4); + let none = set.output.profiles == Some(ProfileInclusion::None); + let to_cmyk = out.dest.as_ref().is_some_and(|d| d.model == Model::Cmyk); + if out.tagged + && set.standard.is_pdfx() + && let Some(intent) = intent_cmyk.and_then(|(name, _)| cms::icc_bytes(name).ok()) + && ((none && !to_cmyk) || cms::icc_bytes(&out.cmyk_profile).is_ok_and(|own| own == intent)) + { + out.device_icc = Some(intent); + out.untag_cmyk_images = none; + } Ok(out) } + /// CMYK colors are written as DeviceCMYK although colors are tagged, in PDF/X-3 and PDF/X-4 + /// with a CMYK output intent: its profile is the one they are in, or `profiles` is `none` and + /// there is no CMYK destination of another profile. RGB and gray colors stay tagged, and + /// so does a CMYK image that carries another profile, except with `none`. + pub(crate) fn device_cmyk(&self) -> bool { + self.device_icc.is_some() + } + /// Transparency blends in CMYK: converting to CMYK, or (without conversion) in a CMYK /// document (`cmyk`). pub(crate) fn blends_cmyk(&self, cmyk: bool) -> bool { @@ -415,22 +452,29 @@ impl ColorOut { /// The CMYK profile CMYK image `blob` is tagged with ([`crate::images::cmyk_icc`]): the one it /// carries, when its numbers are kept and the Profiles setting or the standard includes source - /// profiles. `None` otherwise, and in PDF/X-1a, whose images are untagged CMYK. + /// profiles. `None` otherwise, and in PDF/X-1a, whose images are untagged CMYK. When CMYK + /// colors are DeviceCMYK ([`Self::device_cmyk`]), an image that carries the output intent's + /// profile is untagged too, and so is every CMYK image with `none`. pub(crate) fn cmyk_image_icc(&self, blob: &vectorcraft_doc::ImageBlob) -> Option> { if !self.image_icc || self.cmyk_pixels().is_some() { return None; } - crate::images::cmyk_icc(blob) + let icc = crate::images::cmyk_icc(blob)?; + match &self.device_icc { + Some(intent) if self.untag_cmyk_images || icc == **intent => None, + _ => Some(icc), + } } /// How CMYK image `blob` is tagged ([`crate::images::recode_cmyk`]): with the profile /// [`Self::cmyk_image_icc`] gives (`icc`), else untagged, without a JPEG's own `ICC_PROFILE` - /// segments when Don't Include Profiles was set. + /// segments when Don't Include Profiles was set or CMYK colors are DeviceCMYK + /// ([`Self::device_cmyk`]). pub(crate) fn cmyk_tag<'a>(&self, icc: Option<&'a [u8]>) -> crate::images::CmykTag<'a> { use crate::images::CmykTag; match icc { Some(icc) => CmykTag::Profile(icc), - None if self.no_profiles => CmykTag::Removed, + None if self.no_profiles || self.device_cmyk() => CmykTag::Removed, None => CmykTag::Untagged, } } 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/patch.rs b/crates/pdf/src/patch.rs index 8b9d69b908..9235f22cea 100644 --- a/crates/pdf/src/patch.rs +++ b/crates/pdf/src/patch.rs @@ -107,6 +107,42 @@ impl Xref { /// A replacement of bytes `start..end` of the file. type Edit = (usize, usize, Vec); +/// Where byte offsets of the old file land in the new one, for edits sorted by start that do not +/// overlap, whose ends therefore never decrease. +struct Moves { + /// Each edit's end, in order. + ends: Vec, + /// The change in length made by the edits up to and including each one. + shifts: Vec, +} + +impl Moves { + /// `None` when a change in length doesn't fit an `isize`. + fn new(edits: &[Edit]) -> Option { + let mut total: isize = 0; + let mut shifts = Vec::with_capacity(edits.len()); + for (start, end, new) in edits { + let removed = isize::try_from(end.checked_sub(*start)?).ok()?; + total = total.checked_add(isize::try_from(new.len()).ok()?)?.checked_sub(removed)?; + shifts.push(total); + } + Some(Self { ends: edits.iter().map(|e| e.1).collect(), shifts }) + } + + /// Where `off` lands: moved by every edit that ends at or before it. + fn at(&self, off: usize) -> Option { + match self.ends.partition_point(|&end| end <= off) { + 0 => Some(off), + n => off.checked_add_signed(*self.shifts.get(n - 1)?), + } + } +} + +/// `off` as the ten digits of a cross-reference entry; `None` past what ten digits hold. +fn entry_offset(off: usize) -> Option { + (u64::try_from(off).ok()? < 10_000_000_000).then(|| format!("{off:010}")) +} + /// The edits of one PDF, applied together by [`Self::apply`]. pub(crate) struct Patch { edits: Vec, @@ -139,18 +175,17 @@ impl Patch { } /// `pdf` with the edits, new objects and trailer entries, and a cross-reference table that - /// matches. Refused when an edit overlaps another or reaches past the objects. + /// matches. Refused when an edit overlaps another or reaches past the objects, or when an + /// object would start past the ten digits a cross-reference entry gives its offset in. pub fn apply(mut self, pdf: &[u8], xref: &Xref) -> Result, PdfError> { let bad = |why: &str| PdfError::Write(format!("can't edit the written PDF: {why}")); self.edits.sort_by_key(|e| (e.0, e.1)); if self.edits.windows(2).any(|w| w[0].1 > w[1].0) || self.edits.iter().any(|e| e.0 > e.1 || e.1 > xref.at) { return Err(bad("edits overlap")); } - // Where a byte offset of the old file lands in the new one. let edits = &self.edits; - let moved = |off: usize| -> usize { - edits.iter().filter(|e| e.1 <= off).fold(off as isize, |o, e| o + e.2.len() as isize - (e.1 - e.0) as isize) as usize - }; + let moves = Moves::new(edits).ok_or_else(|| bad("edits too large"))?; + let too_far = || bad("an object lies past what the cross-reference table holds"); let added: usize = self.edits.iter().map(|e| e.2.len()).sum::() + self.objects.iter().map(|o| o.len() + 32).sum::(); let mut out = Vec::with_capacity(pdf.len() + added + 64); let mut at = 0; @@ -175,7 +210,7 @@ impl Patch { for e in old.chunks(20) { match number(e, 0) { Some((off, _)) if e.get(17) == Some(&b'n') => { - out.extend_from_slice(format!("{:010}", moved(off)).as_bytes()); + out.extend_from_slice(moves.at(off).and_then(entry_offset).ok_or_else(too_far)?.as_bytes()); out.extend_from_slice(e.get(10..).unwrap_or_default()); } _ => out.extend_from_slice(e), @@ -183,7 +218,8 @@ impl Patch { } let eol = old.get(18..20).unwrap_or(b"\r\n"); for off in offsets { - out.extend_from_slice(format!("{off:010} 00000 n").as_bytes()); + out.extend_from_slice(entry_offset(off).ok_or_else(too_far)?.as_bytes()); + out.extend_from_slice(b" 00000 n"); out.extend_from_slice(eol); } // The trailer, with its size and the new entries. @@ -201,3 +237,279 @@ impl Patch { Ok(out) } } + +#[cfg(test)] +mod tests { + use super::*; + use std::time::{Duration, Instant}; + + /// A PDF written as the export writes one: objects `<< /N n >>` numbered from 1, those `free` + /// picks left out with a free entry, then one cross-reference table and the trailer. + fn written(count: usize, free: impl Fn(usize) -> bool) -> Vec { + let mut pdf = b"%PDF-1.7\n".to_vec(); + let mut entries = b"0000000000 65535 f\r\n".to_vec(); + for n in 1..=count { + if free(n) { + entries.extend_from_slice(b"0000000000 00001 f\r\n"); + continue; + } + entries.extend(format!("{:010} 00000 n\r\n", pdf.len()).bytes()); + pdf.extend(format!("{n} 0 obj\n<< /N {n} >>\nendobj\n").bytes()); + } + let at = pdf.len(); + pdf.extend(format!("xref\n0 {}\n", count + 1).bytes()); + pdf.extend(entries); + pdf.extend(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{at}\n%%EOF", count + 1).bytes()); + pdf + } + + /// A small linear congruential generator, so every run makes the same edits. + struct Rng(u64); + + impl Rng { + /// A number in `0..n` (0 when `n` is 0). + fn below(&mut self, n: usize) -> usize { + self.0 = self.0.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407); + usize::try_from(self.0 >> 33).unwrap() % n.max(1) + } + + fn bytes(&mut self) -> Vec { + (0..self.below(9)).map(|i| b'a' + u8::try_from(i).unwrap()).collect() + } + } + + /// About `wanted` edits that don't overlap, in shuffled order, at random places among the + /// objects and at object starts: replacements that grow, shrink or remove bytes, edits that end + /// at an object's start, and inserts, several of them at one place. None when `wanted` is 0. + fn edits(pdf: &[u8], xref: &Xref, rng: &mut Rng, wanted: usize) -> Vec { + if wanted == 0 { + return vec![]; + } + let first = b"%PDF-1.7\n".len(); + let mut points: Vec = xref.objects(pdf).into_iter().map(|(_, off)| off).collect(); + points.extend((0..wanted).map(|_| first + rng.below(xref.at() - first + 1))); + points.push(xref.at()); + points.sort_unstable(); + points.dedup(); + let mut out = vec![]; + for w in points.windows(2) { + let (p, q) = (w[0], w[1]); + match rng.below(6) { + 0 => {} + 1 => out.push((p, q, rng.bytes())), + 2 => out.push((p, p, rng.bytes())), + 3 => { + out.push((p, p, rng.bytes())); + out.push((p, p, rng.bytes())); + out.push((p, q.min(p + rng.below(4)), rng.bytes())); + } + 4 => out.push((p + (q - p) / 2, q, rng.bytes())), + _ => out.push((q, q, rng.bytes())), + } + } + for i in (1..out.len()).rev() { + out.swap(i, rng.below(i + 1)); + } + out + } + + fn patch(xref: &Xref, edits: &[Edit], objects: bool) -> Patch { + let mut patch = Patch::new(xref); + for (start, end, with) in edits { + patch.replace(*start, *end, with.clone()); + } + if objects { + patch.add_object(b"<< /Added 1 >>".to_vec()); + patch.trailer_entry(b" /Info 2 0 R"); + } + patch + } + + /// Where `off` lands, by walking every edit: how [`Patch::apply`] found it before [`Moves`]. + fn scan(edits: &[Edit], off: usize) -> usize { + edits.iter().filter(|e| e.1 <= off).fold(off as isize, |o, e| o + e.2.len() as isize - (e.1 - e.0) as isize) as usize + } + + /// [`Patch::apply`] as it was written before [`Moves`], walking every edit for every object. + fn apply_by_scan(mut patch: Patch, pdf: &[u8], xref: &Xref) -> Result, PdfError> { + let bad = |why: &str| PdfError::Write(format!("can't edit the written PDF: {why}")); + patch.edits.sort_by_key(|e| (e.0, e.1)); + if patch.edits.windows(2).any(|w| w[0].1 > w[1].0) || patch.edits.iter().any(|e| e.0 > e.1 || e.1 > xref.at) { + return Err(bad("edits overlap")); + } + let edits = &patch.edits; + let moved = |off: usize| -> usize { scan(edits, off) }; + let added: usize = patch.edits.iter().map(|e| e.2.len()).sum::() + patch.objects.iter().map(|o| o.len() + 32).sum::(); + let mut out = Vec::with_capacity(pdf.len() + added + 64); + let mut at = 0; + for (start, end, new) in edits.iter() { + out.extend_from_slice(pdf.get(at..*start).ok_or_else(|| bad("bad edit"))?); + out.extend_from_slice(new); + at = *end; + } + out.extend_from_slice(pdf.get(at..xref.at).ok_or_else(|| bad("bad edit"))?); + let mut offsets = Vec::with_capacity(patch.objects.len()); + for (i, body) in patch.objects.iter().enumerate() { + offsets.push(out.len()); + out.extend_from_slice(format!("{} 0 obj\n", patch.size + i).as_bytes()); + out.extend_from_slice(body); + out.extend_from_slice(b"\nendobj\n"); + } + let table = out.len(); + let size = patch.size + patch.objects.len(); + out.extend_from_slice(format!("xref\n0 {size}\n").as_bytes()); + let old = pdf.get(xref.entries..xref.entries + 20 * xref.count).ok_or_else(|| bad("bad cross-reference table"))?; + for e in old.chunks(20) { + match number(e, 0) { + Some((off, _)) if e.get(17) == Some(&b'n') => { + out.extend_from_slice(format!("{:010}", moved(off)).as_bytes()); + out.extend_from_slice(e.get(10..).unwrap_or_default()); + } + _ => out.extend_from_slice(e), + } + } + let eol = old.get(18..20).unwrap_or(b"\r\n"); + for off in offsets { + out.extend_from_slice(format!("{off:010} 00000 n").as_bytes()); + out.extend_from_slice(eol); + } + let (ts, te) = xref.trailer; + let dict = pdf.get(ts..te.saturating_sub(2)).ok_or_else(|| bad("bad trailer"))?; + let size_at = find(dict, b"/Size", 0).ok_or_else(|| bad("the trailer has no size"))? + 5; + let (_, size_end) = number(dict, size_at).ok_or_else(|| bad("the trailer has no size"))?; + let (Some(head), Some(tail)) = (dict.get(..size_at), dict.get(size_end..)) else { return Err(bad("bad trailer")) }; + out.extend_from_slice(b"trailer\n"); + out.extend_from_slice(head); + out.extend_from_slice(format!(" {size}").as_bytes()); + out.extend_from_slice(tail); + out.extend_from_slice(&patch.trailer); + out.extend_from_slice(format!(">>\nstartxref\n{table}\n%%EOF").as_bytes()); + Ok(out) + } + + #[test] + fn every_offset_moves_by_the_edits_that_end_at_or_before_it() { + let mut rng = Rng(7661); + for round in 0..100 { + let pdf = written(1 + rng.below(30), |n| n % 7 == 3); + let xref = Xref::read(&pdf).unwrap(); + let mut edits = edits(&pdf, &xref, &mut rng, [0, 1, 3, 20, 80][round % 5]); + edits.sort_by_key(|e| (e.0, e.1)); + let moves = Moves::new(&edits).unwrap(); + for off in 0..=pdf.len() { + assert_eq!(moves.at(off), Some(scan(&edits, off)), "round {round}, offset {off}, edits {edits:?}"); + } + } + } + + #[test] + fn apply_writes_the_bytes_a_walk_of_every_edit_wrote() { + let mut rng = Rng(1378); + for round in 0..300 { + let pdf = written(1 + rng.below(40), |n| n % 7 == 3); + let xref = Xref::read(&pdf).unwrap(); + let edits = edits(&pdf, &xref, &mut rng, [0, 1, 3, 20, 80][round % 5]); + let objects = round % 3 == 0; + let fast = patch(&xref, &edits, objects).apply(&pdf, &xref).unwrap(); + let walked = apply_by_scan(patch(&xref, &edits, objects), &pdf, &xref).unwrap(); + assert_eq!(String::from_utf8_lossy(&fast), String::from_utf8_lossy(&walked), "round {round}"); + } + } + + #[test] + fn every_entry_points_at_its_object_after_the_edits() { + let pdf = written(30, |n| n % 7 == 3); + let xref = Xref::read(&pdf).unwrap(); + let mut patch = Patch::new(&xref); + for (n, off) in xref.objects(&pdf) { + let (at, end) = xref.dict(&pdf, n).unwrap(); + match n % 4 { + 0 => patch.replace(at, at, b" /Grown [1 2 3]".to_vec()), + 1 => patch.replace(at, end, b">>\n".to_vec()), + // An insert at an object's start goes before the object. + 2 => patch.replace(off, off, b"% before\n".to_vec()), + _ => {} + } + } + let added = patch.add_object(b"<< /Added 1 >>".to_vec()); + let out = patch.apply(&pdf, &xref).unwrap(); + let after = Xref::read(&out).unwrap(); + assert_eq!((after.count(), added), (32, 31)); + for n in 1..32u32 { + let Some(off) = after.offset(&out, n) else { + assert!(n % 7 == 3, "object {n} is in use"); + let e = xref.entries + 20 * n as usize; + assert_eq!(out[after.entries + 20 * n as usize..][..20], pdf[e..e + 20], "free entry {n}"); + continue; + }; + assert!(out[off..].starts_with(format!("{n} 0 obj\n").as_bytes()), "object {n} at {off}"); + } + } + + #[test] + fn an_object_moved_past_ten_digits_is_refused() { + let mut pdf = written(2, |_| false); + let entry = Xref::read(&pdf).unwrap().entries + 40; + // Object 2's entry gives the last offset ten digits hold. + pdf[entry..entry + 10].copy_from_slice(b"9999999999"); + let xref = Xref::read(&pdf).unwrap(); + let out = Patch::new(&xref).apply(&pdf, &xref).unwrap(); + assert!(find(&out, b"9999999999 00000 n\r\n", 0).is_some()); + let mut patch = Patch::new(&xref); + patch.replace(9, 9, b"%\n".to_vec()); + let refused = patch.apply(&pdf, &xref); + assert!(matches!(&refused, Err(PdfError::Write(why)) if why.contains("cross-reference table holds")), "{refused:?}"); + } + + /// CPU time this thread has used, where the system reports it (`/proc` on Linux). + 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) + } + + /// How long `f` takes, in thread CPU time where the system reports it, else wall time. + fn time(f: impl FnOnce() -> T) -> (Duration, T) { + let (cpu, wall) = (thread_cpu(), Instant::now()); + let out = f(); + (thread_cpu().zip(cpu).map_or_else(|| wall.elapsed(), |(b, a)| b.saturating_sub(a)), out) + } + + fn median(mut runs: Vec) -> Duration { + runs.sort_unstable(); + runs[runs.len() / 2] + } + + /// `cargo test --release -p vectorcraft-pdf --lib patch::tests::bench -- --ignored --nocapture`. + /// The edits are those of forms in overprint: two inside each form's stream (its `/Length` and + /// data) and an insert into its dictionary, for `n` forms among `n + 20` objects. Each run + /// applies the patch `reps` times, so that small files take long enough for the clock. + #[test] + #[ignore = "timing; run explicitly"] + fn bench_apply_with_many_edits() { + println!("clock: {}", if thread_cpu().is_some() { "thread CPU time" } else { "wall time" }); + println!("| forms | objects | edits | walk every edit (median of 7) | binary search (median of 7) |"); + println!("| ---: | ---: | ---: | ---: | ---: |"); + for n in [100, 1_000, 5_000, 20_000] { + let pdf = written(n + 20, |_| false); + let xref = Xref::read(&pdf).unwrap(); + let mut edits = vec![]; + for (obj, _) in xref.objects(&pdf).into_iter().take(n) { + let (at, _) = xref.dict(&pdf, obj).unwrap(); + edits.push((at, at + 1, b" /Length 120 ".to_vec())); + edits.push((at + 1, at + 3, b"/Data".to_vec())); + edits.push((at + 3, at + 3, b" /Resources << /ExtGState << /GS0 9 0 R >> >>".to_vec())); + } + let reps = (200_000_000 / (3 * n * n)).clamp(1, 2_000); + let (mut walked, mut searched) = (vec![], vec![]); + for _ in 0..7 { + let (t, old) = time(|| (0..reps).fold(None, |_, _| apply_by_scan(patch(&xref, &edits, false), &pdf, &xref).ok())); + walked.push(t); + let (t, new) = time(|| (0..reps).fold(None, |_, _| patch(&xref, &edits, false).apply(&pdf, &xref).ok())); + searched.push(t); + assert!(old.is_some() && old == new, "{n} forms: the files differ"); + } + let ms = |d: Duration| d.as_secs_f64() * 1000.0 / reps as f64; + println!("| {n} | {} | {} | {:.3} ms | {:.3} ms |", n + 20, edits.len(), ms(median(walked)), ms(median(searched))); + } + } +} diff --git a/crates/pdf/src/pdfx.rs b/crates/pdf/src/pdfx.rs index 2313d62129..67c71d5dbc 100644 --- a/crates/pdf/src/pdfx.rs +++ b/crates/pdf/src/pdfx.rs @@ -4,9 +4,11 @@ //! - PDF/X-1a:2001: every colour is CMYK, grey or a spot ink with a CMYK alternate (colours and //! images are converted to a CMYK destination and written untagged, see [`crate::output`]), no //! transparency (the app flattens it before writing), no layers, PDF 1.3. -//! - PDF/X-3:2002: colours are ICC-based (always tagged), no transparency, no layers, PDF 1.3. -//! - PDF/X-4:2010: transparency and layers are kept, colours are tagged, PDF 1.6 at most, and the -//! XMP metadata names the standard too and carries `xmp:MetadataDate`. +//! - PDF/X-3:2002: colors are ICC-based (always tagged), except CMYK colors in the CMYK output +//! intent's profile, which are DeviceCMYK (with `profiles` `none`, all CMYK colors unless they +//! are converted to a CMYK destination of another profile), no transparency, no layers, PDF 1.3. +//! - PDF/X-4:2010: transparency and layers are kept, colors are tagged as in PDF/X-3, PDF 1.6 at +//! most, and the XMP metadata names the standard too and carries `xmp:MetadataDate`. //! - All of them: a `/GTS_PDFX` output intent (blank, the CMYK profile in effect, embedded), a //! TrimBox on every page (the artboard), `/Trapped` True or False, `/GTS_PDFXVersion` in the //! document information, a title and dates, embedded fonts (or text as outlines), no editing diff --git a/crates/pdf/src/print/plates.rs b/crates/pdf/src/print/plates.rs index 74102373e5..5b33683dcf 100644 --- a/crates/pdf/src/print/plates.rs +++ b/crates/pdf/src/print/plates.rs @@ -171,10 +171,11 @@ impl<'a> Separator<'a> { /// swatch link). Any ink above zero puts ink down, except on PostScript plates for a color that /// counts as 100% black ([`vectorcraft_doc::overprint::is_black_ink`], as /// [`vectorcraft_doc::overprint::OverprintBlack::default`] judges it) and is not linked to a - /// spot swatch, to Registration or to a swatch the document lacks: up to the half a percent of - /// another ink such a black may carry counts as none. + /// spot swatch or to Registration: up to the half a percent of another ink such a black may + /// carry counts as none. A link to a swatch the document lacks separates as the color's own + /// values, so such a black counts as unlinked. fn no_ink(&self, plate: &str, p: &Paint) -> bool { - let process = |swatch: Option<&str>| swatch.is_none_or(|n| n != REGISTRATION && self.doc.swatch(n).is_some_and(|w| !w.spot)); + let process = |swatch: Option<&str>| swatch.is_none_or(|n| n != REGISTRATION && self.doc.swatch(n).is_none_or(|w| !w.spot)); let none = |c: &Color, process: bool, ink: f32| ink <= 0.0 || (self.postscript && process && ink <= 0.005 && is_black_ink(c, 1.0, false)); match p { Paint::Solid { color, swatch, tint } => { 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/cmykimages.rs b/crates/pdf/src/tests/cmykimages.rs index 4d22a10ee6..ec157a8182 100644 --- a/crates/pdf/src/tests/cmykimages.rs +++ b/crates/pdf/src/tests/cmykimages.rs @@ -36,21 +36,33 @@ fn stream(dict: &str, data: &[u8]) -> Vec { /// A 300 × 100 pt page with a CMYK rectangle and image XObjects `images` (dictionary entries /// after the type, stream data), 50 pt wide each: objects 5…, then the `extra` objects. fn pdf_with_images(images: &[(String, Vec)], extra: &[Vec]) -> Vec { + pdf_with(images, extra, "", "") +} + +/// [`pdf_with_images`] with `catalog` added to the catalog's entries and `resources` to the +/// page's resources. +fn pdf_with(images: &[(String, Vec)], extra: &[Vec], catalog: &str, resources: &str) -> Vec { let xobjects: String = (0..images.len()).map(|i| format!("/Im{i} {} 0 R ", 5 + i)).collect(); let mut content = String::from("0 1 0.6 0.2 k 0 80 300 20 re f\n"); for i in 0..images.len() { content.push_str(&format!("q 50 0 0 50 {} 10 cm /Im{i} Do Q\n", 10 + 60 * i)); } let mut objs = vec![ - b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(), + format!("<< /Type /Catalog /Pages 2 0 R {catalog}>>").into_bytes(), b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(), - format!("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 100] /Resources << /XObject << {xobjects}>> >> /Contents 4 0 R >>").into_bytes(), + format!("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 100] /Resources << /XObject << {xobjects}>> {resources}>> /Contents 4 0 R >>") + .into_bytes(), stream("", content.as_bytes()), ]; for (dict, data) in images { objs.push(stream(&format!("/Type /XObject /Subtype /Image {dict}"), data)); } objs.extend_from_slice(extra); + pdf_of(&objs) +} + +/// A PDF file of `objs`, numbered from 1, whose catalog is object 1. +fn pdf_of(objs: &[Vec]) -> Vec { let mut out = b"%PDF-1.4\n".to_vec(); let mut at = vec![]; for (i, o) in objs.iter().enumerate() { @@ -164,8 +176,9 @@ fn a_cmyk_jpeg_passes_through_open_and_every_pdf_export() { (json!({}), "DeviceCMYK", None), (json!({"output": {"conversion": "preserveNumbers"}}), "DeviceCMYK", None), (json!({"standard": "pdfX1a"}), "DeviceCMYK", None), - (json!({"standard": "pdfX3"}), "ICCBased", Some(4)), - (json!({"standard": "pdfX4"}), "ICCBased", Some(4)), + // CMYK in the output intent's profile (the CMYK profile in effect) is DeviceCMYK. + (json!({"standard": "pdfX3"}), "DeviceCMYK", None), + (json!({"standard": "pdfX4"}), "DeviceCMYK", None), (json!({"output": {"profiles": "all"}}), "ICCBased", Some(4)), ] { let out = export_with_report(&r.document, &opts(settings.clone())).unwrap(); @@ -178,12 +191,14 @@ fn a_cmyk_jpeg_passes_through_open_and_every_pdf_export() { assert!(out.warnings.iter().all(|w| !w.contains("image")), "{settings}: {:?}", out.warnings); // And open again: the same JPEG, carrying the profile it was written in when it was // ICC-based. + // ICC-based, or DeviceCMYK in a PDF/X file, whose output intent's profile it then carries. let back = import(&out.bytes).unwrap(); let blob = blobs(&back)[0]; - if icc_n.is_some() { + let intent = settings.get("standard").is_some().then(|| cms::icc_bytes(&cms::active_settings().cmyk).unwrap().to_vec()); + if let Some(icc) = w[0].icc.clone().or(intent) { assert_eq!(blob.mime, "image/jpeg", "{settings}"); assert_eq!(blob.cmyk(), b[0].cmyk(), "{settings}: the same samples"); - assert_eq!(blob.cmyk_icc_profile(), w[0].icc, "{settings}: the profile it was written in"); + assert_eq!(blob.cmyk_icc_profile().as_deref(), Some(&*icc), "{settings}: the profile it was written in"); } else { assert_eq!(blob.bytes.as_slice(), jpg.as_slice(), "{settings}"); } @@ -645,6 +660,117 @@ fn a_cmyk_image_that_keeps_its_numbers_carries_its_cmyk_profile() { assert!(!String::from_utf8_lossy(&bytes).contains("/S/Luminosity"), "no luminosity soft mask"); } +/// When CMYK colors are DeviceCMYK in the output intent's profile, a CMYK image that carries that +/// profile is DeviceCMYK too, and with `none` so is one that carries another profile; elsewhere +/// it keeps its own (#1954). +#[test] +fn a_cmyk_image_in_the_output_intents_profile_is_device_cmyk() { + let ink = [0u8, 102, 255, 0]; + let working = cms::icc_bytes(&cms::active_settings().cmyk).unwrap(); + let other = cmyk_profile(|_| {}); + let export = |icc: &[u8], s: serde_json::Value| { + let tiff = cmyk_tiff_with(ink, 4, 4, icc); + let inks = tiff.cmyk().unwrap().data; + let d = image_doc(tiff, 4, 4); + let out = export_with_report(&d, &opts(s.clone())).unwrap_or_else(|e| panic!("{s}: {e}")); + let w: Vec = written(&out.bytes).into_iter().filter(|w| w.space != "DeviceGray").collect(); + assert_eq!(w.len(), 1, "{s}: {w:?}"); + assert_eq!(blobs(&import(&out.bytes).unwrap())[0].cmyk().unwrap().data, inks, "{s}: the inks as they were"); + w.into_iter().next().unwrap() + }; + for s in [json!({"standard": "pdfX4"}), json!({"standard": "pdfX3"}), json!({"standard": "pdfX4", "output": {"profiles": "none"}})] { + let w = export(&working, s.clone()); + assert_eq!((w.space.as_str(), w.icc_n), ("DeviceCMYK", None), "{s}: the output intent's profile"); + } + let w = export(&other, json!({"standard": "pdfX4"})); + assert!((w.space.as_str(), w.icc.as_deref()) == ("ICCBased", Some(other.as_slice())), "another profile is kept: {w:?}"); + let w = export(&other, json!({"standard": "pdfX4", "output": {"profiles": "none"}})); + assert_eq!((w.space.as_str(), w.icc_n), ("DeviceCMYK", None), "with none: {w:?}"); + // Without an output intent, the image keeps the profile it carries. + let w = export(&working, json!({"output": {"profiles": "all"}})); + assert!(w.space == "ICCBased" && w.icc.as_deref() == Some(&*working), "{w:?}"); +} + +/// A DeviceCMYK image in a file with a PDF/X output intent of CMYK opens tagged with the intent's +/// profile, so a CMYK image written as DeviceCMYK in that profile opens with it again. Without an +/// output intent it opens untagged. +#[test] +fn a_device_cmyk_image_opens_with_the_pdfx_output_intents_profile() { + let ink = [0u8, 102, 255, 0]; + let working = cms::icc_bytes(&cms::active_settings().cmyk).unwrap(); + for (s, tagged) in [(json!({"standard": "pdfX4"}), true), (json!({"standard": "pdfX3"}), true), (json!({}), false)] { + let d = image_doc(cmyk_tiff_with(ink, 4, 4, &working), 4, 4); + let out = export_with_report(&d, &opts(s.clone())).unwrap_or_else(|e| panic!("{s}: {e}")); + let w: Vec = written(&out.bytes).into_iter().filter(|w| w.space != "DeviceGray").collect(); + assert!(w.len() == 1 && w[0].space == "DeviceCMYK", "{s}: {w:?}"); + let opened = import(&out.bytes).unwrap(); + let icc = blobs(&opened)[0].cmyk_icc_profile(); + assert_eq!(icc.as_deref(), tagged.then_some(&*working), "{s}"); + } +} + +/// In a file whose catalog has a CMYK `/GTS_PDFX` output intent, a DeviceCMYK image opens tagged +/// with the intent's profile; another kind of output intent tags nothing, and neither does the +/// intent on a page whose resources replace DeviceCMYK with a `/DefaultCMYK`. +#[test] +fn a_device_cmyk_image_takes_the_output_intent_unless_a_default_cmyk_replaces_it() { + let (intent, other) = (cmyk_profile(|_| {}), cms::icc_bytes(&cms::active_settings().cmyk).unwrap().to_vec()); + assert_ne!(intent, other); + let image = [(cmyk_dict(2, 2, ""), flat([0, 102, 255, 0], 4))]; + let profiles = [stream("/N 4", &intent), stream("/N 4", &other)]; + let pdfx = "/OutputIntents [<< /Type /OutputIntent /S /GTS_PDFX /OutputConditionIdentifier (Test) /DestOutputProfile 6 0 R >>] "; + let pdfa = "/OutputIntents [<< /Type /OutputIntent /S /GTS_PDFA1 /OutputConditionIdentifier (Test) /DestOutputProfile 6 0 R >>] "; + let default_cmyk = "/ColorSpace << /DefaultCMYK [/ICCBased 7 0 R] >> "; + for (catalog, resources, expected) in [(pdfx, "", Some(&intent)), ("", "", None), (pdfa, "", None), (pdfx, default_cmyk, None)] { + let d = import(&pdf_with(&image, &profiles, catalog, resources)).unwrap(); + let b = blobs(&d); + assert_eq!(b.len(), 1, "{catalog} {resources}"); + assert_eq!(b[0].cmyk().unwrap().data, flat([0, 102, 255, 0], 4), "{catalog} {resources}: the inks as they were"); + assert_eq!(b[0].cmyk_icc_profile().as_deref(), expected.map(Vec::as_slice), "{catalog} {resources}"); + } +} + +/// A `/DefaultCMYK` stops the output intent from tagging a DeviceCMYK image only where it is in +/// scope: on the page's own image when only a form on the page has one, the image keeps the +/// intent's profile; drawn inside that form, it opens untagged; and the same image drawn on a page +/// with a `/DefaultCMYK` and then on a page without one opens untagged on the first and tagged on +/// the second. +#[test] +fn the_output_intent_tags_a_device_cmyk_image_only_where_no_default_cmyk_is_in_scope() { + let (intent, other) = (cmyk_profile(|_| {}), cms::icc_bytes(&cms::active_settings().cmyk).unwrap().to_vec()); + let default = "/ColorSpace << /DefaultCMYK [/ICCBased 8 0 R] >>"; + // Objects: 1 catalog, 2 pages, 3 and 4 the pages, 5 their content, 6 the image, 7 and 8 the + // profiles, 9 a form with a `/DefaultCMYK`. + let file = |pages: &[&str], content: &str, form: &str| { + let kids: String = (0..pages.len()).map(|i| format!("{} 0 R ", 3 + i)).collect(); + let page = |res: &str| format!("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 100] /Resources << {res} >> /Contents 5 0 R >>").into_bytes(); + let form_dict = format!("/Type /XObject /Subtype /Form /BBox [0 0 1 1] /Resources << /XObject << /Im0 6 0 R >> {default} >>"); + pdf_of(&[ + b"<< /Type /Catalog /Pages 2 0 R /OutputIntents [<< /Type /OutputIntent /S /GTS_PDFX /OutputConditionIdentifier (Test) /DestOutputProfile 7 0 R >>] >>".to_vec(), + format!("<< /Type /Pages /Kids [{kids}] /Count {} >>", pages.len()).into_bytes(), + page(pages[0]), + page(pages.get(1).copied().unwrap_or("")), + stream("", content.as_bytes()), + stream(&format!("/Type /XObject /Subtype /Image {}", cmyk_dict(2, 2, "")), &flat([0, 102, 255, 0], 4)), + stream("/N 4", &intent), + stream("/N 4", &other), + stream(&form_dict, form.as_bytes()), + ]) + }; + let image = "q 50 0 0 50 10 10 cm /Im0 Do Q "; + let form = "q 50 0 0 50 80 10 cm /Fm0 Do Q "; + let cases = [ + (file(&["/XObject << /Im0 6 0 R /Fm0 9 0 R >>"], &format!("{image}{form}"), "0 0 0 1 k 0 0 1 1 re f"), vec![Some(&intent)]), + (file(&["/XObject << /Fm0 9 0 R >>"], form, "/Im0 Do"), vec![None]), + (file(&[&format!("/XObject << /Im0 6 0 R >> {default}"), "/XObject << /Im0 6 0 R >>"], image, ""), vec![None, Some(&intent)]), + ]; + for (i, (bytes, expected)) in cases.into_iter().enumerate() { + let d = import(&bytes).unwrap(); + let profiles: Vec>> = all_images(&d).iter().map(|b| b.cmyk_icc_profile().map(|p| p.to_vec())).collect(); + assert_eq!(profiles, expected.into_iter().map(|p| p.cloned()).collect::>(), "case {i}"); + } +} + /// With Don't Include Profiles set, a CMYK JPEG kept as it is is DeviceCMYK without its own /// `ICC_PROFILE` segments, its compressed inks unchanged; one resampled and compressed again is /// written without a profile too. Left unset, the JPEG data stays as it is. @@ -672,6 +798,16 @@ fn a_set_dont_include_profiles_takes_a_cmyk_jpegs_profile_out() { let s = json!({"output": {"profiles": "none"}, "compression": {"color": {"downsample": "bicubic", "ppi": 72.0, "abovePpi": 100.0}}}); let (w, _) = export(s.clone()); assert!(w.icc.is_none() && !segment(&w.data), "{s}: {w:?}"); + // A PDF/X file whose CMYK colors are DeviceCMYK takes the profile out of a JPEG it untags. + let s = json!({"standard": "pdfX4", "output": {"profiles": "none"}}); + let (w, _) = export(s.clone()); + assert!(w.space == "DeviceCMYK" && w.data == vectorcraft_doc::cmyk::jpeg_without_icc(&jpg).unwrap(), "{s}: {w:?}"); + let working = cms::icc_bytes(&cms::active_settings().cmyk).unwrap(); + let own = cmyk_jpeg_with(&flat(ink, 64 * 64), 64, 64, &working); + let d = image_doc(ImageBlob::new("image/jpeg", own.clone()), 64, 64); + let out = export_with_report(&d, &opts(json!({"standard": "pdfX4"}))).unwrap(); + let w: Vec = written(&out.bytes).into_iter().filter(|w| w.space != "DeviceGray").collect(); + assert!(w.len() == 1 && w[0].space == "DeviceCMYK" && w[0].data == vectorcraft_doc::cmyk::jpeg_without_icc(&own).unwrap(), "{w:?}"); } /// A CMYK JPEG kept as it is whose header declares far more pixels than the app reads is left out 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/pdf/src/tests/fx.rs b/crates/pdf/src/tests/fx.rs index cd73c01bb9..709031a6a2 100644 --- a/crates/pdf/src/tests/fx.rs +++ b/crates/pdf/src/tests/fx.rs @@ -1,9 +1,11 @@ -//! Raster effects in PDF export: not written yet, so a fill's, a stroke's or the object's own -//! raster effect is reported. +//! Effects in PDF export: raster effects are not written yet, so a fill's, a stroke's or the +//! object's own raster effect is reported; geometry effects are baked into what the file draws. + +use std::sync::Arc; use vectorcraft_color::{Color, Paint}; -use vectorcraft_doc::{Appearance, Document, Effect, Node, NodeId}; -use vectorcraft_geom::{Rect, shapes}; +use vectorcraft_doc::{Appearance, AppearanceItem, CharStyle, Document, Effect, Node, NodeId, NodeKind, TextObject}; +use vectorcraft_geom::{Point, Rect, shapes}; use crate::*; @@ -27,3 +29,50 @@ fn raster_effects_warn_on_fills_strokes_and_objects() { assert!(warnings(item).iter().any(|w| w.starts_with("raster effects")), "{item:?}"); } } + +/// What `n` paints, in paint order, with consecutive repeats dropped: 'b' for a blue fill, 'r' for a +/// red fill and 'g' for a green stroke, each with whether a clip group clips it. Clipping paths +/// themselves are left out. +fn painted_order(n: &Node, clipped: bool, out: &mut Vec<(char, bool)>) { + let solid = |p: &Paint, r: f32, g: f32, b: f32| matches!(p, Paint::Solid { color, .. } if *color == Color::rgb(r, g, b)); + for i in &n.appearance.items { + let mark = match i { + AppearanceItem::Fill(f) if solid(&f.paint, 0.0, 0.0, 1.0) => 'b', + AppearanceItem::Fill(f) if solid(&f.paint, 1.0, 0.0, 0.0) => 'r', + AppearanceItem::Stroke(s) if s.width > 0.0 && solid(&s.paint, 0.0, 1.0, 0.0) => 'g', + _ => continue, + }; + if out.last() != Some(&(mark, clipped)) { + out.push((mark, clipped)); + } + } + let clips = matches!(n.kind, NodeKind::Group { clip: true, .. }); + for c in n.children().into_iter().flatten().skip(usize::from(clips)) { + painted_order(c, clipped || clips, out); + } +} + +#[test] +fn painted_clipping_type_exports_with_group_effect() { + // Type filled blue and stroked green clips a red square in a group with an Offset Path effect: + // the PDF paints the type's fill inside the clip behind the square, and its stroke over the + // clipped art, outside the clip. + let blue = Paint::solid(Color::rgb(0.0, 0.0, 1.0)); + let green = Paint::solid(Color::rgb(0.0, 1.0, 0.0)); + let style = CharStyle { size: 40.0, fill: blue, stroke: green, stroke_width: 2.0, ..Default::default() }; + let mut d = Document::new(200.0, 200.0); + let text = Node::new(d.alloc_id(), NodeKind::Text(Box::new(TextObject::point(Point::new(5.0, 60.0), "IIII", style)))); + let red = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0); + let square = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 200.0, 200.0)), red); + let clip = Node::new(d.alloc_id(), NodeKind::Group { children: vec![Arc::new(text), Arc::new(square)], clip: true }); + let mut outer = Node::group(d.alloc_id(), vec![Arc::new(clip)]); + outer.appearance.effects.push(Effect { id: "path.offsetPath".into(), params: serde_json::json!({"offset": 1}), visible: true }); + let layer = d.default_layer().unwrap(); + d.insert(Some(layer), 0, outer).unwrap(); + let back = import(&export(&d, &PdfOptions::default()).unwrap()).unwrap(); + let mut order = vec![]; + for l in &back.layers { + painted_order(l, false, &mut order); + } + assert_eq!(order, [('b', true), ('r', true), ('g', false)]); +} diff --git a/crates/pdf/src/tests/import_fidelity.rs b/crates/pdf/src/tests/import_fidelity.rs index 251cc925bf..188ca0e80d 100644 --- a/crates/pdf/src/tests/import_fidelity.rs +++ b/crates/pdf/src/tests/import_fidelity.rs @@ -507,6 +507,56 @@ fn a_form_drawn_many_times_reads_its_font_resources_once() { assert_eq!(walk.fonts.len(), 1); } +/// A Type 3 font that every page lists in a font dictionary of its own, and a form lists in its +/// resources, has its glyph procedures read once for the document. Each page still maps the font's +/// glyphs, and the font whose glyphs set their own color (`d0`) is told from the one whose glyphs +/// don't (`d1`). +#[test] +fn a_type3_font_on_every_page_has_its_glyph_procedures_read_once() { + const PAGES: usize = 6; + let n = first_extra(PAGES); + let (shape, color, shape_a, shape_b, color_a, form) = (n, n + 1, n + 2, n + 3, n + 4, n + 5); + let font = |name: &str, procs: &str| { + format!( + "<< /Type /Font /Subtype /Type3 /Name /{name} /FontBBox [0 0 1000 1000] /FontMatrix [0.001 0 0 0.001 0 0] /CharProcs << {procs} >> /Encoding << /Type /Encoding /Differences [97 /a /b] >> /FirstChar 97 /LastChar 98 /Widths [1000 1000] /Resources << >> >>" + ) + }; + let objects = [ + font("Vcshape", &format!("/a {shape_a} 0 R /b {shape_b} 0 R")), + font("Vccolor", &format!("/a {color_a} 0 R /b {color_a} 0 R")), + stream("", "1000 0 0 0 1000 1000 d1 0 0 1000 1000 re f"), + stream("", "1000 0 0 0 1000 1000 d1 0 0 500 500 re f"), + stream("", "1000 0 d0 1 0 0 rg 0 0 1000 1000 re f"), + stream( + &format!("/Type /XObject /Subtype /Form /BBox [0 0 100 100] /Resources << /Font << /C {color} 0 R /S {shape} 0 R >> >>"), + "BT /S 12 Tf (ab) Tj /C 12 Tf (ab) Tj ET", + ), + ]; + let pages: Vec = (0..PAGES) + .map(|_| PdfPage { + resources: format!("/Font << /S {shape} 0 R /C {color} 0 R >> /XObject << /X0 {form} 0 R >>"), + ..PdfPage::new(100.0, 100.0, "BT /S 24 Tf 10 30 Td (ab) Tj /C 24 Tf (ab) Tj ET /X0 Do") + }) + .collect(); + let extra: Vec<&str> = objects.iter().map(String::as_str).collect(); + let pdf = craft_pdf::syntax::Pdf::new(pdf_with(&pages, &extra, None)).unwrap(); + let mut fonts = crate::import_scan::FontNames::new(); + let mut ocgs = crate::import_scan::Ocgs::read(&pdf); + crate::import_scan::TEST_CHARPROC_DECODES.with(|d| d.set(0)); + for page in pdf.pages().iter() { + let scan = crate::import_scan::scan_page(page, &mut ocgs, false, &mut fonts, pdf.decode_limits().max_decoded_stream()).unwrap(); + let mapped: std::collections::HashSet<(u128, bool)> = scan.type3_cache_map.values().copied().collect(); + let noted: std::collections::HashSet<(u128, bool)> = fonts.keys().map(|k| (*k, false)).collect(); + assert_eq!(scan.type3_cache_map.len(), 2 * 257); + assert_eq!(mapped, noted); + let mut colors: Vec<(String, bool)> = fonts.values().map(|f| (f.name.clone(), f.is_colour)).collect(); + colors.sort(); + assert_eq!(colors, [("Vccolor".to_string(), true), ("Vcshape".to_string(), false)]); + } + // The `d1` font's two procedures and the `d0` font's one. + assert_eq!(crate::import_scan::TEST_CHARPROC_DECODES.with(std::cell::Cell::get), 3); +} + /// A value of the page's font dictionary that the reader can't parse (a name with a broken `#` /// escape, a number with a stray `-`) is left out when the page's fonts are noted, and the fonts /// after it are noted. diff --git a/crates/pdf/src/tests/output.rs b/crates/pdf/src/tests/output.rs index 71461ae1f8..d9c2fedc1d 100644 --- a/crates/pdf/src/tests/output.rs +++ b/crates/pdf/src/tests/output.rs @@ -591,39 +591,96 @@ fn standard_pdf(d: &Document, settings: Value) -> ExportReport { export_with_report(d, &PdfOptions { settings, created: Some(1_700_000_000), ..Default::default() }).unwrap() } +/// The output intent's profile, decoded, of `bytes`. +fn intent_profile(bytes: &[u8]) -> Vec { + let mut out = vec![]; + output_intent(bytes, None, |oi| out = oi.get::>(b"DestOutputProfile").unwrap().decoded().unwrap().into_owned()); + out +} + +/// CMYK colors in the profile of a CMYK output intent are DeviceCMYK, which the output intent +/// describes: no ICC-based CMYK space carries the same profile, and it is embedded once (#1954). #[test] -fn a_profile_that_tags_colours_and_is_the_output_intent_is_embedded_once() { - let d = doc(ColorMode::Cmyk, &[Color::cmyk(0.1, 0.2, 0.3, 0.4)]); +fn cmyk_colors_in_the_output_intents_profile_are_device_cmyk() { + let ink = [0.1, 0.2, 0.3, 0.4]; + let d = doc(ColorMode::Cmyk, &[Color::cmyk(ink[0], ink[1], ink[2], ink[3])]); let working = cms::active_settings().cmyk; let icc = cms::icc_bytes(&working).unwrap(); for set in [ json!({"standard": "pdfX4"}), json!({"standard": "pdfX4", "output": {"outputIntent": working}}), - // PDF/X-3 and PDF/X-4 always tag their colours: `profiles` doesn't apply. json!({"standard": "pdfX4", "output": {"profiles": "none", "outputIntent": working}}), json!({"standard": "pdfX3"}), - json!({"output": {"profiles": "all", "outputIntent": working}}), ] { let r = standard_pdf(&d, set.clone()); - let streams = icc_streams(&r.bytes); - assert_eq!(streams.len(), 1, "{set}: ICC profile streams"); - assert!(streams[0] == *icc, "{set}: the working CMYK profile"); - assert!(colours(&r.bytes).iter().all(|c| c.0 == "scn"), "{set}: tagged colours"); - output_intent(&r.bytes, None, |oi| assert_eq!(oi.get::>(b"DestOutputProfile").unwrap().decoded().unwrap().as_ref(), &*icc)); + assert!(r.warnings.is_empty(), "{set}: {:?}", r.warnings); + assert!(icc_streams(&r.bytes) == [icc.to_vec()], "{set}: the working CMYK profile, once"); + assert!(icc_profiles(&r.bytes).is_empty(), "{set}: no ICC-based color space"); + let c = colours(&r.bytes); + assert!(c.len() == 1 && c[0].0 == "k" && close(&c[0].1, &ink), "{set}: DeviceCMYK, the numbers kept: {c:?}"); + assert!(intent_profile(&r.bytes) == *icc, "{set}"); } - // Another output intent profile is its own stream. + // Another output intent's profile: CMYK colors keep their own, and both are embedded. + let other = cms::icc_bytes(DEVICE_CMYK).unwrap(); let r = standard_pdf(&d, json!({"standard": "pdfX4", "output": {"outputIntent": DEVICE_CMYK}})); assert_eq!(icc_streams(&r.bytes).len(), 2); - output_intent(&r.bytes, None, |oi| { - assert_eq!(oi.get::>(b"DestOutputProfile").unwrap().decoded().unwrap().as_ref(), &*cms::icc_bytes(DEVICE_CMYK).unwrap()) - }); + assert!(icc_profiles(&r.bytes) == [(4, icc.to_vec())]); + assert!(colours(&r.bytes).iter().all(|c| c.0 == "scn"), "{:?}", colours(&r.bytes)); + assert!(intent_profile(&r.bytes) == *other); + // With `none`, every CMYK color is DeviceCMYK, in the output intent's profile. + for standard in ["pdfX3", "pdfX4"] { + let set = json!({"standard": standard, "output": {"profiles": "none", "outputIntent": DEVICE_CMYK}}); + let r = standard_pdf(&d, set.clone()); + assert!(icc_streams(&r.bytes) == [other.to_vec()], "{set}"); + let c = colours(&r.bytes); + assert!(c.len() == 1 && c[0].0 == "k" && close(&c[0].1, &ink), "{set}: {c:?}"); + } + // With `none`, colors converted to a CMYK destination of another profile keep its tag: they + // are in the destination's profile, not the output intent's. + let set = json!({"standard": "pdfX4", "output": {"profiles": "none", "conversion": "destination", "destination": DEVICE_CMYK, "outputIntent": working}}); + let r = standard_pdf(&d, set.clone()); + assert!(icc_profiles(&r.bytes) == [(4, other.to_vec())], "{set}"); + assert!(colours(&r.bytes).iter().all(|c| c.0 == "scn"), "{set}: {:?}", colours(&r.bytes)); + assert!(intent_profile(&r.bytes) == *icc, "{set}"); + // Without a standard, `all` tags CMYK colors, with an output intent of their profile or none. + for set in [json!({"output": {"profiles": "all"}}), json!({"output": {"profiles": "all", "outputIntent": working}})] { + let r = standard_pdf(&d, set.clone()); + assert!(icc_profiles(&r.bytes) == [(4, icc.to_vec())], "{set}"); + assert!(colours(&r.bytes).iter().all(|c| c.0 == "scn"), "{set}: {:?}", colours(&r.bytes)); + } +} + +/// Next to DeviceCMYK colors, RGB colors stay ICC-based (a CMYK output intent leaves no room for +/// DeviceRGB), and transparency groups of a CMYK document blend in DeviceCMYK. +#[test] +fn rgb_stays_tagged_and_groups_blend_in_device_cmyk_beside_device_cmyk_colors() { + let d = doc(ColorMode::Rgb, &[Color::rgb(0.2, 0.4, 0.6), Color::cmyk(0.1, 0.2, 0.3, 0.4)]); + for set in [json!({"standard": "pdfX4"}), json!({"standard": "pdfX4", "output": {"profiles": "none"}})] { + let r = standard_pdf(&d, set.clone()); + let ops: Vec = colours(&r.bytes).into_iter().map(|c| c.0).collect(); + assert_eq!(ops, ["scn", "k"], "{set}"); + let n: Vec = icc_profiles(&r.bytes).iter().map(|p| p.0).collect(); + assert_eq!(n, [3], "{set}: sRGB only"); + } + let mut d = doc(ColorMode::Cmyk, &[Color::cmyk(1.0, 0.0, 0.0, 0.0)]); + let mut n = Node::path( + d.alloc_id(), + shapes::rectangle(Rect::new(20.0, 20.0, 60.0, 60.0)), + Appearance::basic(Paint::solid(Color::cmyk(0.0, 1.0, 0.0, 0.0)), Paint::None, 0.0), + ); + n.opacity = 0.5; + let l = d.layers[0].id; + d.insert(Some(l), 1, n).unwrap(); + let r = standard_pdf(&d, json!({"standard": "pdfX4"})); + let text = String::from_utf8_lossy(&r.bytes); + let groups: Vec<&str> = text.split("/Group<<").skip(1).map(|g| g.split(">>").next().unwrap()).collect(); + assert!(!groups.is_empty() && groups.iter().all(|g| g.contains("/CS/DeviceCMYK")), "{groups:?}"); } /// The profiles assigned to a document (Edit › Assign Profile) are its colour spaces whatever the /// working spaces of the session that exports it: a document opened again in a new session, -/// which starts with the default working spaces, keeps its profiles. Its CMYK colours are tagged -/// with its CMYK profile, which is also the PDF/X output intent, and its RGB colours separate -/// through it. +/// which starts with the default working spaces, keeps its profiles. Its CMYK profile is the PDF/X +/// output intent, whose DeviceCMYK colors are in it, and its RGB colours separate through it. #[test] fn colours_are_in_the_profiles_assigned_to_the_document() { let working = cms::active_settings().cmyk; @@ -635,13 +692,13 @@ fn colours_are_in_the_profiles_assigned_to_the_document() { let r = standard_pdf(&d, json!({"standard": "pdfX4"})); assert!(!r.warnings.iter().any(|w| w.contains("profile")), "{:?}", r.warnings); let own = cms::icc_bytes(DEVICE_CMYK).unwrap(); - assert!(icc_streams(&r.bytes) == [own.to_vec()], "tagged with the document's CMYK profile, not the working one"); + assert!(icc_streams(&r.bytes) == [own.to_vec()], "the document's CMYK profile, not the working one"); output_intent(&r.bytes, None, |oi| assert_eq!(oi.get::>(b"DestOutputProfile").unwrap().decoded().unwrap().as_ref(), &*own)); let c = colours(&r.bytes); - assert!(c[0].0 == "scn" && close(&c[0].1, &[0.1, 0.2, 0.3, 0.4]), "CMYK keeps its numbers: {c:?}"); + assert!(c[0].0 == "k" && close(&c[0].1, &[0.1, 0.2, 0.3, 0.4]), "CMYK keeps its numbers: {c:?}"); let separated = to_cmyk(DEVICE_CMYK).to_cmyk(&grey, intent); assert!(!close(&separated, &cms::active().to_cmyk(&grey, intent)), "the two profiles separate grey differently"); - assert!(c[1].0 == "scn" && close(&c[1].1, &separated), "RGB separated through the document's profile: {c:?} vs {separated:?}"); + assert!(c[1].0 == "k" && close(&c[1].1, &separated), "RGB separated through the document's profile: {c:?} vs {separated:?}"); // A profile that isn't available leaves the working space, with a warning. d.color_profiles.cmyk = Some("No Such Press".into()); let r = standard_pdf(&d, json!({"standard": "pdfX4"})); diff --git a/crates/pdf/src/tests/print.rs b/crates/pdf/src/tests/print.rs index 49a34ff428..588273faf9 100644 --- a/crates/pdf/src/tests/print.rs +++ b/crates/pdf/src/tests/print.rs @@ -829,6 +829,80 @@ fn overprint_black_keeps_the_cyan_under_near_and_freeform_blacks_on_postscript_p assert_eq!((fills(&p.plates[0]), fills(&p.plates[3])), (1, 4), "the cyan plate, the Black plate"); } +#[test] +fn overprint_black_keeps_the_cyan_under_a_near_black_linked_to_a_missing_swatch_on_postscript_plates() { + // 0.4% cyan beside 100% K, linked to a swatch the document lacks: it separates from its own + // values and the option marks it to overprint, so it counts as black like an unlinked color. + let near = Paint::Solid { color: Color::cmyk(0.004, 0.0, 0.0, 1.0), swatch: Some("Missing".into()), tint: 1.0 }; + let square = + Node::path(vectorcraft_doc::NodeId(0), shapes::rectangle(Rect::new(10.0, 15.0, 30.0, 35.0)), Appearance::basic(near, Paint::None, 0.0)); + let d = over_cyan(vec![square]); + assert!(d.swatch("Missing").is_none()); + let opts = PrintOptions { + settings: settings(json!({"output": {"mode": "separations", "overprintBlack": true}})), + postscript: true, + ..Default::default() + }; + let p = plan(&d, &opts).unwrap(); + let fills = |doc: &Document| { + let mut count = 0; + doc.walk(|n| count += usize::from(n.appearance.fill().is_some_and(|f| !f.paint.is_none()))); + count + }; + assert_eq!((fills(&p.plates[0]), fills(&p.plates[3])), (1, 2), "the cyan plate, the Black plate"); +} + +#[test] +fn overprinting_near_blacks_linked_to_a_missing_swatch_keep_the_cyan_on_postscript_plates() { + // 0.4% cyan beside 100% K, linked to a swatch the document lacks and set to overprint, on a + // fill, a stroke, a character fill and a linear gradient's stops: a PostScript cyan plate draws + // it as nothing, as it does an unlinked black, and a PDF cyan plate draws it. A faint cyan that + // is not black, linked to the same name, stays on both. + let missing = |color: Color| Paint::Solid { color, swatch: Some("Missing".into()), tint: 1.0 }; + let near = Color::cmyk(0.004, 0.0, 0.0, 1.0); + let faint = Color::cmyk(0.004, 0.5, 0.0, 0.0); + let square = |x: f64, fill: Paint, stroke: Paint| { + let mut n = + Node::path(vectorcraft_doc::NodeId(0), shapes::rectangle(Rect::new(x, 15.0, x + 20.0, 35.0)), Appearance::basic(fill, stroke, 2.0)); + if let Some(f) = n.appearance.fill_mut() { + f.overprint = true; + } + if let Some(s) = n.appearance.stroke_mut() { + s.overprint = true; + } + n + }; + let stop = |offset: f32| GradientStop { swatch: Some("Missing".into()), ..GradientStop::new(offset, near) }; + let linear = GradientPaint::new(Gradient::new(GradientKind::Linear, vec![stop(0.0), stop(1.0)])); + let style = vectorcraft_doc::CharStyle { fill: missing(near), overprint_fill: true, ..Default::default() }; + let text = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(20.0, 60.0), "Hi", style); + let d = over_cyan(vec![ + square(10.0, missing(near), Paint::None), + square(40.0, Paint::None, missing(near)), + square(70.0, Paint::Gradient(Box::new(linear)), Paint::None), + square(100.0, missing(faint), Paint::None), + Node::new(vectorcraft_doc::NodeId(0), NodeKind::Text(Box::new(text))), + ]); + assert!(d.swatch("Missing").is_none()); + // The fills, strokes and character fills plate `plate` draws. + let drawn = |postscript: bool, plate: usize| { + let opts = PrintOptions { settings: settings(json!({"output": {"mode": "separations"}})), postscript, ..Default::default() }; + let p = plan(&d, &opts).unwrap(); + let (mut fills, mut strokes, mut chars) = (0, 0, 0); + p.plates[plate].walk(|n| { + fills += usize::from(n.appearance.fill().is_some_and(|f| !f.paint.is_none())); + strokes += usize::from(n.appearance.stroke().is_some_and(|s| !s.paint.is_none())); + if let NodeKind::Text(t) = &n.kind { + chars += t.runs.iter().filter(|r| !r.style.fill.is_none()).count(); + } + }); + (fills, strokes, chars) + }; + assert_eq!(drawn(true, 0), (2, 0, 0), "PostScript cyan plate: the cyan and the faint fill"); + assert_eq!(drawn(false, 0), (4, 1, 1), "PDF cyan plate: the cyan, the fill, the gradient, the faint fill, the stroke and the type"); + assert_eq!(drawn(true, 3), (3, 1, 1), "PostScript Black plate: every black, not the faint fill"); +} + #[test] fn an_overprinting_fill_keeps_its_faint_ink_on_pdf_plates() { // 0.4% cyan beside 100% K, set to overprint: a PDF plate draws it with Darken, a PostScript 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/svg/src/export/text.rs b/crates/svg/src/export/text.rs index 8a808b5f72..f8bc712117 100644 --- a/crates/svg/src/export/text.rs +++ b/crates/svg/src/export/text.rs @@ -103,20 +103,23 @@ impl Writer<'_> { || t.stacks_warichu() || (inline && matches!(t.kind, TextKind::OnPath { .. })) || unwritable; - let chars = |w: &mut Self, n: &Node| if outlined { w.text_outlines(n, t) } else { w.text(n, t) }; + // Every writer below draws this one layout of the type. + let db = vectorcraft_text::FontDb::global(); + let lay = vectorcraft_text::layout(db, t); + let chars = |w: &mut Self, n: &Node| if outlined { w.text_outlines(n, t, &lay) } else { w.text(n, t, &lay) }; let painted = n.appearance.items.iter().any(|i| i.visible() && !i.paint().is_none()); // Live type with an inside or outside character stroke writes that stroke apart from the // text, in the group. let apart = !outlined && t.runs.iter().any(|r| aligned(&r.style)); if !painted && !inline && !apart { + #[cfg(test)] + DRAW_HANDED.with(|d| d.set(true)); return chars(self, n); } let id = self.id_attr(n); let a = self.attrs(&css::transparency(n)); self.line(&format!("")); self.depth += 1; - let db = vectorcraft_text::FontDb::global(); - let lay = vectorcraft_text::layout(db, t); let mut all = lay.to_bezpath(); for (_, bar) in vectorcraft_text::decorations(&lay, db, t) { all.extend(bar.iter()); @@ -154,14 +157,22 @@ impl Writer<'_> { } /// Text as glyph outlines: one compound path per run, painted like the run (gradients span - /// the whole text), over its colour glyphs, as on the canvas. - fn text_outlines(&mut self, n: &Node, t: &TextObject) { + /// the whole text), over its colour glyphs, as on the canvas. `lay` is the layout of `t`. + fn text_outlines(&mut self, n: &Node, t: &TextObject, lay: &vectorcraft_text::TextLayout) { + let mut again = None; + let lay = handed(t, lay, &mut again); let db = vectorcraft_text::FontDb::global(); - let lay = vectorcraft_text::layout(db, t); let mut runs = vec![kurbo::BezPath::new(); t.runs.len()]; + // Each run's glyphs, in layout order. + let mut run_glyphs = vec![Vec::new(); t.runs.len()]; + for g in &lay.glyphs { + if let Some(gs) = run_glyphs.get_mut(g.run) { + gs.push(g); + } + } // Underline and strikethrough bars join their run's outlines; ruby glyphs are painted // with the run of the text they annotate. - let bars = vectorcraft_text::decorations(&lay, db, t); + let bars = vectorcraft_text::decorations(lay, db, t); for (run, outline) in lay .glyphs .iter() @@ -197,10 +208,10 @@ impl Writer<'_> { // The glyphs stay in text space; the text's transform joins the document's meanwhile. let saved = self.xf; self.xf = saved * t.xf; - for (i, (bp, run)) in runs.iter().zip(&t.runs).enumerate() { + for ((bp, run), glyphs) in runs.iter().zip(&t.runs).zip(&run_glyphs) { // Colour glyphs paint themselves, under their run's paint: bitmap glyphs (emoji) as // their images, COLR and SVG glyphs as their art. - for g in lay.glyphs.iter().filter(|g| g.run == i) { + for g in glyphs { if let Some((image, to_text)) = g.placed_image() { let m = self.matrix(self.xf * to_text); let href = self.blob_href(&image.blob); @@ -233,40 +244,42 @@ impl Writer<'_> { /// spacing come out as on the canvas. Centred and right-aligned lines are anchored /// (`text-anchor`) at their centre or right end, so they stay aligned in a viewer whose font /// differs; other lines are placed where each style run (and, justified, each word) starts. - fn text(&mut self, n: &Node, t: &TextObject) { + /// `lay` is the layout of `t`. + fn text(&mut self, n: &Node, t: &TextObject, lay: &vectorcraft_text::TextLayout) { // Live SVG text is written in logical order from left-aligned pieces: bidirectional text // (and right-to-left paragraphs) keep their look as outlines until it is written with // `direction`/`unicode-bidi`. So do runs set Right to Left (Character Direction), whose // `direction="rtl"` would anchor their pieces at the right end. - let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); + let mut again = None; + let lay = handed(t, lay, &mut again); let rtl_runs = t.runs.iter().any(|r| r.style.char_direction == Some(vectorcraft_doc::ParaDirection::RightToLeft)); if lay.glyphs.iter().any(|g| g.rtl) || lay.lines.iter().any(|l| l.rtl) || rtl_runs { self.warn("bidirectional text is outlined to preserve shaping and visual order"); - return self.text_outlines(n, t); + return self.text_outlines(n, t, lay); } if let TextKind::OnPath { path, start, end } = &t.kind { // A reader lays a ``'s glyphs straight: joined glyphs bent along the path // keep their look as outlines. if lay.glyphs.iter().any(|g| g.bend.is_some()) { self.warn("joined type bent along a path is outlined to keep its look"); - return self.text_outlines(n, t); + return self.text_outlines(n, t, lay); } // `` has a start offset only: an end bracket, Align to Path and Spacing // keep their look as outlines. if end.is_some() || t.path_align != vectorcraft_doc::PathAlign::Baseline || t.path_spacing != 0.0 { self.warn("type on a path with an end bracket, Align to Path or Spacing is outlined to keep its look"); - return self.text_outlines(n, t); + return self.text_outlines(n, t, lay); } // A reader turns each `` glyph with the path, as Rainbow does: Skew, 3D // Ribbon, Stair Step and Gravity keep their look as outlines. if t.path_effect != vectorcraft_doc::PathEffect::Rainbow { self.warn("type on a path with an effect other than Rainbow is outlined to keep its look"); - return self.text_outlines(n, t); + return self.text_outlines(n, t, lay); } // It cannot hang glyphs outside the start bracket either. - if hangs_on_path(t, &lay) { + if hangs_on_path(t, lay) { self.warn("type on a path with glyphs hanging outside its brackets is outlined to keep its look"); - return self.text_outlines(n, t); + return self.text_outlines(n, t, lay); } // The space before the first character is written as its `dx`; one before a character // after a line break, which the `` writes as a space, keeps its look as outlines. @@ -279,39 +292,39 @@ impl Writer<'_> { }); if spaced_break { self.warn("type on a path with space before a character after a line break is outlined to keep its look"); - return self.text_outlines(n, t); + return self.text_outlines(n, t, lay); } // A `` places its characters one after the other: Insert Aki keeps its look as // outlines. if t.runs.iter().any(|r| r.style.aki_left != 0.0 || r.style.aki_right != 0.0) { self.warn("type on a path with Insert Aki is outlined to keep its look"); - return self.text_outlines(n, t); + return self.text_outlines(n, t, lay); } // Tsume does as well. if t.runs.iter().any(|r| r.style.tsume != 0.0) { self.warn("type on a path with Tsume is outlined to keep its look"); - return self.text_outlines(n, t); + return self.text_outlines(n, t, lay); } // Justification…'s Desired word and letter spacing and glyph scaling do too. if (0..t.paragraph_count()).any(|i| !t.layout_justification(t.para_at(i)).desired_is_default()) { self.warn("type on a path with Justification spacing or glyph scaling is outlined to keep its look"); - return self.text_outlines(n, t); + return self.text_outlines(n, t, lay); } // A `` holds the characters of the text, not the bullets or numbers drawn // before them. if !lay.markers.is_empty() { self.warn("type on a path with bullets or numbers is outlined to keep its look"); - return self.text_outlines(n, t); + return self.text_outlines(n, t, lay); } // Nor the character a repeat mark is drawn as in the mark's width (Kurikaeshi Moji Shori). if !lay.repeat_marks.is_empty() { self.warn("type on a path that starts with a repeat mark drawn as the character it repeats is outlined to keep its look"); - return self.text_outlines(n, t); + return self.text_outlines(n, t, lay); } - return self.text_on_path(n, t, path, *start); + return self.text_on_path(n, t, lay, path, *start); } - self.note_fonts(t, &lay); - let lines = text_lines(t, &lay, self.opts.fewer_tspans); + self.note_fonts(t, lay); + let lines = text_lines(t, lay, self.opts.fewer_tspans); // `drawn` holds the styles the layout draws the text in: Shrink Text to Fit scales its sizes, explicit leading and baseline shifts. let fitted = (lay.fit_scale != 1.0).then(|| vectorcraft_text::scaled(t, lay.fit_scale)); let drawn = fitted.as_ref().unwrap_or(t); @@ -374,35 +387,36 @@ impl Writer<'_> { } s.push_str(""); self.line(&s); - self.aligned_char_strokes(t); + self.aligned_char_strokes(t, lay); } - /// The inside and outside character strokes of live type `t`, over its text (which goes - /// without them, see [`Self::char_props`]): each such run's stroke on its glyph outlines, drawn - /// twice as wide and clipped or masked to its side as aligned path strokes are + /// The inside and outside character strokes of live type `t`, laid out as `lay`, over its text + /// (which goes without them, see [`Self::char_props`]): each such run's stroke on its glyph + /// outlines, drawn twice as wide and clipped or masked to its side as aligned path strokes are /// ([`Self::side_attr`]). The text stays live; only the stroke follows the outlines. - fn aligned_char_strokes(&mut self, t: &TextObject) { + fn aligned_char_strokes(&mut self, t: &TextObject, lay: &vectorcraft_text::TextLayout) { if !t.runs.iter().any(|r| aligned(&r.style)) { return; } + let mut again = None; + let lay = handed(t, lay, &mut again); let db = vectorcraft_text::FontDb::global(); - let lay = vectorcraft_text::layout(db, t); - let bars = vectorcraft_text::decorations(&lay, db, t); + let bars = vectorcraft_text::decorations(lay, db, t); + // Each such run's glyph outlines and then its bars, in layout order. + let mut outlines = vec![BezPath::new(); t.runs.len()]; + for (run, outline) in lay.glyphs.iter().map(|g| (g.run, &g.outline)).chain(bars.iter().map(|(r, b)| (*r, b))) { + if let Some(bp) = outlines.get_mut(run).filter(|_| t.runs.get(run).is_some_and(|r| aligned(&r.style))) { + bp.extend(outline.iter()); + } + } // The glyphs stay in text space; the text's transform joins the document's meanwhile. let saved = self.xf; self.xf = saved * t.xf; - for (i, run) in t.runs.iter().enumerate().filter(|(_, r)| aligned(&r.style)) { - let mut bp = BezPath::new(); - for g in lay.glyphs.iter().filter(|g| g.run == i) { - bp.extend(g.outline.iter()); - } - for (_, bar) in bars.iter().filter(|(r, _)| *r == i) { - bp.extend(bar.iter()); - } + for (run, bp) in t.runs.iter().zip(&outlines).filter(|(r, _)| aligned(&r.style)) { if bp.elements().is_empty() { continue; } - let pd = PathData::from_bezpath(&bp); + let pd = PathData::from_bezpath(bp); let ap = vectorcraft_doc::Appearance { items: vec![AppearanceItem::Stroke(run.style.stroke_layer())], ..Default::default() }; let d = self.path_d(&pd, self.xf); self.shape(&Node::path(NodeId(u64::MAX), pd.clone(), ap), &d, None, &[&pd], FillRule::NonZero, Some(lay.bounds)); @@ -574,15 +588,16 @@ impl Writer<'_> { rules } - /// Type on a path: a `` along the path (a def). - fn text_on_path(&mut self, n: &Node, t: &TextObject, path: &PathData, start: f64) { + /// Type on a path, laid out as `lay`: a `` along the path (a def). + fn text_on_path(&mut self, n: &Node, t: &TextObject, lay: &vectorcraft_text::TextLayout, path: &PathData, start: f64) { let id = self.id_attr(n); let pid = self.fresh_id("text-path"); let d = self.path_d(path, self.xf * t.xf); self.def(1, &format!("")); // The element's user space is the document's; gradients span the laid-out text. - let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); - self.note_fonts(t, &lay); + let mut again = None; + let lay = handed(t, lay, &mut again); + self.note_fonts(t, lay); // The styles the layout draws the text in: Dynamic Text scales its sizes, leading and baseline shifts. let fitted = (lay.fit_scale != 1.0).then(|| vectorcraft_text::scaled(t, lay.fit_scale)); let drawn = fitted.as_ref().unwrap_or(t); @@ -626,7 +641,7 @@ impl Writer<'_> { } s.push_str(""); self.line(&s); - self.aligned_char_strokes(t); + self.aligned_char_strokes(t, lay); } } @@ -635,6 +650,34 @@ fn aligned(st: &CharStyle) -> bool { st.has_stroke() && st.stroke_align != StrokeAlign::Center } +#[cfg(test)] +thread_local! { + /// Tests: each type writer lays `t` out again ([`handed`]) instead of drawing the layout it is + /// handed, so a test can compare the two. The first writer of type written without a group + /// still draws the layout it is handed ([`DRAW_HANDED`]), so each object is laid out where it + /// is drawn. + static LAY_OUT_AGAIN: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// Tests: the next type writer draws the layout it is handed, with [`LAY_OUT_AGAIN`] too. + static DRAW_HANDED: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// The layout a type writer draws: `lay`, the layout of `t` it is handed. In tests that ask for it, +/// `t` laid out again, kept in `again`. +fn handed<'a>( + t: &TextObject, + lay: &'a vectorcraft_text::TextLayout, + again: &'a mut Option, +) -> &'a vectorcraft_text::TextLayout { + #[cfg(test)] + let lay = { + let draw_handed = DRAW_HANDED.with(|d| d.replace(false)); + if LAY_OUT_AGAIN.with(std::cell::Cell::get) && !draw_handed { &*again.insert(vectorcraft_text::layout(FontDb::global(), t)) } else { lay } + }; + #[cfg(not(test))] + let _ = (t, again); + lay +} + /// Does type on a path `t`, laid out as `lay`, hang glyphs outside its brackets? It does when /// Optical Margin Alignment or its first paragraph's Roman Hanging Punctuation is on and its /// glyphs sit elsewhere with both off. diff --git a/crates/svg/src/export/text/tests.rs b/crates/svg/src/export/text/tests.rs index 951817c2c5..6b2fcbfb1f 100644 --- a/crates/svg/src/export/text/tests.rs +++ b/crates/svg/src/export/text/tests.rs @@ -1,5 +1,7 @@ //! The advances a reader gives live type ([`reader_advances`]): the same as when the type is laid //! out again each time, which happens only when a reader sets the type differently from its layout. +//! The type writers draw one layout of the type ([`handed`]) and write what laying it out in each +//! writer writes. use super::*; use vectorcraft_doc::text::{Bullet, ParaList}; @@ -145,3 +147,202 @@ fn a_mixed_document_lays_out_again_only_the_japanese_type() { let (svg, again) = export_layouts_again(vec![point("Latin"), point("「かな」。"), point(""), point("Ab2")]); assert_eq!(again, 1, "{svg}"); } + +/// Type `t`, with the object's own fills and strokes `items`, alone in a document. +fn doc_of(t: TextObject, items: Vec) -> Document { + let mut d = Document::new(300.0, 200.0); + let mut n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t))); + n.appearance.items = items; + let l = d.layers[0].id; + d.insert(Some(l), 0, n).unwrap(); + d +} + +/// Type on a straight path across the page. +fn on_path(text: &str, st: CharStyle) -> TextObject { + let mut t = TextObject::point(Point::ZERO, text, st); + let mut line = BezPath::new(); + line.move_to((20.0, 100.0)); + line.line_to((280.0, 100.0)); + t.kind = TextKind::OnPath { path: PathData::from_bezpath(&line), start: 0.0, end: None }; + t +} + +/// A character style with a stroke on side `align`. +fn stroked(align: StrokeAlign) -> CharStyle { + CharStyle { stroke: Paint::solid(vectorcraft_color::Color::rgb8(200, 0, 0)), stroke_width: 2.0, stroke_align: align, ..style() } +} + +fn red_fill() -> Vec { + vec![AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(Paint::solid(vectorcraft_color::Color::rgb8(255, 0, 0))))] +} + +/// The type the writers handle differently, each with how many times its export lays the type +/// out: once, plus the layout of the copy that checks for hanging glyphs on a path; and how many +/// times with each writer laying the type out on its own ([`LAY_OUT_AGAIN`]). +fn writer_cases() -> Vec<(&'static str, Document, crate::ExportOptions, u64, u64)> { + let opts = crate::ExportOptions::default; + let outlined = || crate::ExportOptions { outline_text: true, ..crate::ExportOptions::default() }; + let mut runs = point("Red "); + runs.runs.push(TextRun::new("green ", CharStyle { underline: true, ..stroked(StrokeAlign::Outside) })); + runs.runs.push(TextRun::new("blue", CharStyle { strikethrough: true, ..style() })); + let mut many = point(""); + many.runs = (0..200).map(|i| TextRun::new(if i % 7 == 6 { " " } else { "x" }, CharStyle { size: 8.0 + f64::from(i % 5), ..style() })).collect(); + let mut rtl_run = point("abc"); + rtl_run.runs[0].style.char_direction = Some(vectorcraft_doc::ParaDirection::RightToLeft); + let mut skewed = on_path("Skewed", style()); + skewed.path_effect = vectorcraft_doc::PathEffect::Skew; + let mut hanging = on_path("\u{201C}Quoted.\u{201D}", style()); + hanging.optical_margin = true; + let mut inside = point("Inside out"); + inside.runs.push(TextRun::new(" plain", style())); + inside.runs[0].style = CharStyle { underline: true, ..stroked(StrokeAlign::Inside) }; + let outside = TextObject::point(Point::new(20.0, 20.0), "Outside", stroked(StrokeAlign::Outside)); + vec![ + ("point type", doc_of(point("Plain type"), vec![]), opts(), 1, 1), + ("point type with a fill", doc_of(point("Filled type"), red_fill()), opts(), 1, 2), + ("type on a path", doc_of(on_path("Type on a path", style()), vec![]), opts(), 1, 2), + ("type on a path with a fill", doc_of(on_path("Filled path type", style()), red_fill()), opts(), 1, 3), + ("bidirectional type", doc_of(point("abc \u{5D0}\u{5D1}\u{5D2} def"), vec![]), opts(), 1, 2), + ("a run set right to left", doc_of(rtl_run, vec![]), opts(), 1, 2), + ("bidirectional type on a path", doc_of(on_path("abc \u{5D0}\u{5D1}\u{5D2}", style()), vec![]), opts(), 1, 2), + ("type on a path with Skew", doc_of(skewed, vec![]), opts(), 1, 2), + ("type on a path that may hang", doc_of(hanging, vec![]), opts(), 2, 3), + ("outside character stroke", doc_of(outside, vec![]), opts(), 1, 3), + ("inside character stroke", doc_of(inside, vec![]), opts(), 1, 3), + ("runs with a stroke and decorations", doc_of(runs.clone(), vec![]), opts(), 1, 3), + ("runs as outlines", doc_of(runs.clone(), vec![]), outlined(), 1, 1), + ("outside stroke on a path with a fill", doc_of(on_path("Stroked", stroked(StrokeAlign::Outside)), red_fill()), opts(), 1, 4), + ("inside stroke on a path", doc_of(on_path("Stroked", stroked(StrokeAlign::Inside)), vec![]), opts(), 1, 4), + ("many runs as outlines", doc_of(many.clone(), vec![]), outlined(), 1, 1), + ("many runs", doc_of(many, vec![]), opts(), 1, 1), + ] +} + +/// SVG export of `d` with each type writer laying the type out again (`again`) or drawing the +/// layout it is handed, and how many times the export laid type out. +fn export_counting(d: &Document, opts: &crate::ExportOptions, again: bool) -> (crate::Output, u64) { + LAY_OUT_AGAIN.with(|a| a.set(again)); + let before = vectorcraft_text::test_fonts::layouts_on_this_thread(); + let out = crate::export_full(d, opts, None); + let laid = vectorcraft_text::test_fonts::layouts_on_this_thread() - before; + LAY_OUT_AGAIN.with(|a| a.set(false)); + (out, laid) +} + +#[test] +fn every_type_writer_draws_one_layout() { + for (name, d, opts, layouts, own_layouts) in writer_cases() { + let (out, laid) = export_counting(&d, &opts, false); + assert_eq!(laid, layouts, "{name}: {}", out.svg); + // The same file and warnings as each writer laying the type out on its own. + let (again, laid_again) = export_counting(&d, &opts, true); + assert_eq!(laid_again, own_layouts, "{name}"); + assert_eq!(out.svg, again.svg, "{name}"); + assert_eq!(out.warnings, again.warnings, "{name}"); + assert_eq!(out.setting_notes, again.setting_notes, "{name}"); + } +} + +/// The CPU time this thread has run, from Linux's scheduler statistics; wall time elsewhere. +fn thread_time(start: std::time::Instant) -> std::time::Duration { + std::fs::read_to_string("/proc/thread-self/schedstat") + .ok() + .and_then(|s| s.split_whitespace().next()?.parse().ok()) + .map_or_else(|| start.elapsed(), std::time::Duration::from_nanos) +} + +fn median(mut v: Vec) -> std::time::Duration { + v.sort(); + v[v.len() / 2] +} + +/// Timing, not a check: SVG export of a large document with each writer laying the type out again +/// and with one layout handed to them, alternating, seven runs each; and grouping the glyphs of +/// type with 1,000 runs by run, one filter per run against one pass. Run with +/// `cargo test --release -p vectorcraft-svg --lib svg_type_layout_timing -- --ignored --nocapture`. +#[test] +#[ignore = "timing"] +fn svg_type_layout_timing() { + let mut d = Document::new(2000.0, 2000.0); + let l = d.layers[0].id; + let add = |d: &mut Document, t: TextObject, items: Vec| { + let mut n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t))); + n.appearance.items = items; + d.insert(Some(l), usize::MAX, n).unwrap(); + }; + let words: String = "Type set along a path for timing. ".chars().cycle().take(60).collect(); + for _ in 0..1000 { + add(&mut d, on_path(&words, style()), vec![]); + } + let hebrew = "abc \u{5D0}\u{5D1}\u{5D2}\u{5D3} def ".repeat(6); + for _ in 0..1000 { + add(&mut d, point(&hebrew.chars().take(80).collect::()), vec![]); + } + for _ in 0..300 { + add(&mut d, TextObject::point(Point::new(20.0, 20.0), "Stroked outside", stroked(StrokeAlign::Outside)), vec![]); + } + let mut runs = point(""); + runs.runs = (0..1000).map(|i| TextRun::new(if i % 9 == 8 { " " } else { "x" }, CharStyle { size: 8.0 + f64::from(i % 3), ..style() })).collect(); + let mut outlined = Document::new(2000.0, 2000.0); + let ol = outlined.layers[0].id; + for _ in 0..300 { + let n = Node::new(outlined.alloc_id(), NodeKind::Text(Box::new(runs.clone()))); + outlined.insert(Some(ol), usize::MAX, n).unwrap(); + } + let docs = [ + ("1,000 on a path, 1,000 bidirectional, 300 outside strokes", &d, crate::ExportOptions::default()), + ("300 texts of 1,000 runs as outlines", &outlined, crate::ExportOptions { outline_text: true, ..crate::ExportOptions::default() }), + ]; + for (name, doc, opts) in docs { + let (one, again) = (export_counting(doc, &opts, false), export_counting(doc, &opts, true)); + assert_eq!(one.0.svg, again.0.svg, "{name}"); + let (mut base, mut handed) = (vec![], vec![]); + for _ in 0..7 { + for (again, times) in [(true, &mut base), (false, &mut handed)] { + let start = std::time::Instant::now(); + let t0 = thread_time(start); + let _ = export_counting(doc, &opts, again); + times.push(thread_time(start) - t0); + } + } + let (from, to, base_median, handed_median) = (again.1, one.1, median(base.clone()), median(handed.clone())); + println!( + "{name}: layouts {from} -> {to}; laid out again {base:?} (median {base_median:?}); one layout {handed:?} (median {handed_median:?})" + ); + } + // The glyphs of one 1,000-run text, grouped by run 300 times. + let lay = vectorcraft_text::layout(FontDb::global(), &runs); + let (mut filtered, mut bucketed) = (vec![], vec![]); + for _ in 0..7 { + let start = std::time::Instant::now(); + let t0 = thread_time(start); + for _ in 0..300 { + for i in 0..runs.runs.len() { + for g in lay.glyphs.iter().filter(|g| g.run == i) { + std::hint::black_box(g); + } + } + } + filtered.push(thread_time(start) - t0); + let start = std::time::Instant::now(); + let t0 = thread_time(start); + for _ in 0..300 { + let mut run_glyphs = vec![Vec::new(); runs.runs.len()]; + for g in &lay.glyphs { + if let Some(gs) = run_glyphs.get_mut(g.run) { + gs.push(g); + } + } + for g in run_glyphs.iter().flatten() { + std::hint::black_box(g); + } + } + bucketed.push(thread_time(start) - t0); + } + println!( + "grouping 300 texts of 1,000 runs: filter per run {filtered:?} (median {:?}); one pass {bucketed:?} (median {:?})", + median(filtered.clone()), + median(bucketed.clone()) + ); +} diff --git a/crates/svg/src/import.rs b/crates/svg/src/import.rs index aaeac31a11..5e7afdd55a 100644 --- a/crates/svg/src/import.rs +++ b/crates/svg/src/import.rs @@ -208,6 +208,7 @@ pub(crate) fn import_finding( blends: fx::blends(&xml, &scan.markers), filter_sources: fx::sources(&xml, &scan.markers, |h| files.data_href(h)), files, + image_keys: HashMap::new(), non_scaling: found.non_scaling, data: found.data, events: found.events, @@ -371,6 +372,9 @@ struct Importer { filter_sources: HashMap, /// The files `` elements link to. files: files::Files, + /// The image key of each raster image usvg got, by the address of its bytes, with the bytes + /// held so that the address isn't given to other bytes during the import. + image_keys: HashMap>, String)>, /// Ids of the shapes whose strokes don't scale ([`vector_effect`]). non_scaling: HashSet, /// The `data-*` attributes of elements, by id ([`user_data`]). diff --git a/crates/svg/src/import/importer.rs b/crates/svg/src/import/importer.rs index c1dd856559..7cf350e5e1 100644 --- a/crates/svg/src/import/importer.rs +++ b/crates/svg/src/import/importer.rs @@ -780,6 +780,7 @@ impl Importer { usvg::ImageKind::WEBP(d) => (d, "image/webp"), usvg::ImageKind::SVG(tree) => return self.svg_image(tree, acc), }; + let source = bytes; let size = i.size(); let (pw, ph) = vectorcraft_doc::header_size(bytes).unwrap_or((size.width().round().max(1.0) as u32, size.height().round().max(1.0) as u32)); // A turned CMYK image is stored as the CMYK TIFF of its inks, the size of the PNG usvg got. @@ -792,10 +793,7 @@ impl Importer { let linked = self.files.linked(i.kind()); let missing = linked.is_some_and(|l| l.missing); let link = linked.map(|l| l.link.clone()); - let key = match &link { - Some(l) => linked_key(bytes, &l.path), - None => format!("img-{:016x}", fnv1a(bytes)), - }; + let key = self.image_key(source, bytes, link.as_ref().map(|l| l.path.as_str())); self.doc.images.entry(key.clone()).or_insert_with(|| { let blob = ImageBlob { mime: mime.into(), bytes: bytes.clone(), proxy: missing.then(|| bytes.clone()) }; if link.is_some() && !missing { blob.with_proxy() } else { blob } @@ -813,6 +811,29 @@ impl Importer { Some(node) } + /// The image key of the raster image usvg got as `source`, stored as `bytes` (the CMYK TIFF + /// that replaces a turned CMYK image, else `source`), linked to `path` when it is linked. The + /// bytes are hashed for the first image that shows `source`; the images after it that show + /// the same bytes get the key kept for it. + fn image_key(&mut self, source: &Arc>, bytes: &[u8], path: Option<&str>) -> String { + let at = Arc::as_ptr(source) as usize; + #[cfg(test)] + let kept = !tests::UNKEPT.get(); + #[cfg(not(test))] + let kept = true; + if kept && let Some((_, key)) = self.image_keys.get(&at) { + return key.clone(); + } + #[cfg(test)] + tests::IMAGE_HASHES.set(tests::IMAGE_HASHES.get() + 1); + let key = match path { + Some(path) => linked_key(bytes, path), + None => format!("img-{:016x}", fnv1a(bytes)), + }; + self.image_keys.insert(at, (source.clone(), key.clone())); + key + } + /// An SVG shown as an image (a data URL or a linked file) → its art, `acc` mapping its size. /// Its ids are its own: they mean nothing in the SVG around it. fn svg_image(&mut self, tree: &usvg::Tree, acc: Affine) -> Option { @@ -870,6 +891,7 @@ mod tests { blends: HashMap::new(), filter_sources: HashMap::new(), files: Files::default(), + image_keys: HashMap::new(), non_scaling: HashSet::new(), data: HashMap::new(), events: HashMap::new(), @@ -891,4 +913,242 @@ mod tests { assert!(matches!(im.error, Some(SvgError::TooManyImages(crate::MAX_NESTED_SVG_IMAGES)))); assert_eq!(im.error.unwrap().to_string(), "the SVG expands to more than 256 nested SVG images"); } + + thread_local! { + /// How many times this thread's imports hashed an image's bytes for its key. + pub(super) static IMAGE_HASHES: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// When set, this thread's imports hash the bytes of every image for its key, without + /// the keys kept for earlier images. + pub(super) static UNKEPT: std::cell::Cell = const { std::cell::Cell::new(false) }; + } + + /// `svg` imported on this thread with `opts`, with image keys kept or not, and how many times + /// image bytes were hashed for keys. + fn import_counting(svg: &str, opts: &crate::ImportOptions, kept: bool) -> (Document, Vec, usize) { + UNKEPT.set(!kept); + IMAGE_HASHES.set(0); + let imported = crate::import::import(svg, opts, crate::MAX_NODES); + UNKEPT.set(false); + let (doc, warnings) = imported.unwrap(); + (doc, warnings, IMAGE_HASHES.get()) + } + + /// The image objects of `doc` in paint order. + fn image_objects(doc: &Document) -> Vec { + let mut out = vec![]; + doc.walk(|n| { + if let NodeKind::Image(im) = &n.kind { + out.push((**im).clone()); + } + }); + out + } + + fn svg_of(body: &str) -> String { + format!(r#"{body}"#) + } + + /// A `w` × `h` PNG of pixels made from `seed`. + fn png(w: u32, h: u32, seed: u32) -> Vec { + let mut state = seed.wrapping_mul(2_654_435_761).wrapping_add(1); + let img = image::RgbaImage::from_fn(w, h, |_, _| { + state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + let [r, g, b, _] = state.to_le_bytes(); + image::Rgba([r, g, b, 255]) + }); + let mut out = vec![]; + img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + out + } + + fn data_url(mime: &str, bytes: &[u8]) -> String { + format!("data:{mime};base64,{}", crate::base64_encode(bytes)) + } + + /// A little-endian, uncompressed 1 × 1 CMYK TIFF of the inks `cmyk`. + fn cmyk_tiff(cmyk: [u8; 4]) -> Vec { + let entry = |tag: u16, kind: u16, count: u32, value: u32| { + [&tag.to_le_bytes()[..], &kind.to_le_bytes(), &count.to_le_bytes(), &value.to_le_bytes()].concat() + }; + let entries = 11u16; + let bits_at = 8 + 2 + u32::from(entries) * 12 + 4; + let data_at = bits_at + 8; + let mut out = [b"II".as_slice(), &[0x2a, 0], &8u32.to_le_bytes(), &entries.to_le_bytes()].concat(); + for e in [ + entry(256, 4, 1, 1), + entry(257, 4, 1, 1), + entry(258, 3, 4, bits_at), + entry(259, 3, 1, 1), + entry(262, 3, 1, 5), + entry(273, 4, 1, data_at), + entry(274, 3, 1, 1), + entry(277, 3, 1, 4), + entry(278, 4, 1, 1), + entry(279, 4, 1, 4), + entry(284, 3, 1, 1), + ] { + out.extend(e); + } + out.extend(0u32.to_le_bytes()); + for _ in 0..4 { + out.extend(8u16.to_le_bytes()); + } + assert_eq!(out.len(), data_at as usize); + out.extend(cmyk); + out + } + + /// `svg` imported with `opts` hashes image bytes `hashes` times for keys, and once for each + /// image without kept keys; both imports give the same document and warnings. + fn same_as_hashing_every_image(svg: &str, opts: &crate::ImportOptions, hashes: usize) -> (Document, Vec) { + let (doc, warnings, n) = import_counting(svg, opts, true); + let (every, every_warnings, every_n) = import_counting(svg, opts, false); + assert_eq!(every_n, image_objects(&every).len(), "without kept keys, each image is hashed"); + assert_eq!(n, hashes, "image bytes hashed for keys"); + assert_eq!(warnings, every_warnings); + assert_eq!(image_objects(&doc), image_objects(&every), "the same image objects"); + assert_eq!(doc.images, every.images, "the same stored images"); + assert!(doc == every, "the same document"); + (doc, warnings) + } + + /// Every `` of one image, and every `` with the same data URL, shows bytes usvg + /// got once: they are hashed once, and every image has the key of the image's bytes. + #[test] + fn an_image_shown_many_times_is_hashed_once() { + let png = png(3, 2, 1); + let href = data_url("image/png", &png); + let uses: String = (0..6).map(|i| format!(r##""##, i * 10)).collect(); + let inline: String = (0..6).map(|i| format!(r#""#, i * 10)).collect(); + for body in [format!(r#"{uses}"#), inline] { + let (doc, warnings) = same_as_hashing_every_image(&svg_of(&body), &crate::ImportOptions::default(), 1); + assert!(warnings.is_empty(), "{warnings:?}"); + let objects = image_objects(&doc); + assert_eq!(objects.len(), 6); + let key = format!("img-{:016x}", fnv1a(&png)); + assert!(objects.iter().all(|o| o.key == key && o.link.is_none() && (o.width, o.height) == (3, 2)), "{objects:?}"); + assert_eq!(doc.images.keys().collect::>(), [&key]); + assert_eq!((doc.images[&key].mime.as_str(), &**doc.images[&key].bytes, doc.images[&key].proxy.is_none()), ("image/png", &png[..], true)); + } + } + + /// One image is hashed once; two images of different bytes twice, with keys of their own; two + /// data URLs written differently that hold the same bytes are hashed once each, and share the + /// key and the stored image of those bytes. + #[test] + fn each_buffer_of_image_bytes_is_hashed_once() { + let (a, b) = (png(2, 2, 1), png(2, 2, 2)); + let image = |href: &str| format!(r#""#); + let opts = crate::ImportOptions::default(); + let (doc, _) = same_as_hashing_every_image(&svg_of(&image(&data_url("image/png", &a))), &opts, 1); + assert_eq!(image_objects(&doc)[0].key, format!("img-{:016x}", fnv1a(&a))); + let two = [image(&data_url("image/png", &a)), image(&data_url("image/png", &b)), image(&data_url("image/png", &a))].concat(); + let (doc, _) = same_as_hashing_every_image(&svg_of(&two), &opts, 2); + let keys: Vec = image_objects(&doc).into_iter().map(|o| o.key).collect(); + assert_eq!(keys, [format!("img-{:016x}", fnv1a(&a)), format!("img-{:016x}", fnv1a(&b)), format!("img-{:016x}", fnv1a(&a))]); + assert_eq!(doc.images.len(), 2); + let spelled = [image(&data_url("image/png", &a)), image(&data_url("image/png;x=y", &a))].concat(); + let (doc, _) = same_as_hashing_every_image(&svg_of(&spelled), &opts, 2); + let keys: Vec = image_objects(&doc).into_iter().map(|o| o.key).collect(); + assert_eq!(keys, [format!("img-{:016x}", fnv1a(&a)), format!("img-{:016x}", fnv1a(&a))]); + assert_eq!(doc.images.len(), 1); + } + + /// Every image of one linked file, or of one missing file, is hashed once: the file is read + /// once, and every image has the key of its bytes and its path, with its link. + #[test] + fn a_linked_or_missing_file_shown_many_times_is_hashed_once() { + let png = png(4, 2, 3); + let reads = std::sync::atomic::AtomicUsize::new(0); + let read = |path: &str| { + reads.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + path.ends_with("a.png").then(|| (png.clone(), vectorcraft_doc::LinkInfo::new(path))) + }; + let opts = crate::ImportOptions { folder: Some("/f"), read: Some(&read) }; + for (name, missing) in [("a.png", false), ("gone.png", true)] { + let body: String = (0..5).map(|i| format!(r#""#, i * 10)).collect(); + reads.store(0, std::sync::atomic::Ordering::Relaxed); + let (doc, warnings) = same_as_hashing_every_image(&svg_of(&body), &opts, 1); + assert_eq!(reads.load(std::sync::atomic::Ordering::Relaxed), 2, "{name}: one read for each of the two imports"); + assert_eq!(warnings.iter().any(|w| w.contains(name)), missing, "{name}: {warnings:?}"); + let objects = image_objects(&doc); + assert_eq!(objects.len(), 5); + let path = objects[0].link.as_ref().expect("linked").path.clone(); + assert!(path.ends_with(name), "{path}"); + let stored = doc.images[&objects[0].key].clone(); + assert_eq!(objects[0].key, linked_key(&stored.bytes, &path), "{name}"); + assert!(objects.iter().all(|o| o.key == objects[0].key && o.link.as_ref().is_some_and(|l| l.path == path)), "{name}"); + assert_eq!(doc.images.len(), 1); + assert_eq!(*stored.bytes == png, !missing, "{name}: the file's bytes, or a placeholder"); + assert_eq!(stored.is_proxy(), missing, "{name}"); + } + } + + /// A CMYK TIFF shown many times is stored as a CMYK TIFF and hashed once, its key that of the + /// stored TIFF. + #[test] + fn a_cmyk_image_shown_many_times_is_hashed_once() { + let tif = cmyk_tiff([255, 0, 0, 0]); + let href = data_url("image/tiff", &tif); + let uses: String = (0..4).map(|i| format!(r##""##, i * 10)).collect(); + let body = format!(r#"{uses}"#); + let (doc, _) = same_as_hashing_every_image(&svg_of(&body), &crate::ImportOptions::default(), 1); + let objects = image_objects(&doc); + assert_eq!(objects.len(), 4); + let blob = &doc.images[&objects[0].key]; + assert_eq!(blob.mime, "image/tiff"); + assert!(blob.cmyk().is_some(), "stored with its inks"); + assert_eq!(objects[0].key, format!("img-{:016x}", fnv1a(&blob.bytes))); + assert!(objects.iter().all(|o| o.key == objects[0].key)); + } + + /// This thread's CPU time in seconds where the system reports it, else the time since a first + /// call. + fn cpu_seconds() -> f64 { + static START: std::sync::OnceLock = std::sync::OnceLock::new(); + let schedstat = std::fs::read_to_string("/proc/thread-self/schedstat").ok(); + match schedstat.as_deref().and_then(|s| s.split_whitespace().next()?.parse::().ok()) { + Some(ns) => ns / 1e9, + None => START.get_or_init(std::time::Instant::now).elapsed().as_secs_f64(), + } + } + + /// The import's time for one PNG data URL shown by many `` elements, hashing every image + /// and keeping keys alternating in one process: `cargo test --release -p vectorcraft-svg --lib + /// importer::tests::image_key_timing -- --ignored --nocapture`. + #[test] + #[ignore = "timing, run by hand"] + fn image_key_timing() { + for (side, uses) in [(512, 100), (1024, 500)] { + let png = png(side, side, 7); + let refs: String = (0..uses).map(|i| format!(r##""##, i % 20, i / 20)).collect(); + let svg = svg_of(&format!(r#"{refs}"#, data_url("image/png", &png))); + let run = |kept: bool| { + let t = cpu_seconds(); + let (doc, _, _) = import_counting(&svg, &crate::ImportOptions::default(), kept); + let spent = cpu_seconds() - t; + assert_eq!(image_objects(&doc).len(), uses); + spent + }; + run(false); + run(true); + let (mut every, mut kept) = (vec![], vec![]); + for round in 0..7 { + if round % 2 == 0 { + every.push(run(false)); + kept.push(run(true)); + } else { + kept.push(run(true)); + every.push(run(false)); + } + } + let median = |v: &mut Vec| { + v.sort_by(f64::total_cmp); + v[v.len() / 2] + }; + let ms = |v: &[f64]| v.iter().map(|s| format!("{:.1}", s * 1e3)).collect::>().join(" "); + println!("{uses} uses of a {} byte PNG: every image {} ms, kept {} ms", png.len(), ms(&every), ms(&kept)); + println!("{uses} uses: median every image {:.1} ms, kept {:.1} ms", median(&mut every) * 1e3, median(&mut kept) * 1e3); + } + } } diff --git a/crates/svg/tests/it/effects_export.rs b/crates/svg/tests/it/effects_export.rs index c1a19e8d53..9a0f2aaeba 100644 --- a/crates/svg/tests/it/effects_export.rs +++ b/crates/svg/tests/it/effects_export.rs @@ -145,3 +145,52 @@ fn geometry_effects_on_type_export_as_its_reshaped_outlines() { assert!(!svg.contains(") { + use vectorcraft_doc::AppearanceItem; + let solid = |p: &Paint, r: f32, g: f32, b: f32| matches!(p, Paint::Solid { color, .. } if *color == Color::rgb(r, g, b)); + for i in &n.appearance.items { + let mark = match i { + AppearanceItem::Fill(f) if solid(&f.paint, 0.0, 0.0, 1.0) => 'b', + AppearanceItem::Fill(f) if solid(&f.paint, 1.0, 0.0, 0.0) => 'r', + AppearanceItem::Stroke(s) if s.width > 0.0 && solid(&s.paint, 0.0, 1.0, 0.0) => 'g', + _ => continue, + }; + if out.last() != Some(&(mark, clipped)) { + out.push((mark, clipped)); + } + } + let clips = matches!(n.kind, NodeKind::Group { clip: true, .. }); + for c in n.children().into_iter().flatten().skip(usize::from(clips)) { + painted_order(c, clipped || clips, out); + } +} + +#[test] +fn painted_clipping_type_exports_with_group_effect() { + // Type filled blue and stroked green clips a red square in a group with an Offset Path effect: + // the SVG paints the type's fill inside the clip behind the square, and its stroke over the + // clipped art, outside the clip. + let blue = Paint::solid(Color::rgb(0.0, 0.0, 1.0)); + let green = Paint::solid(Color::rgb(0.0, 1.0, 0.0)); + let style = CharStyle { size: 40.0, fill: blue, stroke: green, stroke_width: 2.0, ..Default::default() }; + let mut d = Document::new(200.0, 200.0); + let text = Node::new(d.alloc_id(), NodeKind::Text(Box::new(TextObject::point(Point::new(5.0, 60.0), "IIII", style)))); + let red = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0); + let square = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 200.0, 200.0)), red); + let clip = Node::new(d.alloc_id(), NodeKind::Group { children: vec![std::sync::Arc::new(text), std::sync::Arc::new(square)], clip: true }); + let mut outer = Node::group(d.alloc_id(), vec![std::sync::Arc::new(clip)]); + outer.appearance.effects.push(Effect { params: json!({"offset": 1}), ..fx("path.offsetPath") }); + let l = d.layers[0].id; + d.insert(Some(l), 0, outer).unwrap(); + let svg = export(&d, &ExportOptions::default()); + let back = vectorcraft_svg::import(&svg).unwrap_or_else(|e| panic!("{e}: {svg}")); + let mut order = vec![]; + for layer in &back.layers { + painted_order(layer, false, &mut order); + } + assert_eq!(order, [('b', true), ('r', true), ('g', false)], "{svg}"); +} 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 cc8881d2d9..5029a79910 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}; #[cfg(test)] use inflate::GRID_WORK; @@ -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 } } } @@ -249,21 +253,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", } } @@ -296,6 +303,10 @@ 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 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`]). + pub surface: 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 /// 0.001 pt off one plane (a piece of a twisted wall) or reach the eye. @@ -384,6 +395,8 @@ 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, plane: face.plane, #[cfg(test)] view: vec![], diff --git a/crates/three-d/src/solid/build.rs b/crates/three-d/src/solid/build.rs index d734161343..29d5debcc3 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, @@ -211,6 +212,7 @@ impl<'a> Builder<'a> { side: false, away: behind, end: None, + surface: None, plane, #[cfg(test)] view, @@ -249,11 +251,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], @@ -261,6 +265,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. @@ -295,6 +300,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() @@ -353,6 +373,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 { @@ -667,7 +694,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 }; @@ -684,7 +721,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 { @@ -705,6 +743,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 0d9566e5e5..b32faf1097 100644 --- a/crates/three-d/src/solid/tests.rs +++ b/crates/three-d/src/solid/tests.rs @@ -438,9 +438,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/addons/anchor_eraser.rs b/crates/tools/src/addons/anchor_eraser.rs index 1eae255bc2..114e2b8e7a 100644 --- a/crates/tools/src/addons/anchor_eraser.rs +++ b/crates/tools/src/addons/anchor_eraser.rs @@ -152,6 +152,16 @@ impl Tool for AnchorEraserTool { _ => {} } } + + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + use crate::option_check as c; + match key { + "size" => c::number(key, v, SIZE_RANGE.0, SIZE_RANGE.1), + "tolerance" => c::number(key, v, TOLERANCE_RANGE.0, TOLERANCE_RANGE.1), + "pressure" => c::boolean(key, v), + _ => Err(c::unknown(key)), + } + } } #[cfg(test)] diff --git a/crates/tools/src/addons/box3d.rs b/crates/tools/src/addons/box3d.rs index b0ecdc350e..e4f4b272c5 100644 --- a/crates/tools/src/addons/box3d.rs +++ b/crates/tools/src/addons/box3d.rs @@ -729,4 +729,33 @@ impl Tool for Box3dTool { _ => {} } } + + /// The options within their ranges. Any finite arc angle is taken: it is kept from 0 to 360°. + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + use crate::option_check as c; + let max_radius = crate::shape::MAX_CORNER_RADIUS; + match key { + "shape" => c::one_of(key, v, &["box3d", "rectangle", "ellipse", "polygon", "star", "spiral"]), + "cornerRadius" => c::number(key, v, 0.0, max_radius), + "cornerRadii" => { + let radii = v.as_array().filter(|a| a.len() == 4); + if radii.is_some_and(|a| a.iter().all(|r| r.as_f64().is_some_and(|r| r.is_finite() && (0.0..=max_radius).contains(&r)))) { + Ok(()) + } else { + Err(format!("`cornerRadii` must be four numbers from 0 to {max_radius}")) + } + } + "arcStart" | "arcEnd" => c::finite(key, v), + "arcMode" => c::one_of(key, v, &["whole", "pie", "chord", "arc"]), + "sides" | "points" => c::whole(key, v, 3, 1000), + "starRatio" => c::number(key, v, 0.01, 1.0), + "rounded" | "randomized" => c::number(key, v, -10.0, 10.0), + "turns" => c::number(key, v, 0.01, 1024.0), + "divergence" => c::number(key, v, 0.0, 1000.0), + "innerRadius" => c::number(key, v, 0.0, 0.999), + "angleX" | "angleY" | "angleZ" => c::number(key, v, -180.0, 180.0), + "cornerSymmetry" | "polyIsStar" | "clockwise" | "parallelX" | "parallelY" | "parallelZ" => c::boolean(key, v), + _ => Err(c::unknown(key)), + } + } } diff --git a/crates/tools/src/addons/contour.rs b/crates/tools/src/addons/contour.rs index e77bb29eed..3bac5a6649 100644 --- a/crates/tools/src/addons/contour.rs +++ b/crates/tools/src/addons/contour.rs @@ -248,6 +248,15 @@ impl Tool for ContourTool { } } + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + match key { + "corners" if value.as_str().and_then(Corners::parse).is_some() => Ok(()), + "corners" => Err("`corners` must be one of `sharp`, `round`, `square`".into()), + "miterLimit" => crate::option_check::number(key, value, 1.0, 500.0), + _ => Err(crate::option_check::unknown(key)), + } + } + fn busy(&self) -> bool { self.drag.is_some() } diff --git a/crates/tools/src/addons/corner_tool.rs b/crates/tools/src/addons/corner_tool.rs index 470795579e..05ec27b18b 100644 --- a/crates/tools/src/addons/corner_tool.rs +++ b/crates/tools/src/addons/corner_tool.rs @@ -382,6 +382,16 @@ impl Tool for CornerTool { _ => {} } } + + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + use crate::option_check as c; + match key { + "radius" => c::number(key, v, 0.0, MAX_RADIUS), + "kind" if serde_json::from_value::(v.clone()).is_ok() => Ok(()), + "kind" => Err("`kind` must be one of `round`, `invertedRound`, `chamfer`".into()), + _ => Err(c::unknown(key)), + } + } } #[cfg(test)] diff --git a/crates/tools/src/addons/extend_path.rs b/crates/tools/src/addons/extend_path.rs index 816000ac9f..e844da9130 100644 --- a/crates/tools/src/addons/extend_path.rs +++ b/crates/tools/src/addons/extend_path.rs @@ -203,6 +203,14 @@ impl Tool for ExtendPathTool { self.mode = Mode(m); } } + + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + if key != "mode" { + return Err(crate::option_check::unknown(key)); + } + let ids: Vec<&str> = ExtendMode::ALL.iter().map(|m| m.id()).collect(); + crate::option_check::one_of(key, v, &ids) + } } #[cfg(test)] diff --git a/crates/tools/src/addons/parametric_shape.rs b/crates/tools/src/addons/parametric_shape.rs index 33700073c7..e651f5399b 100644 --- a/crates/tools/src/addons/parametric_shape.rs +++ b/crates/tools/src/addons/parametric_shape.rs @@ -475,6 +475,32 @@ impl Tool for ParametricShapeTool { self.next = s; } } + + /// The numbers [`Self::options`] shows, each as [`apply`] checks it; null is not a value. + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + if self.options().get(key).is_none() { + return Err(crate::option_check::unknown(key)); + } + if v.is_null() { + return Err(format!("`{key}` must not be null")); + } + apply(self.next, &json!({ key: v })).map(|_| ()) + } + + /// The options together, as [`apply`] takes them: a `kind` given with them sets the kind + /// first, and the other values are checked against that kind's ranges. + fn check_options(&self, values: &serde_json::Map) -> Result<(), String> { + let options = self.options(); + for (key, v) in values { + if options.get(key).is_none() { + return Err(crate::option_check::unknown(key)); + } + if v.is_null() { + return Err(format!("`{key}` must not be null")); + } + } + apply(self.next, &Value::Object(values.clone())).map(|_| ()) + } } #[cfg(test)] diff --git a/crates/tools/src/addons/shared_edge.rs b/crates/tools/src/addons/shared_edge.rs index d11261800a..703e8e6f3f 100644 --- a/crates/tools/src/addons/shared_edge.rs +++ b/crates/tools/src/addons/shared_edge.rs @@ -214,6 +214,16 @@ impl Tool for SharedEdgeTool { _ => {} } } + + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + use crate::option_check as c; + match key { + "diameter" => c::number(key, v, DIAMETER_RANGE.0, DIAMETER_RANGE.1), + "tolerance" => c::number(key, v, 0.0, MAX_COINCIDENCE), + "together" => c::boolean(key, v), + _ => Err(c::unknown(key)), + } + } } #[cfg(test)] diff --git a/crates/tools/src/addons/smart_pen.rs b/crates/tools/src/addons/smart_pen.rs index 43269ed580..805e015159 100644 --- a/crates/tools/src/addons/smart_pen.rs +++ b/crates/tools/src/addons/smart_pen.rs @@ -625,6 +625,10 @@ impl Tool for SmartPenTool { } } } + + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + if key == "next" { crate::option_check::one_of(key, v, &["curved", "straight"]) } else { Err(crate::option_check::unknown(key)) } + } } #[cfg(test)] diff --git a/crates/tools/src/builder.rs b/crates/tools/src/builder.rs index ea3324dc33..77ff240f75 100644 --- a/crates/tools/src/builder.rs +++ b/crates/tools/src/builder.rs @@ -858,6 +858,9 @@ impl Tool for ShapeBuilderTool { self.cache.clear(); self.cache.gap = self.gap(); } + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + check_builder_options(self.id(), &serde_json::Map::from_iter([(key.to_string(), v.clone())])) + } } /// Why `tool.setOption` cannot give the builder-family tool `tool` the options `values`, checked diff --git a/crates/tools/src/builder/live_paint.rs b/crates/tools/src/builder/live_paint.rs index caa9379308..c694240057 100644 --- a/crates/tools/src/builder/live_paint.rs +++ b/crates/tools/src/builder/live_paint.rs @@ -870,6 +870,10 @@ impl Tool for LivePaintBucketTool { self.hover = LpHover::None; } + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + check_live_paint_options(self.id(), &serde_json::Map::from_iter([(key.to_string(), v.clone())])) + } + fn waiting(&self) -> bool { self.cache.waiting() } @@ -1293,4 +1297,8 @@ impl Tool for LivePaintSelectionTool { } self.hover = LpHover::None; } + + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + check_live_paint_options(self.id(), &serde_json::Map::from_iter([(key.to_string(), v.clone())])) + } } 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/catalog.rs b/crates/tools/src/catalog.rs index 529aa80d18..cd6cbf627a 100644 --- a/crates/tools/src/catalog.rs +++ b/crates/tools/src/catalog.rs @@ -56,6 +56,7 @@ pub const TOOL_GROUPS: &[&[ToolInfo]] = &[ t("rectangle", "Rectangle Tool", Some("M"), "tool-rect"), t("roundedRectangle", "Rounded Rectangle Tool", None, "tool-rounded-rect"), t("ellipse", "Ellipse Tool", Some("L"), "tool-ellipse"), + t(crate::circle::ID, "Circle Tool", None, "tool-circle"), t("polygon", "Polygon Tool", None, "tool-polygon"), t("star", "Star Tool", None, "tool-star"), t("flare", "Flare Tool", None, "tool-flare"), diff --git a/crates/tools/src/circle.rs b/crates/tools/src/circle.rs new file mode 100644 index 0000000000..9e467b35d6 --- /dev/null +++ b/crates/tools/src/circle.rs @@ -0,0 +1,309 @@ +//! The Circle tool draws a circle through points it is given (`shape.circleThroughPoints`). +//! +//! Two points are the ends of a diameter: a drag from one to the other, or a click on each. A click +//! on a first point, then a press on a second point dragged to a third, draws the circle through +//! the three. Shift keeps the second point at 45° steps from the first (from General › Constrain +//! Angle), Alt rounds the diameter of a circle drawn on two points to the nearest tick of the +//! rulers at the current zoom, in the General unit, and every point snaps to Smart Guides. Until +//! the release, the tool shows the circle as a dashed outline (solid once it is more than 50,000 +//! screen points around) with its points, its center as a small cross, a line from the center to +//! each point and, with Measurement Labels on, the diameter by the pointer. The circle is one undo +//! step. Escape, a press dropped part way, and an edit, Undo or Redo made outside the tool drop +//! the first point. A second press within 3 screen points +//! of the first point, or one that snaps to it, is a press on it: let go there (a double-click) it +//! places nothing, and dragged out it draws the circle on the diameter it drags out. Where no +//! circle passes through the points (two are the same, three lie on one line) or the circle would +//! reach past the canvas, the tool shows none and the release draws nothing; for three different +//! points on one line, or a circle past the canvas, the pointer shows "Circle too large". + +use serde_json::{Value, json}; +use vectorcraft_doc::MAX_COORD; +use vectorcraft_geom::{Point, Rect, Vec2, shapes}; + +use crate::guides::{DrawSnap, Leave}; +use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; + +pub const ID: &str = "circle"; + +/// How far (screen points) the pointer travels from a press before the press counts as a drag. +const DRAG_PX: f64 = 2.0; +/// Half the length (screen points) of each arm of the cross at the circle's center. +const CROSS_PX: f64 = 4.0; +/// How near (screen points) the first point a second click counts as a click on it. +const REACH_PX: f64 = 3.0; +/// The longest outline (screen points) the preview draws dashed, about 7,000 dashes. +const DASHED_PX: f64 = 50_000.0; + +/// The press in progress. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Press { + /// The first point `at`, pressed with the pointer at `from` (before snapping): a release after + /// a drag draws the circle on that diameter. + First { at: Point, from: Point, dragged: bool }, + /// The second press, after a click placed the first point, with the pointer at `from` (before + /// snapping). `snapped` is the point it snapped to, and `at` that point with Alt's rounding of + /// the diameter. A release without a drag draws the circle on the diameter to `at`; a drag + /// places the third point and the circle passes through `snapped`. A press within + /// [`REACH_PX`] of the first point, or one that snaps to it (`on_first`), is a press on it: let + /// go there it places nothing, and dragged out it draws the circle on the diameter it drags out. + Second { at: Point, snapped: Point, from: Point, on_first: bool, dragged: bool }, +} + +#[derive(Default)] +pub struct CircleTool { + snap: DrawSnap, + /// The first point, placed by a click (or by the press of a drag in progress). + first: Option, + press: Option, + /// Where the pointer is, snapped: the point the next press or release places. + pointer: Option, +} + +/// The command the tool runs for `points`. +fn command(points: &[Point]) -> (String, Value) { + let pairs: Vec = points.iter().map(|p| json!([p.x, p.y])).collect(); + ("shape.circleThroughPoints".into(), json!({ "points": pairs })) +} + +/// The circle through two points (the ends of a diameter) or three, as `shape.circleThroughPoints` +/// draws it: none where no circle passes through them or it would reach past the canvas. +pub fn circle_of(points: &[Point]) -> Option<(Point, f64)> { + let on_canvas = |(c, r): &(Point, f64)| [c.x - r, c.y - r, c.x + r, c.y + r].iter().all(|v| v.abs() <= MAX_COORD); + shapes::circle_through_points(points).filter(on_canvas) +} + +/// With Alt, `p` moved along the line from `first` so that their distance (the diameter) is on +/// the nearest ruler tick at the current zoom, in the General unit; `p` itself without Alt, and +/// when that rounding leaves no distance. +fn round_diameter(cx: &ToolContext, first: Point, p: Point, mods: Mods) -> Point { + let d = first.distance(p); + let rounded = cx.unit.snap_to_ruler_tick(d, cx.zoom); + if mods.alt && d > 0.0 && rounded > 0.0 && rounded.is_finite() { first + (p - first) * (rounded / d) } else { p } +} + +/// Are the points two or more different points through which no circle is drawn: three on one +/// line, or a circle that would reach past the canvas? +fn too_large(points: &[Point]) -> bool { + let distinct = points.iter().enumerate().all(|(i, p)| !points.iter().take(i).any(|q| q == p)); + points.len() >= 2 && distinct && circle_of(points).is_none() +} + +impl CircleTool { + fn clear(&mut self) { + self.first = None; + self.press = None; + self.pointer = None; + self.snap.clear(); + } + + /// How the second point keeps to the first: Shift's 45° steps and the construction guides. + fn leave(&self, cx: &ToolContext, mods: Mods) -> Option { + self.first.map(|a| Leave::segment(cx, a, mods.shift)) + } + + /// The points the circle passes through as the tool shows it now. + fn points(&self) -> Vec { + let mut out: Vec = self.first.into_iter().collect(); + match self.press { + Some(Press::First { .. }) | None => out.extend(self.pointer.filter(|_| self.first.is_some())), + // A press on the first point adds no point: a drag from it drags out a diameter. + Some(Press::Second { on_first: true, dragged, .. }) => out.extend(self.pointer.filter(|_| dragged)), + Some(Press::Second { at, dragged: false, .. }) => out.push(at), + Some(Press::Second { snapped, dragged: true, .. }) => { + out.push(snapped); + out.extend(self.pointer); + } + } + out + } + + /// The second point as the tool shows it: none for a press on the first point. + fn second(&self) -> Option { + match self.press { + Some(Press::Second { on_first: false, dragged: false, at, .. }) => Some(at), + Some(Press::Second { on_first: false, dragged: true, snapped, .. }) => Some(snapped), + _ => None, + } + } + + /// Runs the circle through `points` and starts afresh; where no circle is drawn through them + /// (the tool showed none), it only starts afresh. + fn draw(&mut self, points: &[Point]) -> Vec { + self.clear(); + if circle_of(points).is_none() { + return vec![]; + } + let (c, v) = command(points); + vec![Action::Exec(c, v)] + } + + /// Is the press a drag at `ev`: dragged already, or `ev` is [`DRAG_PX`] or more from the press? + fn drags(&self, cx: &ToolContext, ev: &PointerEvent) -> bool { + match self.press { + Some(Press::First { from, dragged, .. } | Press::Second { from, dragged, .. }) => dragged || ev.pos.distance(from) >= cx.tol(DRAG_PX), + None => false, + } + } +} + +impl Tool for CircleTool { + fn id(&self) -> &'static str { + ID + } + + fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { + if !ev.pos.is_finite() { + return vec![]; + } + // A drag ends where it is let go: the release moves the points as a drag to it would. A + // click, or a release within DRAG_PX of the press, keeps the points of the press. + if ev.kind == PointerKind::Up && self.drags(cx, ev) { + self.pointer(cx, &PointerEvent { kind: PointerKind::Drag, ..*ev }); + } + match ev.kind { + PointerKind::Move => { + let leave = self.leave(cx, ev.mods); + let p = self.snap.hover(cx, ev.pos, &[], leave.as_ref()); + self.pointer = Some(self.first.map_or(p, |a| round_diameter(cx, a, p, ev.mods))); + vec![] + } + PointerKind::Down => { + match self.first { + None => { + let at = self.snap.press(cx, ev.pos, &[], None); + self.first = Some(at); + self.press = Some(Press::First { at, from: ev.pos, dragged: false }); + self.pointer = Some(at); + } + Some(a) => { + let leave = self.leave(cx, ev.mods); + let snapped = self.snap.press(cx, ev.pos, &[], leave.as_ref()); + let at = round_diameter(cx, a, snapped, ev.mods); + let on_first = snapped == a || ev.pos.distance(a) <= cx.tol(REACH_PX); + self.press = Some(Press::Second { at, snapped, from: ev.pos, on_first, dragged: false }); + self.pointer = Some(at); + } + } + vec![] + } + PointerKind::Drag => { + match &mut self.press { + Some(Press::First { at, from, dragged }) => { + *dragged |= ev.pos.distance(*from) >= cx.tol(DRAG_PX); + let leave = Leave::segment(cx, *at, ev.mods.shift); + self.pointer = Some(round_diameter(cx, *at, self.snap.drag(cx, ev.pos, Some(&leave)), ev.mods)); + } + // Dragged from the first point, the pointer is the other end of a diameter, as + // for a drag from a first press. + Some(Press::Second { from, on_first: true, dragged, .. }) => { + *dragged |= ev.pos.distance(*from) >= cx.tol(DRAG_PX); + let leave = self.first.map(|a| Leave::segment(cx, a, ev.mods.shift)); + let p = self.snap.drag(cx, ev.pos, leave.as_ref()); + self.pointer = Some(self.first.map_or(p, |a| round_diameter(cx, a, p, ev.mods))); + } + Some(Press::Second { from, dragged, .. }) => { + *dragged |= ev.pos.distance(*from) >= cx.tol(DRAG_PX); + self.pointer = Some(self.snap.drag(cx, ev.pos, None)); + } + None => {} + } + vec![] + } + PointerKind::Up => match (self.press.take(), self.first, self.pointer) { + (Some(Press::First { at, dragged: true, .. }), _, Some(b)) if b.distance(at) >= cx.tol(DRAG_PX) => self.draw(&[at, b]), + // A click places the first point; the guides of the press go. + (Some(Press::First { .. }), ..) => { + self.snap.clear(); + vec![] + } + // The second click of a double-click lands on the first point and places nothing; + // a drag from there draws the circle on the diameter it drags out. + (Some(Press::Second { on_first: true, dragged: false, .. }), ..) => vec![], + (Some(Press::Second { on_first: true, dragged: true, .. }), Some(a), Some(c)) => self.draw(&[a, c]), + (Some(Press::Second { at, dragged: false, .. }), Some(a), _) => self.draw(&[a, at]), + // Three points: Alt's rounding of the diameter does not apply. + (Some(Press::Second { snapped, dragged: true, .. }), Some(a), Some(c)) => self.draw(&[a, snapped, c]), + _ => vec![], + }, + PointerKind::DoubleClick | PointerKind::TripleClick => vec![], + } + } + + fn key(&mut self, _cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { + if key == ToolKey::Escape { + self.clear(); + } + vec![] + } + + fn claims_key(&self, _cx: &ToolContext, key: ToolKey) -> bool { + key == ToolKey::Escape && self.first.is_some() + } + + /// A first point placed: Escape drops it. + fn ends_on_escape(&self, _cx: &ToolContext) -> bool { + self.first.is_some() + } + + fn busy(&self) -> bool { + self.first.is_some() + } + + /// A dropped press (a second finger, a canceled touch) drops the points placed so far. + fn drop_press(&mut self, _cx: &ToolContext) -> Vec { + self.clear(); + vec![] + } + + fn deactivate(&mut self, _cx: &ToolContext) -> Vec { + self.clear(); + vec![] + } + + fn hover_ended(&mut self, _cx: &ToolContext) { + if self.press.is_none() { + self.pointer = None; + self.snap.clear(); + } + } + + /// An edit, Undo or Redo made outside the tool, or another document, drops the first point. + fn history_moved(&mut self) { + self.clear(); + } + + fn overlays(&self, cx: &ToolContext) -> Vec { + let mut o = self.snap.guides().to_vec(); + let points = self.points(); + let color = crate::draw2::FEEDBACK; + if let Some((c, r)) = circle_of(&points) { + let path = shapes::ellipse(Rect::new(c.x - r, c.y - r, c.x + r, c.y + r)).to_bezpath(); + // The canvas draws a dashed outline dash by dash along its whole length: a circle longer + // than DASHED_PX on screen is drawn solid instead. + let dashed = std::f64::consts::TAU * r <= cx.tol(DASHED_PX); + o.push(Overlay::Path { path, color, width: 1.0, dashed }); + for p in &points { + o.push(Overlay::Line { a: c, b: *p, color, dashed: false }); + } + let arm = cx.tol(CROSS_PX); + o.push(Overlay::Line { a: c - Vec2::new(arm, 0.0), b: c + Vec2::new(arm, 0.0), color, dashed: false }); + o.push(Overlay::Line { a: c - Vec2::new(0.0, arm), b: c + Vec2::new(0.0, arm), color, dashed: false }); + if let Some(p) = self.pointer.filter(|_| cx.measurement_labels) { + o.push(Overlay::Measure { p: p + Vec2::new(cx.tol(12.0), cx.tol(12.0)), text: format!("D: {}", cx.len(2.0 * r)) }); + } + } else if let Some(p) = self.pointer.filter(|_| too_large(&points)) { + o.push(Overlay::Label { p, text: "Circle too large".into(), color }); + } + for p in self.first.into_iter().chain(self.second()) { + o.push(Overlay::Anchor { p, color, filled: true, size: 6.0 }); + } + o + } + + fn cursor(&self, _cx: &ToolContext, _p: Point, _mods: Mods) -> Cursor { + Cursor::Crosshair + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/tools/src/circle/tests.rs b/crates/tools/src/circle/tests.rs new file mode 100644 index 0000000000..e262d242ef --- /dev/null +++ b/crates/tools/src/circle/tests.rs @@ -0,0 +1,352 @@ +use super::*; +use crate::testutil::*; +use vectorcraft_doc::Selection; + +fn ev(kind: PointerKind, (x, y): (f64, f64), mods: Mods) -> PointerEvent { + PointerEvent::new(kind, x, y).with_mods(mods) +} + +fn click(t: &mut CircleTool, cx: &ToolContext, p: (f64, f64)) -> Vec { + let mut acts = t.pointer(cx, &ev(PointerKind::Down, p, Mods::default())); + acts.extend(t.pointer(cx, &ev(PointerKind::Up, p, Mods::default()))); + acts +} + +/// A press at `from`, dragged through `path` and let go at its last point. +fn drag(t: &mut CircleTool, cx: &ToolContext, from: (f64, f64), path: &[(f64, f64)], mods: Mods) -> Vec { + let mut acts = t.pointer(cx, &ev(PointerKind::Down, from, mods)); + for p in path { + acts.extend(t.pointer(cx, &ev(PointerKind::Drag, *p, mods))); + } + let end = path.last().copied().unwrap_or(from); + acts.extend(t.pointer(cx, &ev(PointerKind::Up, end, mods))); + acts +} + +fn circle(points: &[(f64, f64)]) -> Vec { + let pairs: Vec = points.iter().map(|(x, y)| json!([x, y])).collect(); + vec![Action::Exec("shape.circleThroughPoints".into(), json!({ "points": pairs }))] +} + +/// The dashed circle the tool shows: its bounding box. +fn preview(o: &[Overlay]) -> Option { + o.iter().find_map(|o| match o { + Overlay::Path { path, dashed: true, .. } => Some(vectorcraft_geom::Shape::bounding_box(path)), + _ => None, + }) +} + +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-9) +} + +/// A drag from one point to another draws the circle with those two as the ends of a diameter. +#[test] +fn a_drag_draws_the_circle_on_its_diameter() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CircleTool::default(); + assert_eq!(drag(&mut t, &cx, (300.0, 300.0), &[(340.0, 330.0), (380.0, 360.0)], Mods::default()), circle(&[(300.0, 300.0), (380.0, 360.0)])); + assert!(!t.ends_on_escape(&cx) && t.overlays(&cx).is_empty()); +} + +/// A click places the first point and a second click the other end of the diameter. In between, +/// the tool shows the circle through the first point and the pointer, its center cross, its radii +/// and its diameter. +#[test] +fn two_clicks_draw_the_circle_on_their_diameter() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CircleTool::default(); + assert_eq!(click(&mut t, &cx, (300.0, 300.0)), vec![]); + assert!(t.ends_on_escape(&cx) && t.claims_key(&cx, ToolKey::Escape)); + t.pointer(&cx, &ev(PointerKind::Move, (380.0, 360.0), Mods::default())); + let o = t.overlays(&cx); + // Center (340, 330), radius 50. + assert!(near(preview(&o).expect("the circle is shown"), Rect::new(290.0, 280.0, 390.0, 380.0)), "{o:?}"); + let center = Point::new(340.0, 330.0); + let lines = o.iter().filter(|o| matches!(o, Overlay::Line { a, .. } if *a == center)).count(); + assert_eq!(lines, 2, "a radius to each point: {o:?}"); + assert!(o.iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text.starts_with("D: 100"))), "{o:?}"); + let without_labels = ToolContext { measurement_labels: false, ..cx }; + assert!(!t.overlays(&without_labels).iter().any(|o| matches!(o, Overlay::Measure { .. }))); + assert_eq!(click(&mut t, &cx, (380.0, 360.0)), circle(&[(300.0, 300.0), (380.0, 360.0)])); + assert!(!t.ends_on_escape(&cx)); +} + +/// A click, then a press on a second point dragged to a third, draws the circle through the three. +#[test] +fn a_click_and_a_drag_draw_the_circle_through_three_points() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CircleTool::default(); + click(&mut t, &cx, (300.0, 300.0)); + t.pointer(&cx, &ev(PointerKind::Down, (380.0, 300.0), Mods::default())); + t.pointer(&cx, &ev(PointerKind::Drag, (300.0, 360.0), Mods::default())); + // (300, 300), (380, 300) and (300, 360): the right angle stands on the diameter, center + // (340, 330), radius 50. + let o = t.overlays(&cx); + assert!(near(preview(&o).expect("the circle is shown"), Rect::new(290.0, 280.0, 390.0, 380.0)), "{o:?}"); + assert_eq!(o.iter().filter(|o| matches!(o, Overlay::Anchor { .. })).count(), 2, "{o:?}"); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (300.0, 360.0), Mods::default())), circle(&[(300.0, 300.0), (380.0, 300.0), (300.0, 360.0)])); +} + +/// A drag ends where it is let go, also when the release is away from the last drag: from a first +/// press, from a second press, and from a press on the first point. A release within 2 screen +/// points of a second press is still a click and keeps the point of the press. +#[test] +fn a_drag_ends_where_it_is_let_go() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let (down, drag, up) = (PointerKind::Down, PointerKind::Drag, PointerKind::Up); + let mut t = CircleTool::default(); + t.pointer(&cx, &ev(down, (300.0, 300.0), Mods::default())); + t.pointer(&cx, &ev(drag, (380.0, 300.0), Mods::default())); + assert_eq!(t.pointer(&cx, &ev(up, (400.0, 300.0), Mods::default())), circle(&[(300.0, 300.0), (400.0, 300.0)])); + click(&mut t, &cx, (300.0, 300.0)); + t.pointer(&cx, &ev(down, (380.0, 300.0), Mods::default())); + t.pointer(&cx, &ev(drag, (300.0, 340.0), Mods::default())); + assert_eq!(t.pointer(&cx, &ev(up, (300.0, 360.0), Mods::default())), circle(&[(300.0, 300.0), (380.0, 300.0), (300.0, 360.0)])); + click(&mut t, &cx, (300.0, 300.0)); + t.pointer(&cx, &ev(down, (300.0, 300.0), Mods::default())); + t.pointer(&cx, &ev(drag, (300.0, 380.0), Mods::default())); + assert_eq!(t.pointer(&cx, &ev(up, (300.0, 400.0), Mods::default())), circle(&[(300.0, 300.0), (300.0, 400.0)])); + click(&mut t, &cx, (300.0, 300.0)); + t.pointer(&cx, &ev(down, (380.0, 360.0), Mods::default())); + assert_eq!(t.pointer(&cx, &ev(up, (381.0, 360.0), Mods::default())), circle(&[(300.0, 300.0), (380.0, 360.0)])); +} + +/// Three points on one line show no circle, and the release draws nothing and starts afresh. A +/// circle past the canvas is not shown either. +#[test] +fn points_on_one_line_show_no_circle() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CircleTool::default(); + click(&mut t, &cx, (100.0, 100.0)); + t.pointer(&cx, &ev(PointerKind::Down, (200.0, 200.0), Mods::default())); + t.pointer(&cx, &ev(PointerKind::Drag, (300.0, 300.0), Mods::default())); + assert_eq!(preview(&t.overlays(&cx)), None); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (300.0, 300.0), Mods::default())), vec![]); + assert!(!t.ends_on_escape(&cx) && t.overlays(&cx).is_empty()); + assert_eq!(circle_of(&[Point::new(0.0, 0.0), Point::new(4.1e6, 0.0)]), None); + assert_eq!(circle_of(&[Point::new(0.0, 0.0), Point::new(200.0, 0.0), Point::new(100.0, 0.001)]), None); +} + +/// Shift keeps the second point at 45° steps from the first. +#[test] +fn shift_keeps_the_diameter_at_45_degree_steps() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let shift = Mods { shift: true, ..Mods::default() }; + let mut t = CircleTool::default(); + let acts = drag(&mut t, &cx, (300.0, 300.0), &[(400.0, 310.0)], shift); + let [Action::Exec(_, v)] = acts.as_slice() else { panic!("one circle: {acts:?}") }; + let end = &v["points"][1]; + assert!((end[1].as_f64().unwrap() - 300.0).abs() < 1e-9, "level with the first point: {v}"); +} + +/// Alt rounds the diameter to the nearest ruler tick at the current zoom: every 5 pt at 100% and +/// every 2.5 pt at 200% in points, keeping the direction from the first point; for a drag, for a +/// second click and in the preview. +#[test] +fn alt_rounds_the_diameter_to_ruler_ticks() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let alt = Mods { alt: true, ..Mods::default() }; + // The second point of the one circle `acts` draws. + let second = |acts: Vec| { + let [Action::Exec(_, v)] = acts.as_slice() else { panic!("one circle: {acts:?}") }; + Point::new(v["points"][1][0].as_f64().unwrap(), v["points"][1][1].as_f64().unwrap()) + }; + let mut t = CircleTool::default(); + let end = second(drag(&mut t, &cx, (300.0, 300.0), &[(373.0, 300.0)], alt)); + assert!(end.distance(Point::new(375.0, 300.0)) < 1e-9, "{end:?}"); + // (31.2, 41.6) is 52 from the origin, and Alt makes it 50: (30, 40). + click(&mut t, &cx, (0.0, 0.0)); + t.pointer(&cx, &ev(PointerKind::Move, (31.2, 41.6), alt)); + assert!(near(preview(&t.overlays(&cx)).expect("the circle is shown"), Rect::new(-10.0, -5.0, 40.0, 45.0)), "{:?}", t.overlays(&cx)); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Down, (31.2, 41.6), alt)), vec![]); + let end = second(t.pointer(&cx, &ev(PointerKind::Up, (31.2, 41.6), alt))); + assert!(end.distance(Point::new(30.0, 40.0)) < 1e-9, "{end:?}"); + let zoomed = ToolContext { zoom: 2.0, ..cx }; + for (to, want) in [(51.0, 50.0), (51.5, 52.5)] { + let end = second(drag(&mut t, &zoomed, (0.0, 0.0), &[(0.0, to)], alt)); + assert!(end.distance(Point::new(0.0, want)) < 1e-9, "{to}: {end:?}"); + } + // Without Alt the pointer is used as it is. + assert_eq!(drag(&mut t, &cx, (300.0, 300.0), &[(373.0, 300.0)], Mods::default()), circle(&[(300.0, 300.0), (373.0, 300.0)])); +} + +/// Alt rounds only a diameter: a second press dragged to a third point keeps the second point +/// where it was pressed, and a second press 2.6 pt from the first point, which Alt's rounding +/// would move to 5 pt, is still a press on the first point and places nothing. +#[test] +fn alt_leaves_three_points_and_presses_on_the_first_point_alone() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let alt = Mods { alt: true, ..Mods::default() }; + let mut t = CircleTool::default(); + click(&mut t, &cx, (0.0, 0.0)); + assert_eq!(drag(&mut t, &cx, (31.2, 41.6), &[(45.0, 20.0), (60.0, 0.0)], alt), circle(&[(0.0, 0.0), (31.2, 41.6), (60.0, 0.0)])); + click(&mut t, &cx, (300.0, 300.0)); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Down, (302.6, 300.0), alt)), vec![]); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (302.6, 300.0), alt)), vec![]); + assert!(t.ends_on_escape(&cx), "the first point stays"); +} + +/// Three different points on one line show "Circle too large" by the pointer instead of a circle; +/// a pointer back on the first point does not. +#[test] +fn points_on_one_line_say_the_circle_is_too_large() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let label = |t: &CircleTool| { + t.overlays(&cx).iter().find_map(|o| match o { + Overlay::Label { p, text, .. } => Some((*p, text.clone())), + _ => None, + }) + }; + let mut t = CircleTool::default(); + click(&mut t, &cx, (100.0, 100.0)); + t.pointer(&cx, &ev(PointerKind::Down, (200.0, 200.0), Mods::default())); + t.pointer(&cx, &ev(PointerKind::Drag, (300.0, 300.0), Mods::default())); + assert_eq!(label(&t), Some((Point::new(300.0, 300.0), "Circle too large".to_string()))); + t.pointer(&cx, &ev(PointerKind::Drag, (300.0, 290.0), Mods::default())); + assert_eq!(label(&t), None, "a circle is shown"); + t.pointer(&cx, &ev(PointerKind::Drag, (200.0, 200.0), Mods::default())); + assert_eq!(label(&t), None, "the third point is on the second"); + assert!(too_large(&[Point::new(0.0, 0.0), Point::new(4.1e6, 0.0)])); + assert!(!too_large(&[Point::new(0.0, 0.0)]) && !too_large(&[Point::new(1.0, 0.0), Point::new(1.0, 0.0)])); +} + +/// Escape drops the first point; so do a dropped press and an edit made outside the tool. A +/// second click on the first point places nothing. +#[test] +fn escape_and_outside_edits_drop_the_first_point() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CircleTool::default(); + click(&mut t, &cx, (300.0, 300.0)); + assert_eq!(click(&mut t, &cx, (300.5, 300.0)), vec![], "a double-click places one point"); + assert!(t.ends_on_escape(&cx)); + t.key(&cx, ToolKey::Escape, Mods::default()); + assert!(!t.ends_on_escape(&cx) && t.overlays(&cx).is_empty()); + click(&mut t, &cx, (300.0, 300.0)); + t.history_moved(); + assert!(!t.ends_on_escape(&cx)); + click(&mut t, &cx, (300.0, 300.0)); + t.pointer(&cx, &ev(PointerKind::Down, (380.0, 300.0), Mods::default())); + t.drop_press(&cx); + assert!(!t.ends_on_escape(&cx)); + // After all of that, two clicks start a new circle. + click(&mut t, &cx, (10.0, 10.0)); + assert_eq!(click(&mut t, &cx, (30.0, 10.0)), circle(&[(10.0, 10.0), (30.0, 10.0)])); +} + +/// The points snap to Smart Guides: a press near the rectangle's corner anchor at (100, 100) places +/// the point on it. +#[test] +fn points_snap_to_smart_guides() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let mut t = CircleTool::default(); + t.pointer(&cx, &ev(PointerKind::Move, (101.0, 101.5), Mods::default())); + click(&mut t, &cx, (101.0, 101.5)); + assert_eq!(click(&mut t, &cx, (300.0, 100.0)), circle(&[(100.0, 100.0), (300.0, 100.0)])); +} + +/// A click is measured from where the pointer was pressed, not from the point it snapped to: a +/// second press pulled 1.8 pt onto the corner anchor at (100, 100) and moved 0.5 pt before the +/// release still draws the circle on that diameter. +#[test] +fn a_snapped_second_click_is_not_a_drag() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let mut t = CircleTool::default(); + click(&mut t, &cx, (300.0, 100.0)); + t.pointer(&cx, &ev(PointerKind::Down, (101.0, 101.5), Mods::default())); + t.pointer(&cx, &ev(PointerKind::Drag, (101.5, 101.5), Mods::default())); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (101.5, 101.5), Mods::default())), circle(&[(300.0, 100.0), (100.0, 100.0)])); +} + +/// A second press within 3 screen points of the first point is a press on it: dragged out, it +/// draws the circle on the diameter it drags out, whether it landed on the first point or next to +/// it; a press farther away and dragged places the second and third points. +#[test] +fn a_drag_from_the_first_point_draws_the_circle_on_its_diameter() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CircleTool::default(); + click(&mut t, &cx, (300.0, 300.0)); + let acts = drag(&mut t, &cx, (301.0, 300.0), &[(300.0, 350.0), (300.0, 400.0)], Mods::default()); + assert_eq!(acts, circle(&[(300.0, 300.0), (300.0, 400.0)])); + click(&mut t, &cx, (300.0, 300.0)); + let acts = drag(&mut t, &cx, (304.0, 300.0), &[(300.0, 350.0), (300.0, 400.0)], Mods::default()); + assert_eq!(acts, circle(&[(300.0, 300.0), (304.0, 300.0), (300.0, 400.0)])); + click(&mut t, &cx, (300.0, 300.0)); + t.pointer(&cx, &ev(PointerKind::Down, (300.0, 300.0), Mods::default())); + t.pointer(&cx, &ev(PointerKind::Drag, (300.0, 400.0), Mods::default())); + assert!(near(preview(&t.overlays(&cx)).expect("the circle is shown"), Rect::new(250.0, 300.0, 350.0, 400.0)), "{:?}", t.overlays(&cx)); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (300.0, 400.0), Mods::default())), circle(&[(300.0, 300.0), (300.0, 400.0)])); +} + +/// A second press farther than 3 screen points from the first point that snaps to it is a press on +/// it too: the first point is the rectangle's corner anchor at (100, 100), and a press 3.2 pt away +/// snaps back to that anchor. +#[test] +fn a_second_press_that_snaps_to_the_first_point_is_a_press_on_it() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let mut t = CircleTool::default(); + click(&mut t, &cx, (100.0, 100.0)); + t.pointer(&cx, &ev(PointerKind::Down, (103.2, 100.0), Mods::default())); + assert_eq!(t.second(), None, "the press snapped to the first point: {:?}", t.press); + t.pointer(&cx, &ev(PointerKind::Drag, (100.0, 150.0), Mods::default())); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (100.0, 150.0), Mods::default())), circle(&[(100.0, 100.0), (100.0, 150.0)])); +} + +/// A circle more than 50,000 screen points around is previewed solid, not dashed: three points +/// nearly on one line give a radius of about 1,250,000 pt. +#[test] +fn a_huge_circle_is_previewed_solid() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CircleTool::default(); + click(&mut t, &cx, (0.0, 0.0)); + t.pointer(&cx, &ev(PointerKind::Down, (1000.0, 0.0), Mods::default())); + t.pointer(&cx, &ev(PointerKind::Drag, (500.0, 0.1), Mods::default())); + let o = t.overlays(&cx); + assert_eq!(preview(&o), None, "{o:?}"); + assert!(o.iter().any(|o| matches!(o, Overlay::Path { dashed: false, .. })), "{o:?}"); + // At 100% a circle 100 pt across is dashed. + t.pointer(&cx, &ev(PointerKind::Drag, (500.0, 300.0), Mods::default())); + assert!(preview(&t.overlays(&cx)).is_some()); +} + +/// The tool is in the Ellipse tool's group, after the Ellipse tool. +#[test] +fn the_circle_tool_follows_the_ellipse_tool() { + let tool = crate::create(ID); + assert_eq!(tool.id(), ID); + let group = crate::catalog::group_of(ID).unwrap(); + assert_eq!(crate::catalog::group_of("ellipse"), Some(group)); + let ids: Vec<&str> = crate::TOOL_GROUPS[group].iter().map(|t| t.id).collect(); + let ellipse = ids.iter().position(|id| *id == "ellipse").unwrap(); + assert_eq!(ids.get(ellipse + 1), Some(&ID)); +} diff --git a/crates/tools/src/cropimage.rs b/crates/tools/src/cropimage.rs index 13691da613..2e23159e5c 100644 --- a/crates/tools/src/cropimage.rs +++ b/crates/tools/src/cropimage.rs @@ -419,6 +419,24 @@ impl Tool for CropImageTool { }; } + /// `rect` is `[x, y, width, height]`, or null to put the box back where it starts. `ppi`, + /// `reference` and `linked` take the values [`check_options`] takes (the selected image's + /// limit on `ppi` is checked by `tool.setOption`, which knows the selection). + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + if matches!(key, "ppi" | "reference" | "linked") { + return check_options(&serde_json::Map::from_iter([(key.to_string(), value.clone())]), None); + } + if key != "rect" { + return Err(crate::option_check::unknown(key)); + } + let numbers = value.as_array().filter(|a| a.len() == 4).and_then(|a| a.iter().map(Value::as_f64).collect::>>()); + match numbers.as_deref() { + _ if value.is_null() => Ok(()), + Some([x, y, w, h]) if [x, y, w, h].iter().all(|n| n.is_finite()) && *w >= 0.0 && *h >= 0.0 => Ok(()), + _ => Err(format!("`{key}` must be [x, y, width, height]: four finite numbers, width and height not negative")), + } + } + fn deactivate(&mut self, _cx: &ToolContext) -> Vec { self.reset(); vec![] @@ -635,6 +653,15 @@ mod tests { ] { assert_eq!(check_options(&values(v.clone()), Some(36.0)), Err(want.to_string()), "{v}"); } + // The tool takes the same values on its own, without an image's limit. + let t = CropImageTool::default(); + for (k, v) in [("ppi", json!(72)), ("ppi", json!(null)), ("reference", json!(0)), ("linked", json!(true)), ("rect", json!(null))] { + assert_eq!(t.check_option(k, &v), Ok(()), "{k}: {v}"); + } + assert_eq!(t.check_option("reference", &json!(9)), Err("`reference` must be a whole number from 0 to 8, not 9".into())); + assert_eq!(t.check_option("linked", &json!(1)), Err("`linked` must be true or false, not 1".into())); + assert_eq!(t.check_option("ppi", &json!(2401)), Err("`ppi` must be a number from 1 to 2400 or null, not 2401".into())); + assert_eq!(t.check_option("size", &json!(1)), Err("unknown option `size`".into())); } /// An image's own resolution, and the most it can be cropped to. diff --git a/crates/tools/src/cut.rs b/crates/tools/src/cut.rs index 906a632fb3..514e41e4c0 100644 --- a/crates/tools/src/cut.rs +++ b/crates/tools/src/cut.rs @@ -214,6 +214,15 @@ impl Tool for CutTool { _ => {} } } + /// Mirror & Cut's `axis` and `keep`; the other cutting tools have no options. + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + use crate::option_check as c; + match (self.id, key) { + ("mirrorCut", "axis") => c::one_of(key, v, &["vertical", "horizontal", "free"]), + ("mirrorCut", "keep") => c::one_of(key, v, &["left", "right", "top", "bottom"]), + _ => Err(c::unknown(key)), + } + } } #[cfg(test)] diff --git a/crates/tools/src/dimension.rs b/crates/tools/src/dimension.rs index d78850e78e..3e50415434 100644 --- a/crates/tools/src/dimension.rs +++ b/crates/tools/src/dimension.rs @@ -579,6 +579,13 @@ impl Tool for DimensionTool { self.style = o; } } + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + match key { + "mode" => crate::option_check::one_of(key, value, &["linear", "angular", "radial", "radius", "diameter"]), + "style" => DimensionOptions::from_params(value.clone()).map(|_| ()), + _ => Err(crate::option_check::unknown(key)), + } + } fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { self.at = ev.pos; self.shift = ev.mods.shift; diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index 6586cb8586..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)))) }) @@ -1348,7 +1360,7 @@ impl DirectSelectionTool { if hit.as_ref().and_then(|h| cx.doc.node(h.leaf)).is_some_and(|n| matches!(n.kind, NodeKind::Text(_))) { return vec![Action::SwitchTool("type".into())]; } - // Outside the isolated art it leaves isolation mode, as with the Selection tool (#4466). + // Outside the isolated art it runs Exit Isolation Mode, as with the Selection tool (#4466). if hit.is_none() && cx.isolation.is_some() { return vec![Action::Exec("object.exitIsolation".into(), json!({}))]; } @@ -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/distort.rs b/crates/tools/src/distort.rs index 30cb1cd4c5..b4cd0a957c 100644 --- a/crates/tools/src/distort.rs +++ b/crates/tools/src/distort.rs @@ -27,7 +27,7 @@ use crate::Tool; pub use liquify::LiquifyTool; pub use perspective::{PerspectiveGridTool, PerspectiveSelectionTool}; pub use puppet::{PinSet, PuppetWarpTool, mesh_for, mesh_input, rest_and_pins, warp_from_rest}; -pub use width::{WidthTool, stroke_owner}; +pub use width::{KEEPS_SIZE, WidthTool, stroke_owner}; /// Create a distortion tool by id (None = not one of ours). pub fn create(id: &str) -> Option> { diff --git a/crates/tools/src/distort/liquify.rs b/crates/tools/src/distort/liquify.rs index 0dc599444f..f93bf3e699 100644 --- a/crates/tools/src/distort/liquify.rs +++ b/crates/tools/src/distort/liquify.rs @@ -829,6 +829,25 @@ impl Tool for LiquifyTool { } } } + /// The options of [`LiquifyParams::from_json`] within its ranges, `diameter` for both sizes, + /// `showBrush`, and `tool` naming this tool. A percentage is a fraction up to 1 and a percent + /// above it. + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + use crate::option_check as c; + match key { + "tool" if value.as_str() == Some(self.params.kind.id()) => Ok(()), + "tool" => Err(format!("`tool` must be `{}`", self.params.kind.id())), + "diameter" | "width" | "height" => c::number(key, value, 0.5, 10_000.0), + "angle" => c::finite(key, value), + "intensity" | "horizontal" | "vertical" => c::number(key, value, 0.0, 100.0), + "detail" => c::number(key, value, 1.0, 10.0), + "simplify" => c::number(key, value, 0.0, 100.0), + "rate" => c::number(key, value, -180.0, 180.0), + "complexity" => c::number(key, value, 0.0, 15.0), + "showBrush" | "usePressure" | "simplifyOn" | "affectAnchors" | "affectIn" | "affectOut" => c::boolean(key, value), + _ => Err(c::unknown(key)), + } + } /// The tool claims Escape during an Alt-drag that sizes the brush. fn claims_key(&self, _cx: &ToolContext, key: ToolKey) -> bool { key == ToolKey::Escape && self.sizing.is_some() diff --git a/crates/tools/src/distort/puppet.rs b/crates/tools/src/distort/puppet.rs index 2ca6ec0631..5aae36826e 100644 --- a/crates/tools/src/distort/puppet.rs +++ b/crates/tools/src/distort/puppet.rs @@ -515,6 +515,15 @@ impl Tool for PuppetWarpTool { _ => {} } } + /// `showMesh`, `selectAllPins` and `expand`; `pins` and `selected` are read only. + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + use crate::option_check as c; + match key { + "showMesh" | "selectAllPins" => c::boolean(key, value), + "expand" => c::number(key, value, 0.0, 1000.0), + _ => Err(c::unknown(key)), + } + } fn busy(&self) -> bool { self.drag.is_some() } diff --git a/crates/tools/src/distort/width.rs b/crates/tools/src/distort/width.rs index 4ebbac4981..005b8e9473 100644 --- a/crates/tools/src/distort/width.rs +++ b/crates/tools/src/distort/width.rs @@ -19,8 +19,18 @@ //! A compound path's stroke is the compound's: its members are edited through it, and the width //! points show on every subpath of the stroke (one profile runs along each). The cursor says what a //! drag does: add a width point on a stroke, or move or widen the one under it. +//! +//! A stroke drawn with a brush is left alone, as a width profile does not change it: a press or a +//! double-click on it sends no command and shows why in the status bar ([`KEEPS_SIZE`]). Without +//! Shift, the press or double-click deselects the width points, and the cursor over it offers no +//! edit. Its width points selected before it took the brush show no handles, and Delete, +//! Backspace and Escape do what they do with no width points selected. + +use std::cell::Cell; +use std::sync::Arc; use serde_json::json; +use vectorcraft_brush::Brush; use vectorcraft_doc::{Document, NodeId, NodeKind, StrokeLayer}; use vectorcraft_geom::{Point, Vec2}; @@ -107,8 +117,14 @@ pub struct WidthTool { selected: Option<(NodeId, Vec)>, /// The selected width points when the button went down: a dropped press puts them back. before_press: Option<(NodeId, Vec)>, + /// The document's brush library as it was at a revision, so pointer moves and overlays do not + /// parse it again ([`Self::keeps_size`]). + brushes: Cell>, } +/// A document revision and its brush library ([`WidthTool::keeps_size`]). +type BrushesAt = ((u64, u64), Arc>); + /// The object whose stroke path `id` draws with: its compound path, if it is a member of one. pub fn stroke_owner(doc: &Document, id: NodeId) -> NodeId { doc.parent_of(id).filter(|p| doc.node(*p).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }))).unwrap_or(id) @@ -132,6 +148,9 @@ fn paths_of(doc: &Document, owner: NodeId) -> Vec { out } +/// The status message for a press on a stroke the tool leaves alone ([`WidthTool::keeps_size`]). +pub const KEEPS_SIZE: &str = "The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile."; + /// Side widths (points) of a stroke at fraction `t`. pub fn sides_at(st: &StrokeLayer, t: f64) -> (f64, f64) { let (l, r) = st.profile.as_ref().map(|p| p.at(t)).unwrap_or((1.0, 1.0)); @@ -139,8 +158,46 @@ pub fn sides_at(st: &StrokeLayer, t: f64) -> (f64, f64) { } impl WidthTool { - /// The stroked path nearest to `p` within reach (stroke half-width + a few pixels). - fn spot_at(cx: &ToolContext, p: Point) -> Option { + /// Does `owner`'s stroke draw with a brush ([`vectorcraft_brush::keeps_brush_size`])? A width + /// profile does not change it, so the tool adds and edits no width points on it. The library is + /// parsed once per document revision. + fn keeps_size(&self, cx: &ToolContext, owner: NodeId) -> bool { + let Some(st) = stroke_of(cx.doc, owner).filter(|s| s.brush.is_some()) else { return false }; + let lib = self + .brushes + .take() + .filter(|(rev, _)| *rev == cx.revision) + .map(|(_, lib)| lib) + .unwrap_or_else(|| Arc::new(vectorcraft_brush::library(cx.doc))); + let keeps = vectorcraft_brush::keeps_brush_size(&lib, st); + self.brushes.set(Some((cx.revision, lib))); + keeps + } + + /// Where a press at `p` lands: the nearest stroke the tool edits ([`Self::spot_at`] without + /// brushed strokes), so a plain stroke under a selected brushed one stays reachable. `Err(true)` + /// when only brushed strokes are within reach, `Err(false)` when no stroke is. + fn edit_spot_at(&self, cx: &ToolContext, p: Point) -> Result { + // `spot_at` asks `skip` only about strokes within reach, so one search tells both apart. + let passed_over = Cell::new(false); + let skip = |owner| { + let keeps = self.keeps_size(cx, owner); + passed_over.set(passed_over.get() || keeps); + keeps + }; + Self::spot_at(cx, p, &skip).ok_or_else(|| passed_over.get()) + } + + /// The hovered stroke while the tool still edits it: a brush applied since the last pointer + /// move takes away its handles and its edit cursor. + fn live_hover(&self, cx: &ToolContext) -> Option { + self.hover.filter(|s| !self.keeps_size(cx, s.owner)) + } + + /// The stroked path nearest to `p` within reach (stroke half-width + a few pixels), passing over + /// the strokes whose owner `skip` returns true for. `skip` is asked only about strokes within + /// reach. + fn spot_at(cx: &ToolContext, p: Point, skip: &dyn Fn(NodeId) -> bool) -> Option { let editable = cx.doc.editable(); let consider = |id: NodeId| -> Option<(f64, Spot)> { if !editable(id) { @@ -156,7 +213,7 @@ impl WidthTool { return None; } let (sub, t, q, tan, d) = nearest_fraction(path, p)?; - if d > reach { + if d > reach || skip(owner) { return None; } let (left, right) = sides_at(st, t); @@ -297,12 +354,22 @@ impl Tool for WidthTool { let p = ev.pos; match ev.kind { PointerKind::Move => { - self.hover = Self::spot_at(cx, p); + // A brushed stroke takes no width points, so the cursor offers no edit over it. + self.hover = self.edit_spot_at(cx, p).ok(); vec![] } PointerKind::TripleClick => vec![], PointerKind::DoubleClick => { - let Some(spot) = Self::spot_at(cx, p) else { return vec![] }; + let spot = match self.edit_spot_at(cx, p) { + Ok(spot) => spot, + Err(false) => return vec![], + Err(true) => { + if !ev.mods.shift { + self.selected = None; + } + return vec![Action::Status(KEEPS_SIZE.into())]; + } + }; let Some((w, _)) = Self::hit(cx, &spot, p) else { self.selected = Some((spot.owner, vec![spot.t])); return vec![Action::Dialog("widthPoint".into(), json!({"id": spot.owner.0, "t": spot.t}))]; @@ -312,11 +379,14 @@ impl Tool for WidthTool { } PointerKind::Down => { self.before_press = self.selected.clone(); - let Some(spot) = Self::spot_at(cx, p) else { - if !ev.mods.shift { - self.selected = None; + let spot = match self.edit_spot_at(cx, p) { + Ok(spot) => spot, + Err(brushed) => { + if !ev.mods.shift { + self.selected = None; + } + return if brushed { vec![Action::Status(KEEPS_SIZE.into())] } else { vec![] }; } - return vec![]; }; let drag = match Self::hit(cx, &spot, p) { Some((w, part)) => { @@ -399,11 +469,12 @@ impl Tool for WidthTool { } /// Delete/Backspace remove the selected width points and Escape deselects them; with none /// selected the keys do what they do with other tools (Clear deletes the selected objects, and - /// Escape leaves isolation mode, for one). + /// Escape leaves isolation mode, for one). Width points of a brushed stroke, which show no + /// handles, count as none selected. fn claims_key(&self, cx: &ToolContext, key: ToolKey) -> bool { matches!(key, ToolKey::Delete | ToolKey::Backspace | ToolKey::Escape) && self.drag.is_none() - && self.selected.as_ref().is_some_and(|(id, _)| !self.selected_indices(cx, *id).is_empty()) + && self.selected.as_ref().is_some_and(|(id, _)| !self.selected_indices(cx, *id).is_empty() && !self.keeps_size(cx, *id)) } /// A dropped press ends the drag, and the width points selected when the button went down are /// selected again. @@ -426,12 +497,16 @@ impl Tool for WidthTool { return vec![]; } self.selected = None; + if self.keeps_size(cx, id) { + return vec![]; + } vec![Action::Exec("stroke.widthPoint.remove".into(), json!({"id": id.0, "indices": indices}))] } fn overlays(&self, cx: &ToolContext) -> Vec { let mut out = vec![]; let r = cx.tol(4.0); - let focus = self.drag.as_ref().map(|d| d.spot).or(self.hover); + let hover = self.live_hover(cx); + let focus = self.drag.as_ref().map(|d| d.spot).or(hover); // Every subpath's width points of the stroke under the pointer, and of the selected ones'. let show = |owner: NodeId, out: &mut Vec| { for w in Self::all_points(cx, owner) { @@ -445,8 +520,11 @@ impl Tool for WidthTool { if let Some(s) = focus { show(s.owner, &mut out); } + // Width points selected before their stroke took a brush show no handles: the tool no + // longer edits them. if let Some((owner, _)) = &self.selected && focus.is_none_or(|s| s.owner != *owner) + && !self.keeps_size(cx, *owner) { show(*owner, &mut out); } @@ -457,7 +535,7 @@ impl Tool for WidthTool { if cx.measurement_labels { out.push(Overlay::Measure { p: q + d.spot.n * (d.left + r * 3.0), text: format!("W: {}", cx.stroke_unit.readout(d.left + d.right)) }); } - } else if let Some(h) = &self.hover { + } else if let Some(h) = &hover { out.push(Overlay::Line { a: h.p + h.n * h.left, b: h.p - h.n * h.right, color: BLUE, dashed: true }); out.push(Overlay::Path { path: diamond(h.p, r), color: BLUE, width: 1.0, dashed: false }); } @@ -468,7 +546,7 @@ impl Tool for WidthTool { return Cursor::WidthPoint; } // The stroke under the pointer, as the last move found it (no search every frame). - match self.hover { + match self.live_hover(cx) { Some(spot) if Self::hit(cx, &spot, p).is_some() => Cursor::WidthPoint, Some(_) => Cursor::WidthAdd, None => Cursor::Width, @@ -538,6 +616,169 @@ mod tests { assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, 150.0, 220.0)), vec![Action::Commit]); } + /// A stroke drawn with a brush of the library (the 3 pt. Round calligraphic brush) is left + /// alone: a press or a double-click sends no command and says why. A brush name the library + /// lacks draws a plain stroke, which the tool edits as usual. + #[test] + fn brushed_stroke_is_left_alone_with_a_reason() { + let (mut d, id) = doc_line(); + d.node_mut(id).unwrap().appearance.stroke_mut().unwrap().brush = Some("3 pt. Round".into()); + let (s, p) = (Selection::default(), paint()); + let mut t = WidthTool::default(); + let c = cx(&d, &s, &p); + let refused = vec![Action::Status(KEEPS_SIZE.into())]; + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 150.0, 201.0)), refused); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 150.0, 220.0)), vec![], "no drag began"); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, 150.0, 220.0)), vec![]); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::DoubleClick, 150.0, 201.0)), refused); + + d.node_mut(id).unwrap().appearance.stroke_mut().unwrap().brush = Some("No Such Brush".into()); + let c = cx(&d, &s, &p); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 150.0, 201.0)), vec![Action::Begin("Width Point".into())]); + } + + /// A selected brushed stroke lying on a plain one does not hide the plain one: a press there + /// edits the plain stroke. + #[test] + fn a_plain_stroke_under_a_selected_brushed_one_stays_reachable() { + let (mut d, _) = doc_line(); + let l = d.layers[0].id; + let brushed = d.alloc_id(); + let mut ap = Appearance::default_art(); + let st = ap.stroke_mut().unwrap(); + st.width = 10.0; + st.brush = Some("3 pt. Round".into()); + let path = PathData::single(SubPath::polyline(&[Point::new(100.0, 200.0), Point::new(300.0, 200.0)], false)); + d.insert(Some(l), 0, Node::path(brushed, path, ap)).unwrap(); + let (s, p) = (Selection { objects: vec![brushed], ..Default::default() }, paint()); + let mut t = WidthTool::default(); + let c = cx(&d, &s, &p); + t.pointer(&c, &PointerEvent::new(PointerKind::Move, 150.0, 201.0)); + assert_eq!(t.cursor(&c, Point::new(150.0, 201.0), Mods::default()), Cursor::WidthAdd); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 150.0, 201.0)), vec![Action::Begin("Width Point".into())]); + } + + /// A brush applied to the hovered stroke, with the pointer still, takes away its handles and its + /// edit cursor before the next pointer move. + #[test] + fn a_brush_applied_under_a_still_pointer_takes_away_the_hover() { + let (mut d, id) = doc_line(); + let (s, p) = (Selection::default(), paint()); + let mut t = WidthTool::default(); + let c = cx(&d, &s, &p); + t.pointer(&c, &PointerEvent::new(PointerKind::Move, 150.0, 201.0)); + assert_eq!(t.cursor(&c, Point::new(150.0, 201.0), Mods::default()), Cursor::WidthAdd); + assert!(!t.overlays(&c).is_empty()); + d.node_mut(id).unwrap().appearance.stroke_mut().unwrap().brush = Some("3 pt. Round".into()); + let c = ToolContext { revision: (0, 1), ..cx(&d, &s, &p) }; + assert_eq!(t.cursor(&c, Point::new(150.0, 201.0), Mods::default()), Cursor::Width); + assert!(t.overlays(&c).is_empty()); + } + + /// The brush library is read once per document revision: a brush added to the library under a + /// new revision is seen, so a stroke naming it is then left alone. + #[test] + fn a_brush_added_to_the_library_is_seen_at_the_next_revision() { + let (mut d, id) = doc_line(); + d.node_mut(id).unwrap().appearance.stroke_mut().unwrap().brush = Some("Added Later".into()); + let (s, p) = (Selection::default(), paint()); + let mut t = WidthTool::default(); + let c = cx(&d, &s, &p); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 150.0, 201.0)), vec![Action::Begin("Width Point".into())]); + t.pointer(&c, &PointerEvent::new(PointerKind::Up, 150.0, 201.0)); + let mut lib = vectorcraft_brush::library(&d); + let mut added = lib[0].clone(); + added.name = "Added Later".into(); + lib.push(added); + vectorcraft_brush::store(&mut d, &lib); + let c = ToolContext { revision: (0, 1), ..cx(&d, &s, &p) }; + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 150.0, 201.0)), vec![Action::Status(KEEPS_SIZE.into())]); + } + + /// Width points selected before the stroke took a brush show no handles and count as none + /// selected: the tool leaves Delete and Escape to the app, and removes none. + #[test] + fn delete_leaves_the_width_points_of_a_brushed_stroke() { + let (mut d, id) = doc_line(); + d.node_mut(id).unwrap().appearance.stroke_mut().unwrap().profile = + Some(WidthProfile { points: vec![(0.0, 1.0, 1.0), (0.5, 2.0, 2.0), (1.0, 1.0, 1.0)] }); + let (s, p) = (Selection::default(), paint()); + let mut t = WidthTool::default(); + let c = cx(&d, &s, &p); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, 200.0, 200.0)); + t.pointer(&c, &PointerEvent::new(PointerKind::Up, 200.0, 200.0)); + assert!(t.claims_key(&c, ToolKey::Delete), "a width point is selected"); + assert!(!t.overlays(&c).is_empty(), "the selected point shows its handles"); + d.node_mut(id).unwrap().appearance.stroke_mut().unwrap().brush = Some("3 pt. Round".into()); + let c = ToolContext { revision: (0, 1), ..cx(&d, &s, &p) }; + assert!(t.overlays(&c).is_empty(), "no handles show on a stroke the tool no longer edits"); + for key in [ToolKey::Delete, ToolKey::Backspace, ToolKey::Escape] { + assert!(!t.claims_key(&c, key), "{key:?} is the app's"); + } + assert_eq!(t.key(&c, ToolKey::Delete, Mods::default()), vec![]); + assert!(t.selected.is_none()); + } + + /// With Shift held, a press or a double-click on a brushed stroke keeps the width points of + /// another stroke selected, as a Shift-press that misses every stroke does. + #[test] + fn shift_on_a_brushed_stroke_keeps_the_selected_width_points() { + let (mut d, _) = doc_three_points(); + let l = d.layers[0].id; + let other = d.alloc_id(); + let mut ap = Appearance::default_art(); + let st = ap.stroke_mut().unwrap(); + st.width = 10.0; + st.brush = Some("3 pt. Round".into()); + let path = PathData::single(SubPath::polyline(&[Point::new(100.0, 400.0), Point::new(300.0, 400.0)], false)); + d.insert(Some(l), 0, Node::path(other, path, ap)).unwrap(); + let (s, p) = (Selection::default(), paint()); + let shift = Mods { shift: true, ..Default::default() }; + let mut t = WidthTool::default(); + let c = cx(&d, &s, &p); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, 200.0, 200.0)); + t.pointer(&c, &PointerEvent::new(PointerKind::Up, 200.0, 200.0)); + let kept = t.selected.clone(); + assert!(kept.is_some(), "the plain stroke's width point is selected"); + for kind in [PointerKind::Down, PointerKind::DoubleClick] { + assert_eq!(t.pointer(&c, &ev(kind, 200.0, 401.0, shift)), vec![Action::Status(KEEPS_SIZE.into())]); + assert_eq!(t.selected, kept, "{kind:?} with Shift keeps the selection"); + } + assert_eq!(t.pointer(&c, &ev(PointerKind::DoubleClick, 200.0, 401.0, Mods::default())), vec![Action::Status(KEEPS_SIZE.into())]); + assert!(t.selected.is_none(), "a double-click without Shift deselects"); + } + + /// A press on a brushed stroke deselects the width points of another stroke, as a press that + /// misses every stroke does, so a later Delete does not edit that other stroke. The cursor over + /// a brushed stroke offers no edit. + #[test] + fn a_press_on_a_brushed_stroke_deselects_and_its_cursor_offers_no_edit() { + let (mut d, _) = doc_three_points(); + let l = d.layers[0].id; + let other = d.alloc_id(); + let mut ap = Appearance::default_art(); + let st = ap.stroke_mut().unwrap(); + st.width = 10.0; + st.brush = Some("3 pt. Round".into()); + let path = PathData::single(SubPath::polyline(&[Point::new(100.0, 400.0), Point::new(300.0, 400.0)], false)); + d.insert(Some(l), 0, Node::path(other, path, ap)).unwrap(); + let (s, p) = (Selection::default(), paint()); + let mut t = WidthTool::default(); + let c = cx(&d, &s, &p); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, 200.0, 200.0)); + t.pointer(&c, &PointerEvent::new(PointerKind::Up, 200.0, 200.0)); + assert!(t.claims_key(&c, ToolKey::Delete), "the plain stroke's width point is selected"); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 200.0, 401.0)), vec![Action::Status(KEEPS_SIZE.into())]); + t.pointer(&c, &PointerEvent::new(PointerKind::Up, 200.0, 401.0)); + assert!(!t.claims_key(&c, ToolKey::Delete), "nothing is left to delete"); + assert_eq!(t.key(&c, ToolKey::Delete, Mods::default()), vec![]); + + t.pointer(&c, &PointerEvent::new(PointerKind::Move, 200.0, 401.0)); + assert_eq!(t.cursor(&c, Point::new(200.0, 401.0), Mods::default()), Cursor::Width); + t.pointer(&c, &PointerEvent::new(PointerKind::Move, 220.0, 201.0)); + assert_eq!(t.cursor(&c, Point::new(220.0, 201.0), Mods::default()), Cursor::WidthAdd, "the plain stroke still offers one"); + } + #[test] fn alt_drag_changes_one_side_and_move_slides() { let (mut d, id) = doc_line(); 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/draw2/family.rs b/crates/tools/src/draw2/family.rs index 8bdbb4db0f..87c11abba9 100644 --- a/crates/tools/src/draw2/family.rs +++ b/crates/tools/src/draw2/family.rs @@ -529,11 +529,32 @@ impl Tool for FamilyTool { } } } + /// The options the tool shows ([`Self::options`]): those of the arc, the spiral or the grid. + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + use crate::option_check as c; + if self.options().get(key).is_none() { + return Err(c::unknown(key)); + } + let skew = vectorcraft_geom::shapes::GRID_SKEW_MAX; + match key { + "lengthX" | "lengthY" => c::number(key, v, 1e-9, 1e6), + "width" | "height" => c::positive(key, v, 1e6), + "reference" => c::whole(key, v, 0, 8), + "baseAlong" => c::one_of(key, v, &["x", "y", "X", "Y"]), + "slope" => c::number(key, v, -100.0, 100.0), + "decay" => c::number(key, v, 5.0, 99.99), + "segments" => c::whole(key, v, 2, 1000), + "rows" | "concentric" | "columns" | "radial" => c::whole(key, v, 0, 999), + "rowSkew" | "concentricSkew" | "columnSkew" | "radialSkew" => c::number(key, v, -skew, skew), + _ => c::boolean(key, v), + } + } } -/// Arc segment length from a dialog or preference value. +/// Arc segment length from a dialog or preference value, from 1e-9 to 1e6 pt (as the option check +/// takes it). fn arc_length(v: &Value, current: f64) -> f64 { - v.as_f64().filter(|n| n.is_finite()).map_or(current, |n| n.abs().max(1e-9)) + v.as_f64().filter(|n| n.is_finite()).map_or(current, |n| n.abs().clamp(1e-9, 1e6)) } /// A grid's Default Size side from option value `v`: a finite positive length (at most 1e6 pt), @@ -578,6 +599,28 @@ mod tests { } } + /// A number `tool.setOption` takes is kept as given, and a number the tool would keep as + /// another value is refused: `decay` past 99.99 is an error. + #[test] + fn family_tools_keep_the_numbers_their_option_check_takes() { + let tries = [-1e9, -150.0, -100.0, -1.0, 0.0, 1e-12, 0.5, 1.0, 2.0, 5.0, 8.0, 99.99, 100.0, 120.0, 150.0, 999.0, 1000.0, 1e6, 1e9]; + for id in ["arc", "spiral", "rectangularGrid", "polarGrid"] { + let defaults = FamilyTool::new(id).options(); + for (k, _) in defaults.as_object().into_iter().flatten().filter(|(_, v)| v.is_number()) { + for n in tries { + let mut t = FamilyTool::new(id); + if t.check_option(k, &json!(n)).is_ok() { + t.set_option(k, &json!(n)); + assert_eq!(t.options()[k].as_f64(), Some(n), "{id} `{k}` = {n}"); + } + } + } + } + let t = FamilyTool::new("spiral"); + assert_eq!(t.check_option("decay", &json!(120.0)).err(), Some("`decay` must be a number from 5 to 99.99".into())); + assert!(t.check_option("decay", &json!(99.99)).is_ok()); + } + #[test] fn normalized_spiral_decay_preserves_existing_capped_paths_within_roundoff() { for requested in [100.0, 150.0] { @@ -1067,6 +1110,10 @@ mod tests { "fillArc": true, }) ); + // A length past 1e6 pt is kept at 1e6, which `tool.setOption` takes back. + t.set_option("lengthX", &json!(-1e9)); + assert_eq!(t.options()["lengthX"], json!(1e6)); + assert_eq!(t.check_option("lengthX", &t.options()["lengthX"]), Ok(())); } /// While an arc is dragged out, C switches it between open and closed, F switches its base diff --git a/crates/tools/src/draw2/gesture.rs b/crates/tools/src/draw2/gesture.rs index 502fd16dbd..75f0fde6d6 100644 --- a/crates/tools/src/draw2/gesture.rs +++ b/crates/tools/src/draw2/gesture.rs @@ -2059,6 +2059,32 @@ impl Tool for GestureTool { _ => {} } } + /// The options the tool shows ([`Self::options`]), and the Smooth tool's Fidelity that the + /// Pencil, Paintbrush and Blob Brush smooth with while Alt is held (`smoothFidelity`). + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + use crate::option_check as c; + let smooth_store = key == "smoothFidelity" && matches!(self.id, "pencil" | "paintbrush" | "blobBrush"); + if !smooth_store && self.options().get(key).is_none() { + return Err(c::unknown(key)); + } + match key { + "fidelity" => c::number(key, v, super::min_fidelity(self.id), 100.0), + "smoothFidelity" => c::number(key, v, super::min_fidelity("smooth"), 100.0), + "size" => c::number(key, v, 0.1, 1000.0), + "sizeVariation" => c::number(key, v, 0.0, 1000.0), + "angle" => c::number(key, v, -180.0, 180.0), + "roundness" => c::number(key, v, if self.id == "blobBrush" { 0.0 } else { 1.0 }, 100.0), + "editWithin" | "closeWithin" => c::number(key, v, 0.0, 100.0), + "angleVariation" => c::number(key, v, 0.0, 180.0), + "roundnessVariation" => c::number(key, v, 0.0, 100.0), + // The Blob Brush's Size is Fixed or Pressure; the Eraser's Angle, Roundness and Size + // take any mode (`set_option`). + "sizeMode" if self.id != "eraser" => c::one_of(key, v, &[Variation::Fixed.id(), Variation::Pressure.id()]), + "sizeMode" | "angleMode" | "roundnessMode" => c::one_of(key, v, &Variation::ALL.map(Variation::id)), + "fill" | "altSmooth" | "livePreview" | "liveFit" | "keepSelected" | "mergeOnlySelection" => c::boolean(key, v), + _ => Err(c::unknown(key)), + } + } } #[cfg(test)] diff --git a/crates/tools/src/draw2/gesture/tests.rs b/crates/tools/src/draw2/gesture/tests.rs index 550e7f9d32..3ebc50cd02 100644 --- a/crates/tools/src/draw2/gesture/tests.rs +++ b/crates/tools/src/draw2/gesture/tests.rs @@ -3087,6 +3087,20 @@ fn the_eraser_tip_follows_its_variation_modes() { [&o["angleMode"], &o["angleVariation"], &o["roundnessMode"], &o["roundnessVariation"], &o["sizeMode"], &o["sizeVariation"]], [&json!("rotation"), &json!(90.0), &json!("random"), &json!(10.0), &json!("tilt"), &json!(8.0)] ); + // `tool.setOption` takes back what the tool reports, and refuses a mode or Variation it does + // not take. + let reported = o.as_object().unwrap().clone(); + assert_eq!(t.check_options(&reported), Ok(())); + for mode in Variation::ALL { + for k in ["sizeMode", "angleMode", "roundnessMode"] { + assert_eq!(t.check_option(k, &json!(mode.id())), Ok(()), "{k} {mode:?}"); + } + } + let modes = "must be one of `fixed`, `random`, `pressure`, `tilt`, `bearing`, `rotation`"; + assert_eq!(t.check_option("angleMode", &json!("wheel")), Err(format!("`angleMode` {modes}"))); + assert_eq!(t.check_option("angleVariation", &json!(181)), Err("`angleVariation` must be a number from 0 to 180".into())); + assert_eq!(t.check_option("roundnessVariation", &json!(500)), Err("`roundnessVariation` must be a number from 0 to 100".into())); + assert_eq!(GestureTool::new("blobBrush").check_option("sizeMode", &json!("tilt")), Err("`sizeMode` must be one of `fixed`, `pressure`".into())); // A mode it does not have leaves the mode as it was; a Variation is kept within its range. t.set_option("angleMode", &json!("wheel")); t.set_option("roundnessVariation", &json!(500)); diff --git a/crates/tools/src/extra.rs b/crates/tools/src/extra.rs index 4c6a6c6d45..5eed055eaa 100644 --- a/crates/tools/src/extra.rs +++ b/crates/tools/src/extra.rs @@ -400,6 +400,18 @@ impl Tool for FlareTool { } } } + /// The switches and [`FLARE_OPTIONS`] within their ranges, the counts whole. + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + use crate::option_check as c; + if matches!(key, "raysOn" | "ringsOn") { + return c::boolean(key, v); + } + let Some(&(_, _, lo, hi)) = FLARE_OPTIONS.iter().find(|(k, ..)| *k == key) else { return Err(c::unknown(key)) }; + if is_count(key) && v.as_f64().is_none_or(|n| n.fract() != 0.0) { + return Err(format!("`{key}` must be a whole number from {lo} to {hi}")); + } + c::number(key, v, lo, hi) + } } /// Where a Reshape press landed on a selected path. diff --git a/crates/tools/src/intertwine.rs b/crates/tools/src/intertwine.rs index 7ea841b4a7..35a0f1747d 100644 --- a/crates/tools/src/intertwine.rs +++ b/crates/tools/src/intertwine.rs @@ -364,6 +364,10 @@ impl Tool for IntertwineTool { } } + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + if key == "prev" { crate::option_check::string_or_null(key, value) } else { Err(crate::option_check::unknown(key)) } + } + fn busy(&self) -> bool { self.dragging } diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index b5d7574b1f..43e59de7da 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -12,6 +12,7 @@ pub mod bbox; pub mod blendwidget; pub mod builder; pub mod catalog; +pub mod circle; pub mod corners; pub mod cropimage; pub mod cut; @@ -27,6 +28,7 @@ pub mod meshedit; pub mod mirror; pub mod nineslice; pub mod objects_on_path; +pub mod option_check; pub mod params; pub mod pathtype; pub mod pen; @@ -160,6 +162,18 @@ pub trait Tool: Send { Value::Null } fn set_option(&mut self, _key: &str, _value: &Value) {} + /// Whether [`Self::set_option`] takes `value` for option `key` as it is: an error names an + /// option the tool doesn't have, a value of the wrong type or a number out of range + /// (`tool.setOption` checks every option it is given with this before it sets any). A tool + /// without options takes none. + fn check_option(&self, key: &str, _value: &Value) -> Result<(), String> { + Err(option_check::unknown(key)) + } + /// Whether [`Self::set_option`] takes all of `values`, set together in one call: by default + /// each one checked on its own with [`Self::check_option`]. + fn check_options(&self, values: &serde_json::Map) -> Result<(), String> { + values.iter().try_for_each(|(k, v)| self.check_option(k, v)) + } /// Is an interaction in progress (drag, open pen path)? fn busy(&self) -> bool { false @@ -272,8 +286,8 @@ pub trait Tool: Send { false } /// What the Info panel shows for the tool as it is now: the drag in progress (a move of the - /// selection, a gradient vector, a Scale, Rotate, Reflect or Shear tool drag), or the - /// Paintbrush's brush. None for a tool with nothing of its own to show. + /// selection, a gradient vector, a handle the Pen pulls out, a Scale, Rotate, Reflect or Shear + /// tool drag), or the Paintbrush's brush. None for a tool with nothing of its own to show. fn readout(&self, _cx: &ToolContext) -> Option { None } @@ -365,6 +379,7 @@ pub fn create(id: &str) -> Box { "dimension" => Box::new(dimension::DimensionTool::default()), "type" | "areaType" | "typeOnPath" | "verticalType" | "verticalAreaType" | "verticalTypeOnPath" => Box::new(text::TypeTool::new(id)), "rectangle" | "roundedRectangle" | "ellipse" | "polygon" | "star" | "lineSegment" => Box::new(shape::ShapeTool::new(id)), + circle::ID => Box::new(circle::CircleTool::default()), // Not in the toolbar: `file.place.queue` loads it. "place" => Box::new(place::PlaceTool::default()), other => symbolism::create(other) diff --git a/crates/tools/src/objects_on_path.rs b/crates/tools/src/objects_on_path.rs index fe956691e1..dbb6f8bfdf 100644 --- a/crates/tools/src/objects_on_path.rs +++ b/crates/tools/src/objects_on_path.rs @@ -1106,6 +1106,15 @@ impl Tool for ObjectsOnPathTool { } } + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + use crate::option_check as c; + match key { + "pivot" => c::whole(key, value, 0, 8), + "rotate" => c::number(key, value, -360.0, 360.0), + _ => Err(c::unknown(key)), + } + } + fn busy(&self) -> bool { self.press.is_some() || self.rotating.is_some() || self.spacing.is_some() || self.moving.is_some() || self.member.is_some() } diff --git a/crates/tools/src/option_check.rs b/crates/tools/src/option_check.rs new file mode 100644 index 0000000000..dd26fa28f0 --- /dev/null +++ b/crates/tools/src/option_check.rs @@ -0,0 +1,245 @@ +//! Checks of tool option values ([`crate::Tool::check_option`]) and of `tool.setOption`'s +//! parameters. Each error names the option and what it takes. + +use serde_json::{Map, Value}; + +use crate::Tool; + +/// The error for an option the tool doesn't have. +pub fn unknown(key: &str) -> String { + format!("unknown option `{key}`") +} + +/// `v` is a finite number from `lo` to `hi`. +pub fn number(key: &str, v: &Value, lo: f64, hi: f64) -> Result<(), String> { + match v.as_f64() { + Some(n) if n.is_finite() && (lo..=hi).contains(&n) => Ok(()), + _ => Err(format!("`{key}` must be a number from {lo} to {hi}")), + } +} + +/// `v` is a finite number. +pub fn finite(key: &str, v: &Value) -> Result<(), String> { + match v.as_f64() { + Some(n) if n.is_finite() => Ok(()), + _ => Err(format!("`{key}` must be a finite number")), + } +} + +/// `v` is a finite number above 0 and at most `hi`. +pub fn positive(key: &str, v: &Value, hi: f64) -> Result<(), String> { + match v.as_f64() { + Some(n) if n > 0.0 && n <= hi => Ok(()), + _ => Err(format!("`{key}` must be a number above 0 and at most {hi}")), + } +} + +/// `v` is a whole number (written without a fraction) from `lo` to `hi`. +pub fn whole(key: &str, v: &Value, lo: u64, hi: u64) -> Result<(), String> { + match v.as_u64() { + Some(n) if (lo..=hi).contains(&n) => Ok(()), + _ => Err(format!("`{key}` must be a whole number from {lo} to {hi}")), + } +} + +/// `v` is true or false. +pub fn boolean(key: &str, v: &Value) -> Result<(), String> { + if v.is_boolean() { Ok(()) } else { Err(format!("`{key}` must be true or false")) } +} + +/// `v` is one of the strings `choices`. +pub fn one_of(key: &str, v: &Value, choices: &[&str]) -> Result<(), String> { + if v.as_str().is_some_and(|s| choices.contains(&s)) { + Ok(()) + } else { + let list: Vec = choices.iter().map(|c| format!("`{c}`")).collect(); + Err(format!("`{key}` must be one of {}", list.join(", "))) + } +} + +/// `v` is a string, or null. +pub fn string_or_null(key: &str, v: &Value) -> Result<(), String> { + if v.is_string() || v.is_null() { Ok(()) } else { Err(format!("`{key}` must be a string or null")) } +} + +/// What `tool.setOption {tool?, key?, value?, values?}` sets: the tool named (none: the active +/// tool) and the options, `key` and `value` among `values`. A parameter of the wrong type, a +/// `value` without a `key` or a `key` without a `value`, and an option given both as `key` and in +/// `values` are errors, and so are parameters that are not an object. With none of `key` and +/// `values`, or with no parameters (null), the options are empty: the command reads them. +pub fn set_option_params(p: &Value) -> Result<(Option<&str>, Map), String> { + if !p.is_object() && !p.is_null() { + return Err(format!("the params must be an object, not {}", shown(p))); + } + let tool = match p.get("tool") { + None => None, + Some(t) => Some(t.as_str().ok_or("`tool` must be a tool id")?), + }; + let mut values = match p.get("values") { + None => Map::new(), + Some(v) => v.as_object().cloned().ok_or("`values` must be an object")?, + }; + match (p.get("key"), p.get("value")) { + (None, None) => {} + (Some(k), v) => { + let k = k.as_str().ok_or("`key` must be a string")?; + let v = v.ok_or_else(|| format!("`value` is missing for `{k}`"))?; + if values.contains_key(k) { + return Err(format!("`{k}` is given both as `key` and in `values`")); + } + values.insert(k.to_string(), v.clone()); + } + (None, Some(_)) => return Err("`value` needs a `key`".into()), + } + Ok((tool, values)) +} + +/// The JSON text of `v` as a parameter error shows it: cut to 40 characters, with `…` when it was +/// longer. The text is written only up to the cut. +fn shown(v: &Value) -> String { + struct Cut { + text: String, + left: usize, + } + impl std::fmt::Write for Cut { + fn write_str(&mut self, s: &str) -> std::fmt::Result { + for c in s.chars() { + if self.left == 0 { + return Err(std::fmt::Error); + } + self.left -= 1; + self.text.push(c); + } + Ok(()) + } + } + let mut out = Cut { text: String::new(), left: 40 }; + if std::fmt::Write::write_fmt(&mut out, format_args!("{v}")).is_err() { + out.text.push('…'); + } + out.text +} + +/// Check every one of `values` as an option of `tool` ([`Tool::check_options`]), before any is +/// set: the first one the tool doesn't take is an error that names the tool. +pub fn check_values(tool: &dyn Tool, values: &Map) -> Result<(), String> { + tool.check_options(values).map_err(|e| format!("tool `{}`: {e}", tool.id())) +} + +#[cfg(test)] +mod tests { + use serde_json::json; + + use super::*; + + #[test] + fn numbers_are_checked_against_their_range() { + assert!(number("fidelity", &json!(0.05), 0.05, 100.0).is_ok()); + assert!(number("fidelity", &json!(100), 0.05, 100.0).is_ok()); + for bad in [json!(-3), json!(1e9), json!("abc"), json!(true), json!(null), json!(0.04)] { + assert_eq!(number("fidelity", &bad, 0.05, 100.0), Err("`fidelity` must be a number from 0.05 to 100".into()), "{bad}"); + } + assert!(whole("sides", &json!(3), 3, 1000).is_ok()); + for bad in [json!(2), json!(3.5), json!(1001), json!(-1), json!("6")] { + assert!(whole("sides", &bad, 3, 1000).is_err(), "{bad}"); + } + assert!(positive("width", &json!(0), 1e6).is_err()); + assert!(positive("width", &json!(1e6), 1e6).is_ok()); + assert!(finite("angle", &json!(720)).is_ok()); + assert!(finite("angle", &json!("720")).is_err()); + } + + #[test] + fn other_values_are_checked_by_kind() { + assert!(boolean("fill", &json!(false)).is_ok()); + assert_eq!(boolean("fill", &json!(0)), Err("`fill` must be true or false".into())); + assert!(one_of("axis", &json!("free"), &["vertical", "free"]).is_ok()); + assert_eq!(one_of("axis", &json!("diagonal"), &["vertical", "free"]), Err("`axis` must be one of `vertical`, `free`".into())); + assert!(string_or_null("prev", &json!(null)).is_ok()); + assert!(string_or_null("prev", &json!(3)).is_err()); + } + + /// Every tool takes back the options it reports, each on its own and all together: a dialog's + /// OK sends every field the tool showed it. The state a tool reports and doesn't take (the + /// picked mesh points, the text being edited, the pins, the queue of files to place) is left + /// out. + #[test] + fn every_tool_takes_the_options_it_reports() { + const TYPE: &[&str] = &["type", "areaType", "typeOnPath", "verticalType", "verticalAreaType", "verticalTypeOnPath"]; + const READ_ONLY: &[(&[&str], &[&str])] = &[ + (&["directSelection", "groupSelection", "lasso", "polygonalLasso", "mesh", "magicWand"], &["meshPoints"]), + (TYPE, &["editing"]), + (&["puppetWarp"], &["pins", "selected"]), + // With nothing queued, `current` (0) is no file's index either. + (&["place"], &["count", "current", "name", "width", "height", "names"]), + ]; + let read_only = |id: &str, k: &str| READ_ONLY.iter().any(|(ids, keys)| ids.contains(&id) && keys.contains(&k)); + // Tools that `create` makes and the catalog doesn't list. + let extra = ["place", "dimension", crate::cropimage::ID, "intertwine"]; + let mut refused = Vec::new(); + let mut check = |id: &str, tool: &dyn Tool, after: &str| { + let Some(mut options) = tool.options().as_object().cloned() else { return }; + options.retain(|k, _| !read_only(id, k)); + for (k, v) in &options { + if let Err(e) = tool.check_option(k, v) { + refused.push(format!("tool `{id}`{after}, option `{k}` = {v}: {e}")); + } + } + if let Err(e) = check_values(tool, &options) { + refused.push(format!("{e}{after}")); + } + }; + for id in crate::catalog::all_tools().map(|t| t.id).chain(extra) { + let tool = crate::create(id); + check(id, tool.as_ref(), ""); + // A number set past either end, or a true-or-false option flipped, is still taken back + // as the tool then reports it. + let Some(defaults) = tool.options().as_object().cloned() else { continue }; + for (k, v) in defaults.iter().filter(|(k, _)| !read_only(id, k)) { + let tries = match v { + Value::Number(_) => vec![json!(-1e9), json!(1e9)], + Value::Bool(b) => vec![json!(!b)], + _ => continue, + }; + for value in tries { + let mut changed = crate::create(id); + changed.set_option(k, &value); + check(id, changed.as_ref(), &format!(" after setting `{k}` to {value}")); + } + } + } + assert!(refused.is_empty(), "{}", refused.join("\n")); + } + + #[test] + fn set_option_params_reads_the_tool_and_the_options() { + let p = json!({"tool": "smooth", "key": "fidelity", "value": 2, "values": {"x": 1}}); + let (tool, values) = set_option_params(&p).unwrap(); + assert_eq!(tool, Some("smooth")); + assert_eq!(Value::Object(values), json!({"fidelity": 2, "x": 1})); + let empty = json!({}); + let (tool, values) = set_option_params(&empty).unwrap(); + assert!(tool.is_none() && values.is_empty()); + // Omitted parameters arrive as null: a read, like `{}`. + let (tool, values) = set_option_params(&Value::Null).unwrap(); + assert!(tool.is_none() && values.is_empty()); + for (bad, got) in [(json!(true), "true"), (json!(7), "7"), (json!([]), "[]"), (json!("x"), "\"x\"")] { + assert_eq!(set_option_params(&bad).err(), Some(format!("the params must be an object, not {got}")), "{bad}"); + } + // A long value is shown cut, as the other parameter errors show it. + let long = json!("a".repeat(100)); + let shown = format!("\"{}…", "a".repeat(39)); + assert_eq!(set_option_params(&long).err(), Some(format!("the params must be an object, not {shown}"))); + assert_eq!(set_option_params(&json!({"tool": 3})).err(), Some("`tool` must be a tool id".into())); + assert_eq!(set_option_params(&json!({"values": [1]})).err(), Some("`values` must be an object".into())); + assert_eq!(set_option_params(&json!({"key": 3, "value": 1})).err(), Some("`key` must be a string".into())); + assert_eq!(set_option_params(&json!({"key": "fill"})).err(), Some("`value` is missing for `fill`".into())); + assert_eq!(set_option_params(&json!({"value": 1})).err(), Some("`value` needs a `key`".into())); + assert_eq!( + set_option_params(&json!({"key": "fill", "value": true, "values": {"fill": false}})).err(), + Some("`fill` is given both as `key` and in `values`".into()) + ); + // An explicit null is a value: the Type tool's triggers take one. + assert!(set_option_params(&json!({"key": "stopEditing", "value": null})).is_ok()); + } +} diff --git a/crates/tools/src/pen.rs b/crates/tools/src/pen.rs index ada9754c1d..b1077d5a12 100644 --- a/crates/tools/src/pen.rs +++ b/crates/tools/src/pen.rs @@ -29,6 +29,7 @@ //! the other art and of the path being drawn, into line with them, onto the construction guides //! through the last anchor; with Shift held it slides along its 45° step into line. Hovering shows //! where the next one would go. +//! While a drag pulls a handle out, the Info panel shows it from the anchor to the handle's end. use serde_json::json; use vectorcraft_doc::{NodeId, NodeKind}; @@ -62,6 +63,10 @@ pub struct PenTool { /// The pointer has moved past the drag threshold since the press: a press released inside it /// is a click, so the anchor stays a corner without handles. dragged: bool, + /// The handle a drag past the threshold is pulling out, from the anchor it shapes to the + /// handle's end as last previewed (the outgoing handle, or the incoming one of the first + /// anchor closing the path): what the Info panel shows ([`Tool::readout`]). + vector: Option, /// The last anchor of the path being drawn, while a click retracts its outgoing handle or a /// drag pulls a new one out: (path, subpath, anchor, its position). handle: Option<(NodeId, usize, usize, Point)>, @@ -256,6 +261,12 @@ impl Tool for PenTool { fn ends_on_escape(&self, cx: &ToolContext) -> bool { self.active(cx).is_some() } + /// The handle a drag is pulling out of the anchor it shapes: the outgoing handle of a new or + /// added anchor or of the last anchor, or the incoming handle of the first anchor closing the + /// path. None for a click, a hover or an Alt gesture. + fn readout(&self, _cx: &ToolContext) -> Option { + self.vector.filter(|_| self.dragged && (self.drag.is_some() || self.handle.is_some())).map(crate::Readout::drag) + } fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { let tol = cx.tol(5.0).max(cx.point_tol()); // The path a press began is the selected one by the next event. @@ -292,6 +303,7 @@ impl Tool for PenTool { self.last = ev.pos; self.pressed = ev.pos; self.dragged = false; + self.vector = None; if let Some((id, si, first, last, _)) = active { let end = last_anchor(cx, id, Some(si)); let closing_end = end.filter(|(_, ai)| *ai > 0).map(|_| first); @@ -391,6 +403,7 @@ impl Tool for PenTool { if ev.mods.shift { h = a + vectorcraft_geom::constrain_angle_from(ev.pos - a, 45.0, cx.constrain_angle); } + self.vector = Some(h - a); return vec![set_out_handle(id, si, ai, h)]; } let Some(Place { at: mut a, path, subpath, closing, mut moved }) = self.drag else { return vec![] }; @@ -412,6 +425,8 @@ impl Tool for PenTool { if ev.mods.shift { out_h = a + vectorcraft_geom::constrain_angle_from(ev.pos - a, 45.0, cx.constrain_angle); } + // A closing drag shapes the first anchor's incoming handle, which mirrors the pointer. + self.vector = Some(if closing { a - out_h } else { out_h - a }); let alt = ev.mods.alt; let Some(id) = path else { // First anchor of a new path: re-issue create with handles. @@ -436,6 +451,7 @@ impl Tool for PenTool { } PointerKind::Up => { self.snap.clear(); + self.vector = None; if let Some(mut t) = self.convert.take() { return t.pointer(cx, ev); } @@ -471,6 +487,7 @@ impl Tool for PenTool { self.first = None; self.handle = None; self.convert = None; + self.vector = None; self.snap.clear(); vec![] } @@ -482,6 +499,7 @@ impl Tool for PenTool { let placing = self.drag.take().is_some(); self.first = None; let handling = self.handle.take().is_some(); + self.vector = None; // Finish the preview as it stands; clearing state alone leaves its transaction open. let mut acts = self.convert.take().map(|mut t| t.deactivate(cx)).unwrap_or_default(); if placing || handling { @@ -690,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/tools/src/pen/tests.rs b/crates/tools/src/pen/tests.rs index be8468e379..710c39ae7a 100644 --- a/crates/tools/src/pen/tests.rs +++ b/crates/tools/src/pen/tests.rs @@ -1062,3 +1062,128 @@ fn continuing_a_compound_member_at_its_first_anchor_reverses_that_path_by_id() { ); assert_eq!((pen.path, pen.subpath), (Some(a), Some(0))); } + +/// A context with snapping off, so each point goes where the pointer is. +fn plain<'a>(d: &'a vectorcraft_doc::Document, s: &'a Selection, p: &'a crate::PaintDefaults) -> ToolContext<'a> { + ToolContext { zoom: 1.0, smart_guides: false, snap_to_point: false, snap_to_pixel: false, snap_to_grid: false, ..cx(d, s, p) } +} + +fn drag_readout(dx: f64, dy: f64) -> Option { + Some(crate::Readout::Drag { dx, dy }) +} + +/// The Info panel shows the handle a drag pulls out of a new anchor, from the anchor to the +/// handle's end, once the drag passes the threshold and until the button comes up. +#[test] +fn info_readout_tracks_the_handle_of_a_new_anchor() { + let (d, s, p) = (vectorcraft_doc::Document::new(500.0, 500.0), Selection::default(), paint()); + let cx = plain(&d, &s, &p); + let mut t = PenTool::default(); + assert_eq!(t.readout(&cx), None, "hovering"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 100.0)); + assert_eq!(t.readout(&cx), None, "pressed"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 101.0, 101.0)); + assert_eq!(t.readout(&cx), None, "inside the drag threshold"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 130.0, 60.0)); + let r = t.readout(&cx); + assert_eq!(r, drag_readout(30.0, -40.0)); + let (dist, angle) = r.and_then(|r| r.distance_angle()).unwrap_or_default(); + assert!((dist - 50.0).abs() < 1e-9 && (angle - 53.130_102_354_155_98).abs() < 1e-9, "{dist} {angle}"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 130.0, 60.0)); + assert_eq!(t.readout(&cx), None, "released"); + // A click shows nothing. + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 200.0, 200.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 201.0, 200.0)); + assert_eq!(t.readout(&cx), None); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 201.0, 200.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Move, 250.0, 250.0)); + assert_eq!(t.readout(&cx), None, "hovering after a click"); +} + +/// An anchor added to the path being drawn and the first anchor closing it: the handle the drag +/// shapes is measured from the anchor it belongs to. +#[test] +fn info_readout_tracks_added_and_closing_anchors() { + let pts = [Point::new(100.0, 300.0), Point::new(200.0, 300.0), Point::new(200.0, 400.0)]; + let (d, _, s) = drawing(vectorcraft_geom::SubPath::polyline(&pts, false)); + let p = paint(); + let cx = plain(&d, &s, &p); + let mut t = PenTool { drawing: true, ..PenTool::default() }; + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 300.0, 400.0)); + assert!(matches!(&a[..], [Action::Begin(_), Action::Preview(c, _)] if c == "path.appendAnchor"), "{a:?}"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 330.0, 440.0)); + assert_eq!(t.readout(&cx), drag_readout(30.0, 40.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 330.0, 440.0)); + assert_eq!(t.readout(&cx), None); + // A press on the first anchor, a pixel off it, closes: the readout is that anchor's incoming + // handle, which mirrors the pointer. + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 101.0, 301.0)); + assert!(matches!(&a[..], [Action::Begin(c), _] if c == "Close Path"), "{a:?}"); + let acts = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 130.0, 260.0)); + let [Action::Preview(c, v)] = acts.as_slice() else { panic!("not a close preview: {acts:?}") }; + assert_eq!((c.as_str(), &v["in"]), ("path.close", &json!([70.0, 340.0]))); + assert_eq!(t.readout(&cx), drag_readout(-30.0, 40.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 130.0, 260.0)); + assert_eq!(t.readout(&cx), None); +} + +/// A drag from the last anchor pulls its outgoing handle out on its own; with Shift the readout +/// gives the constrained handle the preview shows. +#[test] +fn info_readout_tracks_the_last_anchor_handle() { + let (d, id, s) = drawing(vectorcraft_geom::SubPath::polyline(&[Point::new(10.0, 300.0), Point::new(60.0, 300.0)], false)); + let p = paint(); + let cx = plain(&d, &s, &p); + let mut t = PenTool { drawing: true, ..PenTool::default() }; + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 60.0, 300.0)); + assert_eq!(t.readout(&cx), None, "a click retracts the handle"); + assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 70.0, 280.0)), vec![set_out(id, 1, 70.0, 280.0)]); + assert_eq!(t.readout(&cx), drag_readout(10.0, -20.0)); + let shift = Mods { shift: true, ..Mods::default() }; + // 26.6° from the anchor: Shift turns it to the 45° step nearest. + let acts = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 80.0, 290.0).with_mods(shift)); + let [Action::Preview(_, v)] = acts.as_slice() else { panic!("not a handle preview: {acts:?}") }; + let (hx, hy) = (v["x"].as_f64().unwrap_or(f64::NAN), v["y"].as_f64().unwrap_or(f64::NAN)); + assert!(((hx - 60.0) + (hy - 300.0)).abs() < 1e-9, "constrained to 45°: {v}"); + assert_eq!(t.readout(&cx), drag_readout(hx - 60.0, hy - 300.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 80.0, 290.0)); + assert_eq!(t.readout(&cx), None); +} + +/// Space moves the anchor and its handles together, so the handle keeps its length; Alt leaves +/// the incoming handle behind and the readout follows the outgoing one. +#[test] +fn info_readout_follows_space_and_alt() { + let (d, s, p) = (vectorcraft_doc::Document::new(500.0, 500.0), Selection::default(), paint()); + let cx = plain(&d, &s, &p); + let mut t = PenTool::default(); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 400.0, 420.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 450.0, 420.0)); + assert_eq!(t.readout(&cx), drag_readout(50.0, 0.0)); + let space = Mods { space: true, ..Mods::default() }; + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 450.0, 380.0).with_mods(space)); + assert_eq!(t.readout(&cx), drag_readout(50.0, 0.0), "the anchor moved with the handle"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 460.0, 400.0)); + assert_eq!(t.readout(&cx), drag_readout(60.0, 20.0), "measured from the moved anchor"); + let alt = Mods { alt: true, ..Mods::default() }; + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 400.0, 450.0).with_mods(alt)); + assert_eq!(t.readout(&cx), drag_readout(0.0, 70.0)); +} + +/// A dropped press and switching tools clear the readout. +#[test] +fn info_readout_clears_on_a_dropped_press_and_deactivate() { + let (d, s, p) = (vectorcraft_doc::Document::new(500.0, 500.0), Selection::default(), paint()); + let cx = plain(&d, &s, &p); + let mut t = PenTool::default(); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 100.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 120.0, 100.0)); + assert_eq!(t.readout(&cx), drag_readout(20.0, 0.0)); + t.drop_press(&cx); + assert_eq!(t.readout(&cx), None, "dropped"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 100.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 100.0, 130.0)); + assert_eq!(t.readout(&cx), drag_readout(0.0, 30.0)); + t.deactivate(&cx); + assert_eq!(t.readout(&cx), None, "deactivated"); +} diff --git a/crates/tools/src/place.rs b/crates/tools/src/place.rs index 66d3fbc5f1..813ec99429 100644 --- a/crates/tools/src/place.rs +++ b/crates/tools/src/place.rs @@ -188,6 +188,33 @@ impl Tool for PlaceTool { } } + /// A queue whose every entry has its `params` object and a finite `width` and `height`, and + /// `current` within the queue held. + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + match key { + "queue" => check_queue(value).map(drop), + "current" => check_current(value, self.entries.len()), + _ => Err(crate::option_check::unknown(key)), + } + } + + /// As [`Self::check_option`], except that a `current` given with a `queue` is an index into + /// that queue (the queue is set first). + fn check_options(&self, values: &serde_json::Map) -> Result<(), String> { + let mut held = self.entries.len(); + if let Some(queue) = values.get("queue") { + held = check_queue(queue)?; + } + for (k, v) in values { + match k.as_str() { + "queue" => {} + "current" => check_current(v, held)?, + _ => self.check_option(k, v)?, + } + } + Ok(()) + } + /// Switching tools discards what the cursor holds. fn deactivate(&mut self, _cx: &ToolContext) -> Vec { self.entries.clear(); @@ -196,6 +223,35 @@ impl Tool for PlaceTool { } } +/// The number of files `queue` holds, or an error when an entry lacks its `params` object or a +/// finite `width` and `height`. +fn check_queue(queue: &Value) -> Result { + let entry = |e: &Value| { + e.get("params").is_some_and(Value::is_object) + && e.get("name").is_none_or(Value::is_string) + && ["width", "height"].iter().all(|k| e.get(k).and_then(Value::as_f64).is_some_and(f64::is_finite)) + }; + let entries = match queue.get("entries") { + None => Some(0), + Some(e) => e.as_array().filter(|a| a.iter().all(entry)).map(Vec::len), + }; + match entries { + Some(n) if queue.is_object() && queue.get("prev").is_none_or(Value::is_string) => Ok(n), + _ => Err("`queue` must be {entries: [{params, name, width, height}], prev?}: each entry with a params object and a finite \ + width and height" + .into()), + } +} + +/// `current` is the index of one of the `held` files. +fn check_current(current: &Value, held: usize) -> Result<(), String> { + match held { + _ if current.as_u64().is_some_and(|i| i < held as u64) => Ok(()), + 0 => Err("`current` can't be set: no file is queued".into()), + _ => Err(format!("`current` must be the index of a queued file, from 0 to {}", held - 1)), + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/tools/src/shape.rs b/crates/tools/src/shape.rs index 571a90daa0..d4c8d4f36c 100644 --- a/crates/tools/src/shape.rs +++ b/crates/tools/src/shape.rs @@ -1088,6 +1088,21 @@ impl Tool for ShapeTool { } } } + /// The options every shape tool keeps ([`Self::options`]). Any finite angle is taken: it is + /// kept as the same direction from 0 to 360°. + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + use crate::option_check as c; + match key { + "sides" | "points" => c::whole(key, v, 3, 1000), + "anchors" => c::whole(key, v, 2, 1000), + "cornerRadius" => c::number(key, v, 0.0, MAX_CORNER_RADIUS), + "starRatio" => c::number(key, v, 0.01, 1.0), + "length" => c::number(key, v, 0.0, 1e6), + "angle" => c::finite(key, v), + "fillLine" => c::boolean(key, v), + _ => Err(c::unknown(key)), + } + } } #[cfg(test)] diff --git a/crates/tools/src/shape/tests.rs b/crates/tools/src/shape/tests.rs index 54ccc4a7f9..ec911f4cfb 100644 --- a/crates/tools/src/shape/tests.rs +++ b/crates/tools/src/shape/tests.rs @@ -1659,6 +1659,18 @@ fn a_move_from_the_centre_point_snaps_and_shows_the_hollow_arrow() { assert_eq!(t.cursor(&c, Point::new(160.0, 150.0), Mods::default()), Cursor::Arrow); } +/// `tool.setOption` takes an ellipse's anchor count from 2 to 1000, as the tool keeps it. +#[test] +fn the_anchor_count_is_checked_against_its_range() { + let t = ShapeTool::new("ellipse"); + for n in [2, 4, 1000] { + assert_eq!(t.check_option("anchors", &json!(n)), Ok(()), "{n}"); + } + for bad in [json!(1), json!(1001), json!(4.5), json!("4")] { + assert_eq!(t.check_option("anchors", &bad), Err("`anchors` must be a whole number from 2 to 1000".into()), "{bad}"); + } +} + /// A drag event to `(x, y)` with Backtick held or not. fn quote_drag(x: f64, y: f64, held: bool) -> PointerEvent { PointerEvent { backquote: held, ..PointerEvent::new(PointerKind::Drag, x, y) } diff --git a/crates/tools/src/symbolism.rs b/crates/tools/src/symbolism.rs index ba00ec4125..b4dd9e631b 100644 --- a/crates/tools/src/symbolism.rs +++ b/crates/tools/src/symbolism.rs @@ -222,6 +222,15 @@ impl Tool for SymbolismTool { _ => {} } } + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + use crate::option_check as c; + match key { + "diameter" => c::number(key, v, 2.0, 2000.0), + "intensity" | "density" => c::number(key, v, 1.0, 10.0), + "symbol" | "style" => c::string_or_null(key, v), + _ => Err(c::unknown(key)), + } + } } /// Paintbrush: the freehand gesture, painting with the current brush. @@ -293,6 +302,9 @@ impl Tool for BrushPaintTool { self.inner.set_option(key, v); } } + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + if key == "brush" { crate::option_check::string_or_null(key, v) } else { self.inner.check_option(key, v) } + } fn wants_samples(&self) -> bool { self.inner.wants_samples() } diff --git a/crates/tools/src/text.rs b/crates/tools/src/text.rs index 763325f90e..fb7e38bd0f 100644 --- a/crates/tools/src/text.rs +++ b/crates/tools/src/text.rs @@ -137,6 +137,15 @@ fn text_hash(s: &str) -> u64 { /// The edited text's layout, keyed by [`vectorcraft_text::layout_inputs`] and the text. type CachedLayout = ((u64, TextObject), Arc); +/// The layouts of the frames other than the edited one that the overlays draw (the ports of the +/// selected area type and type on a path, the other frames of a selected story), by frame, each +/// kept with the layout inputs and the text it was made from ([`TypeTool::frame_layout`]). +type FrameLayouts = std::collections::HashMap; + +/// The most other frames' layouts [`TypeTool::frames`] keeps: every port drawn ([`PORTS_MAX`]) +/// and a long story's frames. The frames an overlays call draws past it are laid out on each call. +const FRAME_LAYOUTS_MAX: usize = 2_048; + /// Process-global Type-tool edit-session counter: the IME target's replacement epoch. /// /// A per-tool counter restarts at zero when the tool is recreated (a document switch, File › @@ -220,6 +229,9 @@ pub struct TypeTool { /// The state at the start of each `command.batch` still running, innermost last. batches: Vec, cache: Mutex>, + /// The other frames' layouts the last overlays drew ([`FrameLayouts`]): each overlays call + /// keeps only the frames it draws. + frames: Mutex, } struct BeforePress { @@ -296,6 +308,28 @@ impl TypeTool { l } + /// Layout of `t`, frame `id`, for an overlays call that draws a frame other than the edited + /// one: the layout kept in `now` or `was` for `id` when it was made from the layout inputs + /// `fonts` and the same text, otherwise a new one. It is kept in `now` either way while `now` + /// holds fewer than [`FRAME_LAYOUTS_MAX`]. + fn frame_layout(now: &mut FrameLayouts, was: &mut FrameLayouts, fonts: u64, id: NodeId, t: &TextObject) -> Arc { + if let Some(((g, k), l)) = now.get(&id) + && *g == fonts + && k == t + { + return l.clone(); + } + let kept = match was.remove(&id) { + Some(((g, k), l)) if g == fonts && &k == t => ((g, k), l), + _ => ((fonts, t.clone()), Arc::new(vectorcraft_text::layout(FontDb::global(), t))), + }; + let l = kept.1.clone(); + if now.len() < FRAME_LAYOUTS_MAX { + now.insert(id, kept); + } + l + } + /// The edited text used to find word and paragraph boundaries for selection: the typing session's /// runs, or the document's current text when there is no live session or it has gone stale. fn plain(&self, cx: &ToolContext) -> String { diff --git a/crates/tools/src/text/tests.rs b/crates/tools/src/text/tests.rs index 94063166bc..89a24cc3bf 100644 --- a/crates/tools/src/text/tests.rs +++ b/crates/tools/src/text/tests.rs @@ -1636,10 +1636,276 @@ fn the_edited_types_ports_follow_the_limit_too() { tool.start_editing(id, 0); let boxes = |o: &[Overlay]| o.iter().filter(|o| matches!(o, Overlay::Highlight { color: [255, 255, 255, 255], .. })).count(); assert_eq!(boxes(&tool.overlays(&cx(&d, &sel, &p))), 2 * PORTS_MAX, "at the limit, the edited one's included"); + assert_eq!(kept_frames(&tool), PORTS_MAX - 1, "the other frames' layouts are kept"); let copy = d.alloc_id(); d.insert(Some(l), 1, Node::new(copy, node.kind.clone())).unwrap(); sel.add(copy); assert_eq!(boxes(&tool.overlays(&cx(&d, &sel, &p))), 0, "past it, not even the edited one's"); + assert_eq!(kept_frames(&tool), 0, "no ports drawn, no layouts kept"); +} + +/// How many other frames' layouts the Type tool keeps between overlays calls. +fn kept_frames(tool: &TypeTool) -> usize { + tool.frames.lock().unwrap().len() +} + +/// The value `f` returns, and how many layouts this thread started while it ran. +fn counted(f: impl FnOnce() -> T) -> (T, u64) { + let before = vectorcraft_text::test_fonts::layouts_on_this_thread(); + let v = f(); + (v, vectorcraft_text::test_fonts::layouts_on_this_thread() - before) +} + +/// A document with area type frames of `texts` (each 120 × 40 pt, one under the other) and their ids. +fn area_frames(texts: &[&str]) -> (Document, Vec) { + let mut d = Document::new(500.0, 2000.0); + let l = d.layers[0].id; + let mut ids = Vec::new(); + for (i, s) in texts.iter().enumerate() { + let id = d.alloc_id(); + let mut t = TextObject::point(Point::new(50.0, 50.0 + 60.0 * i as f64), s, CharStyle::default()); + t.kind = area_kind(120.0, 40.0); + d.insert(Some(l), 0, Node::new(id, NodeKind::Text(Box::new(t)))).unwrap(); + ids.push(id); + } + (d, ids) +} + +/// Area type in a `w` × `h` pt frame. +fn area_kind(w: f64, h: f64) -> TextKind { + TextKind::Area { frame: vectorcraft_geom::PathData::from_bezpath(&Rect::new(0.0, 0.0, w, h).to_path(0.1)) } +} + +fn text_mut(d: &mut Document, id: NodeId) -> &mut TextObject { + match &mut d.node_mut(id).unwrap().kind { + NodeKind::Text(t) => t, + _ => panic!("not text"), + } +} + +const OVERFLOWS: &str = "This text is far too long to fit in a frame of one hundred and twenty by forty points."; + +/// The Type tools draw the ports of several different selected frames, with and without one of +/// them being edited, without laying any of them out again on the next frame, and draw the same +/// overlays as a tool that lays every frame out afresh. +#[test] +fn type_overlays_keep_the_selected_frames_layouts() { + let (d, ids) = area_frames(&["One", "Two words", "Three words here", OVERFLOWS]); + let (mut sel, p) = (Selection::default(), paint()); + sel.set(ids.iter().copied()); + let c = cx(&d, &sel, &p); + let mut probe = Vec::new(); + push_port(&mut probe, Point::ZERO, PortState::Overflow, [0, 0, 0], 1.0); + let Some(Overlay::Line { color: red, .. }) = probe.last().cloned() else { panic!("the red plus is drawn with lines") }; + let red_plus = |o: &[Overlay]| o.iter().filter(|o| matches!(o, Overlay::Line { color, .. } if *color == red)).count(); + for editing in [None, Some(ids[0])] { + let mut tool = TypeTool::new("areaType"); + if let Some(id) = editing { + tool.start_editing(id, 0); + } + let (first, n) = counted(|| tool.overlays(&c)); + assert!(n > 0, "{editing:?}: the first frame lays the frames out"); + let (second, n) = counted(|| tool.overlays(&c)); + assert_eq!(n, 0, "{editing:?}: the next frame lays none out again"); + assert_eq!(first, second, "{editing:?}"); + let mut fresh = TypeTool::new("areaType"); + if let Some(id) = editing { + fresh.start_editing(id, 0); + } + assert_eq!(second, fresh.overlays(&c), "{editing:?}: what laying out afresh draws"); + assert!(red_plus(&second) > 0, "{editing:?}: the overflowing frame's out port shows its red plus"); + } +} + +/// After Select All in threaded text, the story's other frames are highlighted without laying them +/// out again on the next frame. +#[test] +fn type_overlays_keep_a_selected_storys_layouts() { + let (mut d, ids) = area_frames(&["Story one ", "story two ", "story three ", "story four"]); + d.text_threads.push(ids.clone()); + let (mut sel, p) = (Selection::default(), paint()); + sel.set([ids[0]]); + let story = json!({ "story": ids.iter().map(|id| id.0).collect::>() }); + let c = cx(&d, &sel, &p); + let mut tool = TypeTool::new("areaType"); + tool.start_editing(ids[0], 0); + tool.set_option("selectAll", &story); + assert_eq!(tool.story_others(&c).len(), 3); + let highlights = |o: &[Overlay]| o.iter().filter(|o| matches!(o, Overlay::Highlight { color: [60, 120, 255, 90], .. })).count(); + let (first, n) = counted(|| tool.overlays(&c)); + assert!(n > 0); + let (second, n) = counted(|| tool.overlays(&c)); + assert_eq!(n, 0, "the story's other frames are not laid out again"); + assert_eq!(first, second); + let mut fresh = TypeTool::new("areaType"); + fresh.start_editing(ids[0], 0); + fresh.set_option("selectAll", &story); + assert_eq!(second, fresh.overlays(&c), "what laying out afresh draws"); + assert!(highlights(&second) >= 4, "every frame's text is highlighted: {}", highlights(&second)); +} + +/// A kept layout is used only while its frame's text object is unchanged: editing the text, +/// changing the frame and undoing both lay out just the frames that changed, a frame that is no +/// longer drawn is dropped, and choosing another tool drops them all. +#[test] +fn type_overlays_lay_out_again_only_the_frames_that_changed() { + let (mut d, ids) = area_frames(&["One", "Two", "Three", OVERFLOWS]); + let (mut sel, p) = (Selection::default(), paint()); + sel.set(ids.iter().copied()); + let mut tool = TypeTool::new("areaType"); + let fresh = |d: &Document, sel: &Selection| TypeTool::new("areaType").overlays(&cx(d, sel, &p)); + tool.overlays(&cx(&d, &sel, &p)); + let start = d.clone(); + // Edit the text of one frame. + text_mut(&mut d, ids[1]).runs[0].text = OVERFLOWS.into(); + let (o, n) = counted(|| tool.overlays(&cx(&d, &sel, &p))); + assert_eq!(n, 1, "only the edited frame"); + assert_eq!(o, fresh(&d, &sel)); + // Make another frame tall enough for its text. + text_mut(&mut d, ids[3]).kind = area_kind(120.0, 400.0); + let (o, n) = counted(|| tool.overlays(&cx(&d, &sel, &p))); + assert_eq!(n, 1, "only the changed frame"); + assert_eq!(o, fresh(&d, &sel)); + // Undo puts both back. + let (o, n) = counted(|| tool.overlays(&cx(&start, &sel, &p))); + assert_eq!(n, 2, "the two frames undo changed"); + assert_eq!(o, fresh(&start, &sel)); + // A smaller selection keeps only its frames; the others are laid out again when selected again. + let mut one = Selection::default(); + one.set([ids[0]]); + assert_eq!(counted(|| tool.overlays(&cx(&start, &one, &p))).1, 0); + assert_eq!(kept_frames(&tool), 1); + let (o, n) = counted(|| tool.overlays(&cx(&start, &sel, &p))); + assert_eq!(n, 3); + assert_eq!(o, fresh(&start, &sel)); + tool.deactivate(&cx(&start, &sel, &p)); + assert_eq!(kept_frames(&tool), 0, "another tool chosen"); +} + +/// A story of more frames than [`FRAME_LAYOUTS_MAX`] keeps that many layouts, lays the rest out on +/// each call, and draws what laying every frame out afresh draws. +#[test] +fn type_overlays_keep_at_most_frame_layouts_max() { + let texts = vec!["a "; FRAME_LAYOUTS_MAX + 3]; + let (mut d, ids) = area_frames(&texts); + d.text_threads.push(ids.clone()); + let (mut sel, p) = (Selection::default(), paint()); + sel.set([ids[0]]); + let story = json!({ "story": ids.iter().map(|id| id.0).collect::>() }); + let c = cx(&d, &sel, &p); + let mut tool = TypeTool::new("areaType"); + tool.start_editing(ids[0], 0); + tool.set_option("selectAll", &story); + let first = tool.overlays(&c); + assert_eq!(kept_frames(&tool), FRAME_LAYOUTS_MAX); + let (second, n) = counted(|| tool.overlays(&c)); + assert_eq!(n, 2, "the two other frames past the limit"); + assert_eq!(kept_frames(&tool), FRAME_LAYOUTS_MAX); + assert_eq!(first, second); +} + +#[test] +fn frame_layouts_follow_fonts_and_hyphenation_exceptions() { + // Other tests can load system fonts; this assertion needs its own process-wide database. + #[cfg(not(target_arch = "wasm32"))] + if std::env::var("VECTORCRAFT_FONT_CACHE_TEST_CHILD").as_deref() != Ok("1") { + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "text::tests::frame_layouts_follow_fonts_and_hyphenation_exceptions", "--nocapture", "--test-threads=1"]) + .env("VECTORCRAFT_FONT_CACHE_TEST_CHILD", "1") + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + output.status.success() && stdout.contains("test result: ok. 1 passed; 0 failed;"), + "isolated font cache test failed:\n{stdout}\n{}", + String::from_utf8_lossy(&output.stderr), + ); + return; + } + let (mut d, ids) = area_frames(&["One", "Two", "Three ", "four"]); + d.text_threads.push(vec![ids[2], ids[3]]); + let (mut sel, p) = (Selection::default(), paint()); + sel.set([ids[0], ids[1], ids[2]]); + let c = cx(&d, &sel, &p); + let mut tool = TypeTool::new("areaType"); + tool.start_editing(ids[2], 0); + tool.set_option("selectAll", &json!({ "story": [ids[2].0, ids[3].0] })); + tool.overlays(&c); + assert_eq!(counted(|| tool.overlays(&c)).1, 0); + // Two selected frames, the story's other frame and the edited one. + let font = vectorcraft_text::test_fonts::variable_font().unwrap(); + assert!(FontDb::global().add_font(font) > 0, "the test font is new to this process"); + assert_eq!(counted(|| tool.overlays(&c)).1, 4, "a font added after the layouts refreshes them"); + assert_eq!(counted(|| tool.overlays(&c)).1, 0); + vectorcraft_text::set_hyphenation_exceptions(&vectorcraft_text::hyphenation_exceptions()); + assert_eq!(counted(|| tool.overlays(&c)).1, 4, "new hyphenation exceptions refresh them"); +} + +/// Times the Type tool's overlays on 200 selected area type frames of about 400 characters, one of +/// them edited, and on a 5-frame story after Select All, laying every frame out on each call as the +/// tool did before it kept their layouts (base) against keeping them (kept). Run with +/// `cargo test --release -p vectorcraft-tools --lib type_overlays_timing -- --ignored --nocapture`. +#[test] +#[ignore = "timing, run by hand"] +fn type_overlays_timing() { + use std::time::Instant; + let words = "The quick brown fox jumps over the lazy dog while seven wizards box. ".repeat(6); + let texts: Vec = (0..200).map(|i| format!("{i} {words}")).collect(); + let (mut d, ids) = area_frames(&texts.iter().map(String::as_str).collect::>()); + for id in &ids { + text_mut(&mut d, *id).kind = area_kind(200.0, 200.0); + } + let story: Vec = ids[..5].to_vec(); + d.text_threads.push(story.clone()); + let p = paint(); + let mut all = Selection::default(); + all.set(ids.iter().copied()); + let mut first = Selection::default(); + first.set([ids[0]]); + // Before, the selected frames' layouts replaced the edited one's single kept layout; with only + // the edited frame selected, it stayed. + let cases = [("200 selected frames, one edited", &all, None, true), ("5-frame story, Select All", &first, Some(story), false)]; + for (name, sel, story, evicted) in cases { + let c = cx(&d, sel, &p); + let mut tool = TypeTool::new("areaType"); + tool.start_editing(ids[0], 0); + if let Some(s) = &story { + tool.set_option("selectAll", &json!({ "story": s.iter().map(|id| id.0).collect::>() })); + } + let expected = tool.overlays(&c); + tool.frames.lock().unwrap().clear(); + if evicted { + *tool.cache.lock().unwrap() = None; + } + let (_, before) = counted(|| tool.overlays(&c)); + let (_, after) = counted(|| tool.overlays(&c)); + println!("{name}: {before} layouts per call before, {after} after"); + let calls = 20; + let (mut base, mut kept) = (Vec::new(), Vec::new()); + for _ in 0..7 { + let start = Instant::now(); + for _ in 0..calls { + // Before: the other frames were laid out on every call. + tool.frames.lock().unwrap().clear(); + if evicted { + *tool.cache.lock().unwrap() = None; + } + assert_eq!(tool.overlays(&c), expected); + } + base.push(start.elapsed().as_secs_f64() * 1000.0 / f64::from(calls)); + let start = Instant::now(); + for _ in 0..calls { + assert_eq!(tool.overlays(&c), expected); + } + kept.push(start.elapsed().as_secs_f64() * 1000.0 / f64::from(calls)); + } + let median = |v: &mut Vec| { + v.sort_by(f64::total_cmp); + v[v.len() / 2] + }; + println!("{name}: base runs {base:.3?} ms per call, kept runs {kept:.3?} ms per call"); + println!("{name}: median base {:.3} ms, kept {:.3} ms per call", median(&mut base), median(&mut kept)); + } } /// Type on a path has its in port just before its start bracket and its out port just past its diff --git a/crates/tools/src/text/tool.rs b/crates/tools/src/text/tool.rs index e18754f0ca..2945777610 100644 --- a/crates/tools/src/text/tool.rs +++ b/crates/tools/src/text/tool.rs @@ -472,6 +472,7 @@ impl Tool for TypeTool { } fn deactivate(&mut self, cx: &ToolContext) -> Vec { self.prev_tool = None; + self.frames.get_mut().unwrap_or_else(|e| e.into_inner()).clear(); self.finish(cx) } /// Editing ends when a command takes the text out of the selection (Deselect, another object @@ -609,6 +610,25 @@ impl Tool for TypeTool { _ => {} } } + /// The calls [`Self::set_option`] takes: `commitTyping`, `endTyping`, `selectAll` and + /// `stopEditing` take any value, the others the shapes they read. + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + let index = |a: &str, b: &str| v.get(a).or_else(|| v.get(b)).and_then(Value::as_u64).is_some(); + let ok = match key { + "textSelection" => index("editing", "id") && index("anchor", "start") && index("caret", "end"), + "select" => index("start", "start") && index("end", "end"), + "prevTool" | "previousTool" => return crate::option_check::string_or_null(key, v), + "copy" => serde_json::from_value::>(v.clone()).is_ok(), + "commitTyping" | "endTyping" | "selectAll" | "stopEditing" => true, + _ => return Err(crate::option_check::unknown(key)), + }; + let shape = match key { + "textSelection" => "{editing, anchor, caret} with whole numbers", + "select" => "{start, end} with whole numbers", + _ => "a list of text runs", + }; + if ok { Ok(()) } else { Err(format!("`{key}` must be {shape}")) } + } fn overlays(&self, cx: &ToolContext) -> Vec { let mut o = self.snap.guides().to_vec(); if let (Some((_, s)), Some(d)) = (self.press, self.drag) { @@ -633,13 +653,17 @@ impl Tool for TypeTool { o.push(Overlay::Measure { p: d, text: cx.size_label(size.width, size.height) }); } } + // The other frames this call draws keep their layouts for the next call; the rest are dropped. + let fonts = vectorcraft_text::layout_inputs(); + let mut now = self.frames.lock().unwrap_or_else(|e| e.into_inner()); + let mut was = std::mem::take(&mut *now); // The ports of selected area type and type on a path, as many as show ([`PORTS_MAX`]), the // edited one's included. let shown = ports_shown(cx.doc, &cx.selection.objects); if shown { for id in cx.selection.objects.iter().filter(|id| Some(**id) != self.editing) { if let Some(t) = ported(cx.doc, *id) { - let lay = self.layout(t); + let lay = Self::frame_layout(&mut now, &mut was, fonts, *id, t); ports(cx, *id, t, lay.overflow, &mut o); } } @@ -688,7 +712,7 @@ impl Tool for TypeTool { if self.preedit.is_none() { for f in self.story_others(cx) { let Some(other) = Self::text(cx, f) else { continue }; - let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), other); + let lay = Self::frame_layout(&mut now, &mut was, fonts, f, other); for q in vectorcraft_text::selection_quads(&lay, 0, edit::runs_len(&other.runs)) { o.push(Overlay::Highlight { quad: q.map(|p| other.xf * p), color: [60, 120, 255, 90] }); } diff --git a/crates/tools/src/xform/artboard.rs b/crates/tools/src/xform/artboard.rs index 5af642c44b..e8cac59c88 100644 --- a/crates/tools/src/xform/artboard.rs +++ b/crates/tools/src/xform/artboard.rs @@ -726,6 +726,18 @@ impl Tool for ArtboardTool { } } + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + use crate::option_check as c; + match key { + "active" if value.as_u64().is_some() => Ok(()), + "active" => Err("`active` must be an artboard index: a whole number from 0".into()), + "selected" if value.as_array().is_some_and(|a| !a.is_empty() && a.iter().all(|i| i.as_u64().is_some())) => Ok(()), + "selected" => Err("`selected` must be a list of artboard indexes, the active one first".into()), + "moveArt" | "scaleArt" | "suppressFitClick" => c::boolean(key, value), + _ => Err(c::unknown(key)), + } + } + /// A drag is moving or resizing artboards (Artboard Options › Update While Dragging reads it). fn transforming(&self) -> bool { matches!(self.drag, Some(Drag::Move { began: true, .. } | Drag::Resize { began: true, .. })) diff --git a/crates/tools/src/xform/eyedropper.rs b/crates/tools/src/xform/eyedropper.rs index eb1b8b3895..7b91731691 100644 --- a/crates/tools/src/xform/eyedropper.rs +++ b/crates/tools/src/xform/eyedropper.rs @@ -593,6 +593,16 @@ impl Tool for EyedropperTool { } } + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + use crate::option_check as c; + match key { + "stop" => c::string_or_null(key, value), + "brushKeyColor" => c::boolean(key, value), + "textSelection" => self.text_selection.check_option(key, value), + _ => Err(c::unknown(key)), + } + } + /// Drop the range when its text is removed or no longer selected. fn after_command(&mut self, cx: &ToolContext) -> Vec { self.text_selection.after_command(cx) diff --git a/crates/tools/src/xform/free.rs b/crates/tools/src/xform/free.rs index 1583584940..6b7f213469 100644 --- a/crates/tools/src/xform/free.rs +++ b/crates/tools/src/xform/free.rs @@ -237,7 +237,15 @@ impl FreeTransformTool { self.measure = cx.transform_tools_guides.then(|| (p, cx.size_label(nr.width(), nr.height()))); bx.conjugate(a) } - Op::Shear(h) => bx.conjugate(shear_for_side(bx.rect, h, local, m.alt)), + Op::Shear(h) => { + let a = shear_for_side(bx.rect, h, local, m.alt); + // The shear's slope, read from the matrix the preview applies, labeled with the + // angle the Shear tool shows for the same slant. + let [_, vertical, horizontal, ..] = a.as_coeffs(); + let k = if matches!(h, Handle::Top | Handle::Bottom) { horizontal } else { vertical }; + self.measure = cx.transform_tools_guides.then(|| (p, format!("{:.1}°", 0.0 - k.atan().to_degrees()))); + bx.conjugate(a) + } Op::Rotate => { let (a, deg) = rotate_for_drag(bx.center(), d.start, p, shift); self.measure = cx.transform_tools_guides.then(|| (p, format!("{:.1}°", -deg))); @@ -379,6 +387,15 @@ impl Tool for FreeTransformTool { } } + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + use crate::option_check as c; + match key { + "mode" => c::one_of(key, value, &["free", "perspective", "distort", "freeDistort"]), + "constrain" => c::boolean(key, value), + _ => Err(c::unknown(key)), + } + } + fn deactivate(&mut self, _cx: &ToolContext) -> Vec { self.quad = None; self.guides.clear(); @@ -723,4 +740,63 @@ mod tests { t.pointer(&cx(false), &ev(PointerKind::Drag, 220.0, 230.0)); assert!(t.overlays(&cx(false)).iter().all(|o| !matches!(o, Overlay::Measure { .. }))); } + + /// The label a drag shows next to the pointer, and where. + fn shown_measure(t: &FreeTransformTool, cx: &ToolContext) -> Option<(Point, String)> { + t.overlays(cx).into_iter().find_map(|o| if let Overlay::Measure { p, text } = o { Some((p, text)) } else { None }) + } + + /// With Smart Guides' Transform Tools on, a Cmd side-handle shear shows its angle next to the + /// pointer, with the Shear tool's sign: the top side moved right and the right side moved down + /// by 20 pt on the 100 pt square slant 11.3° either way. Alt shears about the center. + #[test] + fn shear_drag_shows_its_angle_with_transform_tools_guides() { + let (d, id) = doc_with_rect(); + let mut s = Selection::default(); + s.add(id); + let p = paint(); + let cx = |on: bool| ToolContext { transform_tools_guides: on, ..cx(&d, &s, &p) }; + let cmd = Mods { cmd: true, ..Default::default() }; + let shear = |c: &ToolContext, from: (f64, f64), to: (f64, f64), m: Mods| { + let mut t = FreeTransformTool::default(); + t.pointer(c, &ev(PointerKind::Down, from.0, from.1).with_mods(m)); + let a = t.pointer(c, &ev(PointerKind::Drag, to.0, to.1).with_mods(m)); + assert_eq!(a[0], Action::Begin("Shear".into())); + let shown = shown_measure(&t, c); + assert_eq!(t.pointer(c, &ev(PointerKind::Up, to.0, to.1).with_mods(m)), vec![Action::Commit]); + assert_eq!(shown_measure(&t, c), None, "the label goes with the drag"); + shown + }; + let on = cx(true); + let off = Vec2::new(on.tol(12.0), on.tol(12.0)); + assert_eq!(shear(&on, (150.0, 100.0), (170.0, 100.0), cmd), Some((Point::new(170.0, 100.0) + off, "11.3°".into()))); + assert_eq!(shear(&on, (200.0, 150.0), (200.0, 170.0), cmd), Some((Point::new(200.0, 170.0) + off, "-11.3°".into()))); + // About the center the lever is half as long: atan(20 / 50). + let alt = Mods { alt: true, ..cmd }; + assert_eq!(shear(&on, (150.0, 100.0), (170.0, 100.0), alt).map(|m| m.1), Some("21.8°".into())); + // A drag straight away from the side, at right angles to it, shears nothing. + assert_eq!(shear(&on, (150.0, 100.0), (150.0, 90.0), cmd).map(|m| m.1), Some("0.0°".into())); + assert_eq!(shear(&cx(false), (150.0, 100.0), (170.0, 100.0), cmd), None); + } + + /// A handle drag that turns into a shear, and back into a scale, labels only what it does now. + #[test] + fn a_handle_drag_that_changes_operation_relabels_it() { + let (d, id) = doc_with_rect(); + let mut s = Selection::default(); + s.add(id); + let p = paint(); + let cx = ToolContext { transform_tools_guides: true, ..cx(&d, &s, &p) }; + let cmd = Mods { cmd: true, ..Default::default() }; + let mut t = FreeTransformTool::default(); + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 100.0)); + t.pointer(&cx, &ev(PointerKind::Drag, 150.0, 90.0)); + let size = cx.size_label(100.0, 110.0); + assert_eq!(shown_measure(&t, &cx).map(|m| m.1), Some(size.clone())); + let a = t.pointer(&cx, &ev(PointerKind::Drag, 170.0, 100.0).with_mods(cmd)); + assert_eq!(a[..2], [Action::Cancel, Action::Begin("Shear".into())]); + assert_eq!(shown_measure(&t, &cx).map(|m| m.1), Some("11.3°".into())); + t.pointer(&cx, &ev(PointerKind::Drag, 150.0, 90.0)); + assert_eq!(shown_measure(&t, &cx).map(|m| m.1), Some(size)); + } } diff --git a/crates/tools/src/xform/transform.rs b/crates/tools/src/xform/transform.rs index 16a1b93a8a..339984e9a1 100644 --- a/crates/tools/src/xform/transform.rs +++ b/crates/tools/src/xform/transform.rs @@ -432,6 +432,15 @@ impl Tool for TransformTool { } } + /// `origin` is `[x, y]`, or null to clear it. + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + if key != "origin" { + return Err(crate::option_check::unknown(key)); + } + let point = value.as_array().is_some_and(|a| a.len() == 2 && a.iter().all(|n| n.as_f64().is_some_and(f64::is_finite))); + if point || value.is_null() { Ok(()) } else { Err("`origin` must be [x, y] with finite numbers, or null".into()) } + } + fn deactivate(&mut self, _cx: &ToolContext) -> Vec { if self.end_drag().is_some_and(|d| d.began) { vec![Action::Cancel] } else { vec![] } } diff --git a/crates/ui-egui/src/addons/pathtools.rs b/crates/ui-egui/src/addons/pathtools.rs index 011af4b171..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 })), @@ -246,12 +248,15 @@ fn body(_app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { false } -/// OK: set the tool's options. +/// OK: set the tool's options. When the tool refuses one of them, nothing is set and the dialog +/// stays open. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { let tool = d.str("__tool"); let values: Map = d.fields.iter().filter(|(k, _)| !k.starts_with("__")).map(|(k, v)| (k.clone(), v.clone())).collect(); let r = app.run("tool.setOption", json!({ "tool": tool, "values": values })); - app.ui.dialog = None; + if r.is_ok() { + app.ui.dialog = None; + } r } 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 7ae09974e6..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,7 +90,9 @@ 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(), placed_keys: Default::default(), cursors: Default::default(), @@ -583,6 +586,7 @@ impl VectorcraftApp { self.ime_caret_rect = None; scrub::begin_frame(self, &ctx); font_menu::end_stale_preview(self, &ctx); + font_menu::apply_preview_size(self, &ctx); tools_float::track(self, &ctx); // A selection move released over a panel ends before any panel sees the release (#2826). canvas::release_over_panel(self, &ctx); @@ -631,6 +635,8 @@ impl VectorcraftApp { plugin_runs::show(self, &ctx); trace_runs::show(self, &ctx); opening::show(self, &ctx); + // After every window this pass may open, and before the palette's field takes the keyboard. + panel_docking::close_overlays_for_modal(self, &ctx); palette::show(self, &ctx); // After every panel had its chance to draw in this pass. crate::panels::three_d::end_stale_drag(self, &ctx); diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index 6dc036fcf2..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,9 +65,15 @@ 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)>, + /// The symbol instances in the selection and its groups, for (document uid, revision): the + /// Properties and Symbols panels read them every frame. + pub symbol_instances: Option<((u64, u64), SymbolInstances)>, /// [`CacheKey::plugins`] by document uid, with the plug-in revision /// ([`vectorcraft_render::effects::plugin_revision`]) it was last checked at. pub plugin_keys: std::collections::HashMap, @@ -111,10 +121,48 @@ 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); +/// [`CanvasCache::symbol_instances`]: the symbol instances in the selection and its groups. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct SymbolInstances { + /// Each instance's id, in the order the selection's subtrees list them. + pub ids: Vec, + /// One of them has appearance changes of its own (`symbol_overrides`). + pub changed: bool, + /// One of them has a scale, rotation or shear that Reset Transformation would change; measured + /// on the first read. + pub transformed: Option, +} + /// [`CanvasCache::print_tiling`]: the print tiling of (document uid, revision). pub type PrintTilingCache = ((u64, u64), std::sync::Arc>); diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 4b9632fd47..ef7ef0ba78 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -69,9 +69,9 @@ pub(crate) use panes::{consolidate, note_drop, noted_cursor, pane, release_on_no pub(crate) use raster::{KeptFrame, color_image, color_image_owned, render_job}; use raster::{changed_pixels, frame_ppp, pixel_region, upload}; pub use selection_marks::SelectionMarks; -#[cfg(test)] -pub(crate) use task_bar::chip_paints; use task_bar::task_bar; +#[cfg(test)] +pub(crate) use task_bar::{chip_paints, images_with_other_art}; pub(crate) use task_bar::{has_colors, task_bar_rect, task_bar_shows_fonts, task_bar_shows_type}; #[cfg(test)] use tool_overlays::{DIAL_RADIUS, HiddenMarks}; diff --git a/crates/ui-egui/src/canvas/context.rs b/crates/ui-egui/src/canvas/context.rs index d8cd85d13a..9cdec919b5 100644 --- a/crates/ui-egui/src/canvas/context.rs +++ b/crates/ui-egui/src/canvas/context.rs @@ -75,10 +75,11 @@ pub(super) fn panel_drop(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respons } return; } - // A symbol from the Symbols panel: an instance centred where it is dropped, on art or not. - if let widgets::PanelDrag::Symbol(name) = &*d { + // A symbol from the Symbols panel: an instance centred where it is dropped, on art or not. A + // symbol of another document is added to this one first. + if let widgets::PanelDrag::Symbol { document, name } = &*d { let at = xf.to_doc(pos); - if let Err(e) = app.run("symbol.place", json!({"name": name, "x": at.x, "y": at.y})) { + if let Err(e) = app.run("symbol.placeFromDocument", json!({"sourceDocument": document, "name": name, "x": at.x, "y": at.y})) { app.status(e); } return; @@ -155,7 +156,7 @@ pub(super) fn panel_drop(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respons // Art dragged back onto the canvas: its move was already dropped. (A symbol was placed // above.) widgets::PanelDrag::Art(_) - | widgets::PanelDrag::Symbol(_) + | widgets::PanelDrag::Symbol { .. } | widgets::PanelDrag::LibrarySymbol { .. } | widgets::PanelDrag::LibraryGraphic { .. } => return, // A Libraries panel style or group only moves within that panel. 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/canvas/task_bar.rs b/crates/ui-egui/src/canvas/task_bar.rs index e49fa9bfc7..c133c003f8 100644 --- a/crates/ui-egui/src/canvas/task_bar.rs +++ b/crates/ui-egui/src/canvas/task_bar.rs @@ -92,6 +92,31 @@ fn smooth_tool_on_paths(app: &VectorcraftApp, ctx: &egui::Context) -> bool { found } +/// Whether the selection holds images together with other objects, for which the bar offers Make +/// Clipping Mask: at least one selected object is an image and at least one is not (a selected id +/// with no object counts as not an image). The walk stops once it has seen both. The answer is kept +/// in `ctx` for the document's revision, as [`smooth_tool_on_paths`] keeps its own. +pub(crate) fn images_with_other_art(st: &vectorcraft_engine::DocState, ctx: &egui::Context) -> bool { + let id = task_bar_id().with("mixed"); + let key = (st.uid, st.revision); + if let Some((k, found)) = ctx.data(|d| d.get_temp::<((u64, u64), bool)>(id)) + && k == key + { + return found; + } + let (mut image, mut other) = (false, false); + let found = st.selection.objects.iter().any(|id| { + if st.doc.node(*id).is_some_and(|o| matches!(o.kind, NodeKind::Image(_))) { + image = true; + } else { + other = true; + } + image && other + }); + ctx.data_mut(|d| d.insert_temp(id, (key, found))); + found +} + /// Whether the bar shows its blank canvas actions, Draw (Pencil) and Place Image: a selection tool is /// in use and the active document has no artwork, only layers and guides. fn blank_canvas(app: &VectorcraftApp) -> bool { @@ -192,10 +217,7 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { _ => None, }); // Images and vector art selected together: a clipping mask is the likely next step. - let mixed = n > 1 && { - let images = st.selection.objects.iter().filter_map(|id| st.doc.node(*id)).filter(|o| matches!(o.kind, NodeKind::Image(_))).count(); - images > 0 && images < n - }; + let mixed = n > 1 && images_with_other_art(st, ui.ctx()); // An Image Trace object: the group the engine names "Image Trace", its source image first. let is_trace = is_group && first.as_ref().is_some_and(|f| { diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 3f8cc4a661..cea61e42bb 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -9028,6 +9028,36 @@ fn escape_while_editing_in_isolation_returns_to_selection_tool_and_keeps_isolati assert!(app.session.active().unwrap().isolation.is_none(), "2nd Escape must exit isolation mode"); } +/// One Escape leaves isolation mode from a sublayer two levels down, where Exit Isolation Mode goes +/// up one layer at a time. +#[test] +fn escape_leaves_an_isolated_sublayer_in_one_step() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let top = app.session.active().unwrap().doc.layers[0].id; + let mid = app.session.execute("layer.newSublayer", &json!({"parent": top.0})).unwrap()["id"].as_u64().unwrap(); + let deep = app.session.execute("layer.newSublayer", &json!({"parent": mid})).unwrap()["id"].as_u64().unwrap(); + app.session.execute("layer.setCurrent", &json!({"id": deep})).unwrap(); + app.session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 20})).unwrap(); + app.session.execute("object.isolate", &json!({"id": deep})).unwrap(); + app.select_tool("selection"); + let ctx = egui::Context::default(); + let timed = |app: &mut VectorcraftApp, time: f64, events: Vec| { + let screen = egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)); + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), time: Some(time), events, ..Default::default() }, |ui| { + crate::shortcuts::handle(app, ui.ctx()); + show(app, ui) + }); + out.textures_delta.clear(); + }; + let esc = |pressed| egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; + timed(&mut app, 0.0, vec![]); + assert_eq!(app.session.active().unwrap().isolation, Some(vectorcraft_doc::NodeId(deep))); + timed(&mut app, 1.0, vec![esc(true), esc(false)]); + timed(&mut app, 1.1, vec![]); + assert_eq!(app.session.active().unwrap().isolation, None, "one Escape leaves every level"); +} + #[test] fn a_symbol_dropped_on_the_canvas_is_placed_there() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); @@ -9040,7 +9070,8 @@ fn a_symbol_dropped_on_the_canvas_is_placed_there() { let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); // Released over empty canvas: an instance centred there. let at = xf.to_screen(Point::new(250.0, 180.0)); - egui::DragAndDrop::set_payload(&ctx, widgets::PanelDrag::Symbol(name.clone())); + let document = app.session.active().unwrap().uid; + egui::DragAndDrop::set_payload(&ctx, widgets::PanelDrag::Symbol { document, name: name.clone() }); let up = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }; frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at), up]); let st = app.session.active().unwrap(); @@ -9051,6 +9082,106 @@ fn a_symbol_dropped_on_the_canvas_is_placed_there() { assert!((c - xf.to_doc(at)).hypot() < 1e-6, "{c:?}"); } +/// A new active document with a symbol `name` made from a `w` by `h` rectangle and no art; → its +/// uid. +fn document_with_symbol(app: &mut VectorcraftApp, name: &str, w: f64, h: f64) -> u64 { + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": w, "height": h})).unwrap(); + app.session.execute("symbol.new", &json!({"name": name})).unwrap(); + app.session.execute("edit.clear", &json!({})).unwrap(); + app.session.active().unwrap().uid +} + +/// The natural size the active document records for symbol `name`. +fn symbol_size(app: &VectorcraftApp, name: &str) -> (f64, f64) { + let st = app.session.active().unwrap(); + let size = st.doc.unknown.get(vectorcraft_doc::SYMBOL_SIZES).and_then(|m| m.get(name)).cloned().unwrap(); + (size[0].as_f64().unwrap(), size[1].as_f64().unwrap()) +} + +/// A symbol dragged from one document's Symbols panel and released on the canvas after another +/// document with a different symbol of the same name became active places the dragged symbol: it +/// is added under a free name, the other document's symbol is left as it was, the source document +/// is not changed, and one Undo takes back both the symbol and the instance. +#[test] +fn a_symbol_dragged_from_another_document_places_that_documents_symbol() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let source = document_with_symbol(&mut app, "Leaf", 40.0, 20.0); + let ctx = egui::Context::default(); + // While Leaf is held, a document with a Leaf of its own becomes active. + egui::DragAndDrop::set_payload(&ctx, widgets::PanelDrag::Symbol { document: source, name: "Leaf".into() }); + document_with_symbol(&mut app, "Leaf", 10.0, 70.0); + frame(&mut app, &ctx, vec![]); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let undo = app.session.active().unwrap().history.undo.len(); + let at = xf.to_screen(Point::new(250.0, 180.0)); + let up = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }; + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at), up]); + let st = app.session.active().unwrap(); + assert_eq!(st.doc.symbols.iter().map(|s| s.name.as_str()).collect::>(), ["Leaf", "Leaf 2"]); + assert_eq!(st.history.undo.len(), undo + 1, "added and placed as one undo step"); + let placed = st.selection.objects.first().copied().expect("the placed instance is selected"); + let n = st.doc.node(placed).unwrap(); + assert!(matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if symbol == "Leaf 2"), "{:?}", n.kind); + let b = n.geometric_bounds().unwrap(); + assert!((b.width() - 40.0).abs() < 1e-6 && (b.height() - 20.0).abs() < 1e-6, "the dragged symbol's size: {b:?}"); + assert!((b.center() - xf.to_doc(at)).hypot() < 1e-6, "{b:?}"); + assert_eq!(symbol_size(&app, "Leaf"), (10.0, 70.0), "this document's Leaf is unchanged"); + app.run("edit.undo", json!({})).unwrap(); + let st = app.session.active().unwrap(); + assert_eq!(st.doc.symbols.iter().map(|s| s.name.as_str()).collect::>(), ["Leaf"]); + assert!(st.doc.node(placed).is_none()); + assert!(app.session.set_active(0)); + assert_eq!(app.session.active().unwrap().uid, source); + assert_eq!(app.session.active().unwrap().doc.symbols.len(), 1, "the source document is unchanged"); + assert_eq!(symbol_size(&app, "Leaf"), (40.0, 20.0)); +} + +/// A symbol dragged from a document that was closed before the release places nothing, even +/// where the active document has a symbol of the same name. +#[test] +fn a_symbol_whose_document_closed_places_nothing() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let source = document_with_symbol(&mut app, "Leaf", 40.0, 20.0); + document_with_symbol(&mut app, "Leaf", 10.0, 70.0); + app.session.execute("file.close", &json!({"index": 0})).unwrap(); + assert!(app.session.documents().iter().all(|d| d.uid != source)); + let ctx = egui::Context::default(); + egui::DragAndDrop::set_payload(&ctx, widgets::PanelDrag::Symbol { document: source, name: "Leaf".into() }); + frame(&mut app, &ctx, vec![]); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let undo = app.session.active().unwrap().history.undo.len(); + let at = xf.to_screen(Point::new(250.0, 180.0)); + let up = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }; + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at), up]); + let st = app.session.active().unwrap(); + assert_eq!(st.history.undo.len(), undo, "no edit"); + assert!(st.selection.objects.is_empty(), "nothing placed"); +} + +/// The chip at the pointer shows the dragged symbol from the document it was dragged from after +/// another document, without a symbol of that name, became active. +#[test] +fn the_pointer_chip_of_a_dragged_symbol_shows_its_own_documents_symbol() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let source = document_with_symbol(&mut app, "Leaf", 40.0, 20.0); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let ctx = egui::Context::default(); + egui::DragAndDrop::set_payload(&ctx, widgets::PanelDrag::Symbol { document: source, name: "Leaf".into() }); + let screen_rect = Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0))); + let run = |events| { + let mut out = + ctx.run_ui(egui::RawInput { screen_rect, events, ..Default::default() }, |ui| crate::panels::swatches::drag_preview(&app, ui.ctx())); + out.textures_delta.clear(); + out + }; + // The chip's area is drawn from its second frame. + run(vec![egui::Event::PointerMoved(pos2(200.0, 150.0))]); + let out = run(vec![]); + let thumbnail = out.shapes.iter().any(|c| matches!(&c.shape, Shape::Mesh(m) if m.texture_id != egui::TextureId::default())); + assert!(thumbnail, "the chip draws the source document's thumbnail of Leaf"); +} + #[test] fn a_library_symbol_dropped_on_the_canvas_is_added_and_placed_there_in_one_step() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); diff --git a/crates/ui-egui/src/chrome/control_bar.rs b/crates/ui-egui/src/chrome/control_bar.rs index 2df5067aa9..2c7ae8ed20 100644 --- a/crates/ui-egui/src/chrome/control_bar.rs +++ b/crates/ui-egui/src/chrome/control_bar.rs @@ -188,9 +188,9 @@ const INLINE_FIELD_WIDTH: f32 = 80.0; /// The keys and labels of the Control bar's inline X/Y/W/H fields, in their order. const INLINE_FIELDS: [(&str, &str); 4] = [("x", "X:"), ("y", "Y:"), ("width", "W:"), ("height", "H:")]; -/// The label of an inline X/Y/W/H field. +/// The label of an inline X/Y/W/H field, underlined: a click on it opens the Transform panel. fn inline_label(t: &Tokens, lbl: &str) -> egui::RichText { - egui::RichText::new(tl!(lbl)).size(12.0).color(t.text_dim) + egui::RichText::new(tl!(lbl)).size(12.0).color(t.text).underline() } /// The room the Control bar's inline X/Y/W/H fields take: their labels as drawn in the current @@ -203,6 +203,53 @@ fn inline_transform_width(ui: &Ui, t: &Tokens) -> f32 { labels + fields + crate::panels::transform::CONSTRAIN_LINK_SIZE + ui.spacing().item_spacing.x * items as f32 } +/// The Control bar's inline X/Y/W/H fields for the selection's box `b`, rotated with rotated +/// objects: X/Y are its reference point on the page (or a symbol instance's registration point), +/// shared with the Transform panel, and W/H its own sides. Edits keep or move that point, and the +/// Transform panel's menu choice of objects, patterns or both applies to them. +fn inline_transform_fields(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens, units: vectorcraft_doc::Unit, b: &vectorcraft_doc::OrientedBox) { + let reference = crate::panels::transform::panel_reference(app, ui, b); + let (refi, rp) = (reference.index, reference.point); + let origin = app.ruler_origin(); + let link = crate::panels::transform::proportional(app, ui); + let copy = crate::panels::transform::alt_enter_copies(app, ui); + let values = [(rp.x, origin.x), (rp.y, origin.y), (b.rect.width(), 0.0), (b.rect.height(), 0.0)]; + // The W/H link sits between W and H, but is made after H so Tab goes from W + // straight to H and finds the link after it. + let mut link_room = None; + let mut labels = Vec::with_capacity(INLINE_FIELDS.len()); + for ((k, lbl), (v, offset)) in INLINE_FIELDS.into_iter().zip(values) { + if k == "height" { + link_room = Some(crate::panels::transform::constrain_link_room(ui)); + } + // A click on the label opens the Transform panel, as the Transform link does; a drag scrubs. + let label = widgets::field_panel_label(ui, inline_label(t, lbl)).on_hover_text(tl!("Transform options")); + let (id, shown) = (("cb", k), Some(v - offset)); + let set = if matches!(k, "width" | "height") { + widgets::size_field(ui, id, shown, units, INLINE_FIELD_WIDTH) + } else { + widgets::num_field(ui, id, shown, units, INLINE_FIELD_WIDTH) + }; + labels.push(label); + if let Some(nv) = set { + let params = match k { + "x" => json!({"x": reference.bounds_xy(nv + offset, 0.0).0, "reference": refi, "copy": copy}), + "y" => json!({"y": reference.bounds_xy(0.0, nv + offset).1, "reference": refi, "copy": copy}), + _ => json!({k: nv, "reference": refi, "proportional": link, "copy": copy}), + }; + crate::panels::transform::run_transform(app, "object.setBounds", params); + } + } + if let Some(room) = link_room { + let id = ui.scope_id().with("cb-constrain-link"); + crate::panels::transform::constrain_link_at(app, ui, ui.interact(room, id, Sense::click())); + } + // After the fields, which each take the label before them as their own. + for label in &labels { + crate::panels::transform::popover(app, label); + } +} + /// The size of the Control bar's Align, Distribute and area type vertical alignment buttons, and /// the height of its Align To menu. const BUTTON: f32 = 24.0; @@ -710,7 +757,7 @@ fn fill_and_stroke(app: &mut VectorcraftApp, ui: &mut Ui, reserve: f32) { stroke_panel::weight_field(app, ui, "cb-stroke", weight, WEIGHT_FIELD_WIDTH); if ui.available_width() < row_width(ui, &[stroke_panel::PROFILE_DROPDOWN_WIDTH]) + reserve { left_out(ui); - } else if let Some(id) = stroke_panel::profile_dropdown(app, ui, shown_stroke.as_ref().and_then(|s| s.profile.as_ref())) { + } else if let Some(id) = stroke_panel::profile_dropdown(app, ui, shown_stroke.as_ref()) { app.run("stroke.set", json!({"profile": id})).ok(); } } else { @@ -1036,38 +1083,11 @@ fn contents(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens, bar: egui::Rect, return; } crate::panels::transform::link(app, ui); - // The bounding box, rotated with rotated objects: its centre and its own sides. let selection_box = app.selection_box(); if selection_box.is_some() && ui.available_width() < inline_transform_width(ui, t) { left_out(ui); } else if let Some(b) = selection_box { - let c = b.center(); - let origin = app.ruler_origin(); - let link = crate::panels::transform::proportional(app, ui); - let copy = crate::panels::transform::alt_enter_copies(app, ui); - let values = [(c.x, origin.x), (c.y, origin.y), (b.rect.width(), 0.0), (b.rect.height(), 0.0)]; - // The W/H link sits between W and H, but is made after H so Tab goes from W - // straight to H and finds the link after it. - let mut link_room = None; - for ((k, lbl), (v, offset)) in INLINE_FIELDS.into_iter().zip(values) { - if k == "height" { - link_room = Some(crate::panels::transform::constrain_link_room(ui)); - } - widgets::field_label(ui, inline_label(t, lbl)); - let (id, shown) = (("cb", k), Some(v - offset)); - let set = if matches!(k, "width" | "height") { - widgets::size_field(ui, id, shown, units, INLINE_FIELD_WIDTH) - } else { - widgets::num_field(ui, id, shown, units, INLINE_FIELD_WIDTH) - }; - if let Some(nv) = set { - app.run("object.setBounds", json!({k: nv + offset, "reference": 4, "proportional": link, "copy": copy})).ok(); - } - } - if let Some(room) = link_room { - let id = ui.scope_id().with("cb-constrain-link"); - crate::panels::transform::constrain_link_at(app, ui, ui.interact(room, id, Sense::click())); - } + inline_transform_fields(app, ui, t, units, &b); } // Select Similar Objects comes last: it takes only the room every control ahead of it left. trailing_select_similar(app, ui); diff --git a/crates/ui-egui/src/chrome/tabs.rs b/crates/ui-egui/src/chrome/tabs.rs index 9278b8baf3..f88372e75b 100644 --- a/crates/ui-egui/src/chrome/tabs.rs +++ b/crates/ui-egui/src/chrome/tabs.rs @@ -364,8 +364,10 @@ pub fn isolation_bar(app: &mut VectorcraftApp, ui: &mut Ui, area: egui::Rect) { ui.painter().rect_filled(crumb_rect, 3.0, t.hover); } if resp.clicked() { - if crumb.is_layer { - nav_cmd = Some(("object.exitIsolation", json!({}))); + // The top-level layer's crumb leaves isolation mode; a sublayer's or a group's + // crumb isolates that level. + if crumb.is_layer && i == 0 { + nav_cmd = Some(("object.exitIsolation", json!({ "all": true }))); } else if let Some(target) = crumb.id { nav_cmd = Some(("object.isolate", json!({ "id": target.0 }))); } @@ -401,7 +403,8 @@ pub fn isolation_bar(app: &mut VectorcraftApp, ui: &mut Ui, area: egui::Rect) { if bresp.clicked() { pattern_cmd = pattern_cmd.or(pattern_edit.as_ref().map(|_| "object.pattern.done")); if pattern_cmd.is_none() { - // Up one level: the isolated object's parent, or out of isolation mode from a layer. + // Up one level: the isolated object's parent group, or `object.exitIsolation`, which + // goes from an isolated sublayer to its parent layer and otherwise leaves isolation mode. nav_cmd = Some(match ancestry.iter().rev().nth(1).filter(|p| st.doc.node(**p).is_some_and(|n| !n.is_layer())) { Some(parent) => ("object.isolate", json!({ "id": parent.0 })), None => ("object.exitIsolation", json!({})), diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 03c7347704..09d31f1a5f 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -1916,6 +1916,45 @@ fn isolation_bar_navigation_and_back_button_steps_up() { assert_eq!(app.session.active().unwrap().isolation, Some(NodeId(g2))); } +/// With a sublayer isolated, the back arrow goes up one layer at a time and then leaves isolation +/// mode. The top-level layer's crumb leaves isolation mode from any depth, and a parent sublayer's +/// crumb isolates that sublayer. +#[test] +fn isolation_bar_back_button_steps_up_through_sublayers() { + use vectorcraft_doc::NodeId; + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); + let top = app.session.active().unwrap().doc.layers[0].id; + let mid = NodeId(app.run("layer.newSublayer", json!({"parent": top.0, "name": "Sublayer B"})).unwrap()["id"].as_u64().unwrap()); + let deep = NodeId(app.run("layer.newSublayer", json!({"parent": mid.0, "name": "Sublayer C"})).unwrap()["id"].as_u64().unwrap()); + app.run("layer.setCurrent", json!({"id": deep.0})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap(); + let ctx = isolation_bar_context(); + let click = |app: &mut crate::VectorcraftApp, pos: egui::Pos2| isolation_bar_gesture(app, &ctx, pos, pos); + let back = egui::pos2(15.0, 12.0); + let isolation = |app: &crate::VectorcraftApp| app.session.active().unwrap().isolation; + + app.run("object.isolate", json!({"id": deep.0})).unwrap(); + let steps = app.session.doc().unwrap().history.undo.len(); + click(&mut app, back); + assert_eq!(isolation(&app), Some(mid), "back from the deepest sublayer"); + click(&mut app, back); + assert_eq!(isolation(&app), Some(top), "back from the middle sublayer"); + click(&mut app, back); + assert_eq!(isolation(&app), None, "back from the top-level layer"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), steps, "no undo step"); + + // "Layer 1" is the first crumb, at x 30 to about 75. + app.run("object.isolate", json!({"id": deep.0})).unwrap(); + click(&mut app, egui::pos2(40.0, 12.0)); + assert_eq!(isolation(&app), None, "the top-level layer's crumb"); + + // "Sublayer B" is the second crumb, from about x 95. + app.run("object.isolate", json!({"id": deep.0})).unwrap(); + click(&mut app, egui::pos2(115.0, 12.0)); + assert_eq!(isolation(&app), Some(mid), "the parent sublayer's crumb"); +} + /// Headless frames of the isolation bar over a 1200 × 700 canvas for one pointer gesture: a press /// at `from`, a move to `to` and a release there. `from == to` is a click. fn isolation_bar_gesture(app: &mut crate::VectorcraftApp, ctx: &egui::Context, from: egui::Pos2, to: egui::Pos2) { @@ -4653,3 +4692,59 @@ fn the_control_bar_shows_the_inline_transform_fields_only_when_they_fit() { assert!(groups_seen.iter().all(|s| *s), "{count} objects: a wide bar shows every group: {groups_seen:?}"); } } + +/// A click on the Control bar's X:, Y:, W: or H: label opens the Transform panel in a popover under +/// it, as the Transform link does, and a second click closes it. The click leaves the selection and +/// its bounds as they were, and no field takes the keyboard. A drag on W: still scrubs the width and +/// opens nothing. +#[test] +fn the_control_bars_x_y_w_and_h_labels_open_the_transform_panel() { + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 40, "height": 30})).unwrap()["id"].clone(); + app.run("select.set", json!({ "ids": [id] })).unwrap(); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(2000.0, 600.0)); + let frame = |app: &mut crate::VectorcraftApp, events| control_bar_frame_in(app, &ctx, screen, events); + let state = |app: &crate::VectorcraftApp| { + let st = app.session.active().unwrap(); + let b = st.doc.bounds_of(&st.selection.objects, false).unwrap(); + (st.selection.objects.len(), [b.x0, b.y0, b.x1, b.y1]) + }; + // The label's own node: a label whose text is `name` (the field it names is named the same). + let label = |nodes: &[egui::accesskit::Node], name: &str| { + let n = nodes.iter().find(|n| n.role() == egui::accesskit::Role::Label && n.value() == Some(name)); + let b = n.and_then(|n| n.bounds()).unwrap_or_else(|| panic!("no {name} label")); + egui::pos2(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32) + }; + // The Transform panel's Rotate field is not on the bar itself. + let open = |nodes: &[egui::accesskit::Node]| nodes.iter().any(|n| n.label() == Some("Rotate")); + let before = state(&app); + frame(&mut app, vec![]); + for name in ["X:", "Y:", "W:", "H:"] { + let nodes = frame(&mut app, vec![]); + assert!(!open(&nodes), "{name}: the Transform panel is closed at first"); + let at = label(&nodes, name); + frame(&mut app, vec![egui::Event::PointerMoved(at), press_at(at, true)]); + frame(&mut app, vec![press_at(at, false)]); + assert!(open(&frame(&mut app, vec![])), "{name}: a click on the label opens the Transform panel"); + assert_eq!(ctx.memory(|m| m.focused()), None, "{name}: no field took the keyboard"); + assert_eq!(state(&app), before, "{name}: the selection and its bounds stay"); + frame(&mut app, vec![egui::Event::PointerMoved(at), press_at(at, true)]); + frame(&mut app, vec![press_at(at, false)]); + assert!(!open(&frame(&mut app, vec![])), "{name}: a second click closes it"); + } + let at = label(&frame(&mut app, vec![]), "W:"); + frame(&mut app, vec![egui::Event::PointerMoved(at), press_at(at, true)]); + for i in 1..=4 { + frame(&mut app, vec![egui::Event::PointerMoved(at + egui::vec2(5.0 * i as f32, 0.0))]); + } + frame(&mut app, vec![press_at(at + egui::vec2(20.0, 0.0), false)]); + let nodes = frame(&mut app, vec![]); + assert!(!open(&nodes), "a drag on W: opens nothing"); + let (_, [x0, _, x1, _]) = state(&app); + assert!(x1 - x0 > before.1[2] - before.1[0], "a drag on W: scrubs the width: {:?} to {:?}", before.1, [x0, x1]); +} diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 17882382c0..da5b93a7bb 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, @@ -600,7 +601,8 @@ pub fn accepts_field(d: &Dialog, field: &str) -> bool { /// Options setting set this way for several rows is sent to every row (Template also sets Lock /// and Dim Images, as its checkbox does). A DXF Options preset set this way sets its fields, as /// one picked from its menu does, and the preset it shows follows the DXF options set this way. -/// A Graph Data Column Width set this way sets every column, as Cell Style's does. +/// A Graph Data Column Width set this way sets every column, as Cell Style's does. An Import PDF +/// `allPages` set this way to the other pick sets Import PDF pages as links back to its default. pub fn set_field(d: &mut Dialog, field: String, value: Value) { if d.kind == brush_options::KIND { brush_art_options::note_set(d, &field); @@ -611,6 +613,9 @@ pub fn set_field(d: &mut Dialog, field: String, value: Value) { if d.kind == layer_options::KIND { layer_options::note_set(d, &field, &value); } + if d.kind == import_pdf::KIND { + import_pdf::note_set(d, &field, &value); + } if d.kind == "preferences" { crate::prefs_dialog::note_set(d, &field, &value); } @@ -649,6 +654,16 @@ fn run_and_close(app: &mut VectorcraftApp, id: &str, params: Value) -> DialogRes r } +/// Set a tool's options with `tool.setOption` (`params`) and close the dialog; when the tool +/// refuses one of them, nothing is set and the dialog stays open. +fn set_tool_options_and_close(app: &mut VectorcraftApp, params: Value) -> DialogResult { + let r = app.run("tool.setOption", params); + if r.is_ok() { + app.ui.dialog = None; + } + r +} + /// The field of a dialog opened over another (Import Shortcut Set over Keyboard Shortcuts) that /// holds the dialog under it, which Cancel and Escape show again. pub(crate) const PARENT: &str = "__parent"; @@ -832,6 +847,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); } @@ -874,14 +893,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() { @@ -1015,6 +1036,8 @@ mod tests_plugin_import; #[cfg(test)] mod tests_raster_formats; #[cfg(test)] +mod tests_raster_supplied_options; +#[cfg(test)] mod tests_svg_options_range; #[cfg(test)] @@ -1060,6 +1083,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 bb3a5633ed..758832cd92 100644 --- a/crates/ui-egui/src/dialogs/color_picker.rs +++ b/crates/ui-egui/src/dialogs/color_picker.rs @@ -293,6 +293,19 @@ pub(super) fn over_effect(parent: &Dialog, field: &str, colour: Color) -> Dialog ); d.fields.insert(super::PARENT.into(), serde_json::to_value(parent).unwrap_or_default()); store(&mut d, &Picked::of(colour)); + d.fields.insert(crate::screen_color::PICKER_ID.into(), json!(crate::screen_color::picker_id())); + d +} + +/// The entry of the dialog's color list that a Color Picker opened with [`over_list_entry`] sets. +const COLOUR_INDEX: &str = "__colourIndex"; + +/// The Color Picker over the dialog `parent`, on `colour`, that sets entry `index` of the dialog's +/// list of colors `field` (Document Setup's `gridColors`) with its OK and goes back to it, leaving +/// the other entries as they are. Cancel goes back to `parent` as it was. It previews nothing. +pub(super) fn over_list_entry(parent: &Dialog, field: &str, index: usize, colour: Color) -> Dialog { + let mut d = over_effect(parent, field, colour); + d.fields.insert(COLOUR_INDEX.into(), json!(index)); d } @@ -371,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 }; @@ -749,7 +763,20 @@ fn swatch_list(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, current: &Colo fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { if let Some(field) = d.fields.get(COLOUR_FIELD).and_then(Value::as_str) { let mut parent = super::parent(d).ok_or("the dialog it was opened over is no longer open")?; - parent.fields.insert(field.to_string(), json!(picked(d).color.to_hex())); + let hex = json!(picked(d).color.to_hex()); + match d.fields.get(COLOUR_INDEX) { + None => { + parent.fields.insert(field.to_string(), hex); + } + Some(index) => { + let entry = index + .as_u64() + .and_then(|i| usize::try_from(i).ok()) + .and_then(|i| parent.fields.get_mut(field)?.as_array_mut()?.get_mut(i)) + .ok_or("no such color")?; + *entry = hex; + } + } // The dialog previews the new colour when it comes back: end this picker's interaction, as // Cancel does, so the dialog starts its preview afresh. let _ = app.session.cancel_interaction(); diff --git a/crates/ui-egui/src/dialogs/color_picker/tests.rs b/crates/ui-egui/src/dialogs/color_picker/tests.rs index 0786df7ca9..15344a131c 100644 --- a/crates/ui-egui/src/dialogs/color_picker/tests.rs +++ b/crates/ui-egui/src/dialogs/color_picker/tests.rs @@ -670,7 +670,8 @@ fn warnings_fit_below_the_preview_without_widening_the_dialog() { } let after = ctx.memory(|m| m.area_rect(id)).unwrap(); assert!((before.size() - after.size()).length() < 1.0, "{before:?} vs {after:?}"); - click_at(&ctx, &mut app, warnings[1].center()); + // The cube icon left of the web correction corrects the color too. + click_at(&ctx, &mut app, warnings[1].center() - vec2(19.0, 0.0)); assert!(is_web_safe(&picked(app.ui.dialog.as_ref().unwrap()).color), "web correction remains clickable"); } 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/document_setup.rs b/crates/ui-egui/src/dialogs/document_setup.rs index 1946cc86b2..187e36e6b0 100644 --- a/crates/ui-egui/src/dialogs/document_setup.rs +++ b/crates/ui-egui/src/dialogs/document_setup.rs @@ -175,17 +175,30 @@ fn general(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool close } +/// The id of the Transparency tab's box that shows grid color `index` (0 or 1). +fn grid_color_box_id(index: usize) -> egui::Id { + egui::Id::unique(("grid-color-box", index)) +} + +/// The grid colors' hex codes that Document Setup `d` holds now (empty strings for entries that are +/// not strings). +fn grid_colors(d: &Dialog) -> Vec { + d.fields.get("gridColors").and_then(Value::as_array).map(|a| a.iter().map(|c| c.as_str().unwrap_or("").to_string()).collect()).unwrap_or_default() +} + fn transparency(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { let t = Tokens::get(ui.ctx()); widgets::subheader(ui, tl!("Transparency Grid")); let sizes: Vec<(&str, &str)> = GridSize::ALL.iter().map(|g| (g.id(), g.label())).collect(); choice(ui, d, "gridSize", tl!("Grid Size:"), &sizes); - let colors: Vec = d - .fields - .get("gridColors") - .and_then(Value::as_array) - .map(|a| a.iter().map(|c| c.as_str().unwrap_or("").to_string()).collect()) - .unwrap_or_default(); + // A preset name in the fields (any case, as `document.setup` takes it) becomes the preset's two + // colors, which the hex fields and the Color Picker edit one at a time. + if let Some((_, pair)) = + d.fields.get("gridColors").and_then(Value::as_str).and_then(|n| GRID_COLOR_PRESETS.iter().find(|(p, _)| p.eq_ignore_ascii_case(n))) + { + d.fields.insert("gridColors".into(), json!(pair.map(|c| c.to_hex()))); + } + let colors = grid_colors(d); let preset = GRID_COLOR_PRESETS .iter() .find(|(_, pair)| colors.len() == 2 && colors.iter().zip(pair).all(|(h, c)| h.eq_ignore_ascii_case(&c.to_hex()))) @@ -196,18 +209,40 @@ fn transparency(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { d.fields.insert("gridColors".into(), json!(pair.map(|c| c.to_hex()))); } }); - // The two colours (the first is also the paper colour): editing either makes them Custom. + // The two colours (the first is also the paper colour): editing either makes them Custom. A + // click on a color's box, or Space or Enter with the keyboard on it, opens the Color Picker on + // that color (white when its hex is not a color), and the picker's OK sets that color. The + // picker opens after the row, on the color Document Setup holds then: a press on a box ends a + // hex field's editing in the same frame, and that field's edit is the color the picker opens on. + // A hex field's edit replaces its own color in the pair Document Setup holds when it commits. + let mut pick = None; widgets::label_row(ui, "", LABEL, |ui| { for i in 0..2 { let hex = colors.get(i).map_or("", |h| h.trim_start_matches('#')); + let colour = vectorcraft_color::Color::from_hex(hex); + let name = format!("{} {}", tl!("Grid Colors:"), i + 1); let (chip, _) = ui.allocate_exact_size(egui::vec2(18.0, 18.0), egui::Sense::hover()); - if let Some(c) = vectorcraft_color::Color::from_hex(hex) { + let resp = ui.interact(chip, grid_color_box_id(i), egui::Sense::click()); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &name)); + let keyed = resp.has_focus() + && ui.input_mut(|inp| { + inp.consume_key(egui::Modifiers::NONE, egui::Key::Space) | inp.consume_key(egui::Modifiers::NONE, egui::Key::Enter) + }); + if resp.clicked() || keyed { + pick = Some(i); + } + if resp.hovered() { + ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand); + } + if let Some(c) = colour { ui.painter().rect_filled(chip, 2.0, crate::panels::c32(&c)); } ui.painter().rect_stroke(chip, 2.0, egui::Stroke::new(1.0, t.input_border), egui::StrokeKind::Inside); - let name = format!("{} {}", tl!("Grid Colors:"), i + 1); + if resp.has_focus() { + ui.painter().rect_stroke(chip.expand(2.0), 3.0, ui.visuals().selection.stroke, egui::StrokeKind::Outside); + } if let Some(c) = widgets::hex_field_named(ui, ("grid-color", i), Some(&name), hex).and_then(|h| vectorcraft_color::Color::from_hex(&h)) { - let mut v = colors.clone(); + let mut v = grid_colors(d); v.resize(2, "#ffffff".into()); v[i] = c.to_hex(); d.fields.insert("gridColors".into(), json!(v)); @@ -215,6 +250,10 @@ fn transparency(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { ui.add_space(10.0); } }); + if let Some(i) = pick { + let c = grid_colors(d).get(i).and_then(|h| vectorcraft_color::Color::from_hex(h.trim_start_matches('#'))); + *d = super::color_picker::over_list_entry(d, "gridColors", i, c.unwrap_or(vectorcraft_color::Color::WHITE)); + } ui.add_space(4.0); check(ui, d, "simulatePaper", tl!("Simulate Colored Paper")); ui.add_space(14.0); @@ -635,4 +674,242 @@ mod tests { assert_eq!(fill(&app, id), before); assert_eq!(undo_steps(&app), steps); } + + /// The Light pair a new document's transparency grid starts with. + const LIGHT: [&str; 2] = ["#ffffff", "#cccccc"]; + + fn hex(h: &str) -> Color { + Color::from_hex(h).unwrap_or_else(|| panic!("bad hex {h}")) + } + + /// The grid colors Document Setup `d` holds. + fn dialog_grid(d: &crate::state::Dialog) -> Vec { + d.fields["gridColors"].as_array().unwrap().iter().map(|c| hex(c.as_str().unwrap())).collect() + } + + /// A new document with Document Setup open on its Transparency tab, drawn in the context returned. + fn transparency_tab() -> (VectorcraftApp, egui::Context) { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("file.documentSetup", json!({})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("tab".into(), json!("Transparency")); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + crate::theme::apply(&ctx, Default::default()); + for _ in 0..4 { + dialog_frame(&mut app, &ctx, vec![]); + } + (app, ctx) + } + + /// Clicks the box of grid color `index`. + fn click_grid_box(app: &mut VectorcraftApp, ctx: &egui::Context, index: usize) { + let at = ctx.read_response(super::grid_color_box_id(index)).unwrap_or_else(|| panic!("no box {index}")).rect.center(); + let button = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + dialog_frame(app, ctx, vec![Event::PointerMoved(at), button(true)]); + dialog_frame(app, ctx, vec![button(false)]); + } + + /// The Color Picker is open over Document Setup, on `color`, and Document Setup's OK has not run. + fn assert_picker_over_setup(app: &VectorcraftApp, color: &str, case: &str) { + let d = app.ui.dialog.as_ref().unwrap_or_else(|| panic!("{case}: no dialog")); + assert_eq!(d.kind, "colorPicker", "{case}"); + assert_eq!(d.fields.get("color").and_then(vectorcraft_engine::cmd::color_value), Some(hex(color)), "{case}"); + assert_eq!(crate::dialogs::parent(d).map(|p| p.kind), Some(super::KIND.to_string()), "{case}"); + assert_eq!(undo_steps(app), 0, "{case}: Document Setup's OK has not run"); + } + + /// A click on either grid color's box opens the Color Picker over Document Setup on that + /// color. Its OK sets only that color, the Grid Colors menu names the pair (Custom, or the + /// preset it matches), and Document Setup's OK applies the pair in one undo step. + #[test] + fn a_grid_color_box_opens_the_color_picker_and_its_ok_sets_that_color() { + for (index, picked, pair, name) in [(0, "#00ff00", ["#00ff00", "#cccccc"], "Custom"), (1, "#c4dcff", ["#ffffff", "#c4dcff"], "Blue")] { + let (mut app, ctx) = transparency_tab(); + click_grid_box(&mut app, &ctx, index); + assert_picker_over_setup(&app, LIGHT[index], name); + app.ui.dialog.as_mut().unwrap().fields.insert("color".into(), json!(picked)); + crate::dialogs::confirm(&mut app).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.kind.as_str(), dialog_grid(d)), (super::KIND, pair.map(hex).to_vec()), "{name}"); + assert_eq!(undo_steps(&app), 0, "{name}: the picker's OK leaves the document as it is"); + dialog_frame(&mut app, &ctx, vec![]); + let texts: Vec = dialog_frame(&mut app, &ctx, vec![]).into_iter().map(|(t, _)| t).collect(); + assert!(texts.iter().any(|t| t == name), "{name}: {texts:?}"); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + let st = app.session.active().unwrap(); + assert_eq!((st.doc.setup.grid_colors, st.doc.setup.grid_colors_name()), (pair.map(hex), name)); + assert_eq!(undo_steps(&app), 1, "{name}"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().doc.setup.grid_colors, LIGHT.map(hex), "{name}"); + } + } + + /// With the keyboard on a grid color's box, Enter or Space opens the Color Picker on that + /// color instead of pressing Document Setup's OK. + #[test] + fn enter_or_space_on_a_grid_color_box_opens_the_color_picker() { + for (index, key) in [(0, egui::Key::Enter), (1, egui::Key::Space)] { + let (mut app, ctx) = transparency_tab(); + ctx.memory_mut(|m| m.request_focus(super::grid_color_box_id(index))); + dialog_frame(&mut app, &ctx, vec![]); + let press = Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; + dialog_frame(&mut app, &ctx, vec![press]); + assert_picker_over_setup(&app, LIGHT[index], &format!("{key:?}")); + } + } + + /// Cancel in the Color Picker goes back to Document Setup with the grid colors as they were, + /// and so does its OK on the color it opened on; Document Setup's OK then records no undo step. + #[test] + fn grid_color_picker_cancel_or_an_unchanged_ok_changes_nothing() { + for cancel in [true, false] { + let (mut app, ctx) = transparency_tab(); + click_grid_box(&mut app, &ctx, 1); + assert_picker_over_setup(&app, LIGHT[1], &format!("cancel {cancel}")); + if cancel { + app.ui.dialog.as_mut().unwrap().fields.insert("color".into(), json!("#ff0000")); + crate::dialogs::cancel(&mut app); + } else { + crate::dialogs::confirm(&mut app).unwrap(); + } + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.kind.as_str(), dialog_grid(d)), (super::KIND, LIGHT.map(hex).to_vec()), "cancel {cancel}"); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.active().unwrap().doc.setup.grid_colors_name(), "Light"); + assert_eq!(undo_steps(&app), 0, "cancel {cancel}"); + } + } + + /// With a preset name in Document Setup's `gridColors` field, the grid color boxes show the + /// preset's colors, and the Color Picker opens on the clicked one; its OK sets that color and + /// keeps the preset's other one. + #[test] + fn a_grid_color_box_opens_the_picker_when_the_field_names_a_preset() { + let (mut app, ctx) = transparency_tab(); + app.ui.dialog.as_mut().unwrap().fields.insert("gridColors".into(), json!("blue")); + dialog_frame(&mut app, &ctx, vec![]); + click_grid_box(&mut app, &ctx, 1); + assert_picker_over_setup(&app, "#c4dcff", "blue"); + app.ui.dialog.as_mut().unwrap().fields.insert("color".into(), json!("#00ff00")); + crate::dialogs::confirm(&mut app).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.kind.as_str(), dialog_grid(d)), (super::KIND, ["#ffffff", "#00ff00"].map(hex).to_vec())); + } + + /// The screen color sampler works in the Color Picker of a grid color: the color sampled goes + /// to that picker, and its OK sets the grid color. + #[test] + fn the_grid_color_picker_takes_a_screen_sampled_color() { + let (mut app, ctx) = transparency_tab(); + let (tx, rx) = std::sync::mpsc::channel::(); + let mut rx = Some(rx); + app.services.screen_color = Some(Box::new(move || rx.take().ok_or_else(|| "shown twice".to_string()))); + click_grid_box(&mut app, &ctx, 0); + assert_picker_over_setup(&app, LIGHT[0], "before sampling"); + app.run("ui.sampleScreenColor", json!({"picker": true})).unwrap(); + tx.send(Ok(Some([0.0, 0.5, 1.0]))).unwrap(); + crate::screen_color::poll(&mut app, &ctx); + let sampled = app.ui.dialog.as_ref().unwrap().fields.get("color").and_then(vectorcraft_engine::cmd::color_value).unwrap(); + assert_ne!(sampled.to_hex(), LIGHT[0]); + crate::dialogs::confirm(&mut app).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + let grid: Vec = dialog_grid(d).iter().map(Color::to_hex).collect(); + assert_eq!((d.kind.as_str(), grid), (super::KIND, vec![sampled.to_hex(), LIGHT[1].to_string()])); + } + + /// Clicks the hex field that shows `digits` and types `typed` over its text, leaving the edit + /// pending; returns the field's id. + fn type_into_hex_field(app: &mut VectorcraftApp, ctx: &egui::Context, digits: &str, typed: &str) -> egui::Id { + let texts = dialog_frame(app, ctx, vec![]); + let at = texts.iter().find(|(t, _)| t == digits).unwrap_or_else(|| panic!("no field {digits}: {texts:?}")).1.center(); + let button = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + dialog_frame(app, ctx, vec![Event::PointerMoved(at), button(true)]); + dialog_frame(app, ctx, vec![button(false)]); + let field = ctx.memory(|m| m.focused()).unwrap_or_else(|| panic!("field {digits} has no focus")); + dialog_frame(app, ctx, vec![Event::Text(typed.into())]); + assert_eq!(ctx.memory(|m| m.focused()), Some(field), "the edit in {digits} is pending"); + field + } + + /// A click on a grid color's box whose press and release come in one frame, while that + /// color's hex field holds an edit, opens the Color Picker on the edited color: the press + /// commits the edit before the picker opens. The picker's unchanged OK keeps the edit, and the + /// other color stays as it was. + #[test] + fn a_grid_color_box_clicked_during_a_hex_edit_opens_the_picker_on_the_edit() { + for index in [0, 1] { + let (mut app, ctx) = transparency_tab(); + type_into_hex_field(&mut app, &ctx, LIGHT[index].trim_start_matches('#'), "123456"); + let at = ctx.read_response(super::grid_color_box_id(index)).unwrap_or_else(|| panic!("no box {index}")).rect.center(); + let button = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + dialog_frame(&mut app, &ctx, vec![Event::PointerMoved(at), button(true), button(false)]); + let case = format!("box {index}"); + assert_picker_over_setup(&app, "#123456", &case); + let mut pair = LIGHT; + pair[index] = "#123456"; + assert_eq!(dialog_grid(&crate::dialogs::parent(app.ui.dialog.as_ref().unwrap()).unwrap()), pair.map(hex).to_vec(), "{case}"); + crate::dialogs::confirm(&mut app).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.kind.as_str(), dialog_grid(d)), (super::KIND, pair.map(hex).to_vec()), "{case}"); + } + } + + /// A hex field's edit that commits in the frame a Grid Colors preset is chosen replaces only + /// its own color in the preset's pair: the other color is the preset's. The test gives the + /// field the focus while the Grid Colors menu is open, then chooses a preset with a click whose + /// press and release come in one frame. + #[test] + fn a_hex_edit_committed_with_a_preset_choice_keeps_the_presets_other_color() { + let field = { + let (mut app, ctx) = transparency_tab(); + type_into_hex_field(&mut app, &ctx, "ffffff", "123456") + }; + let (mut app, ctx) = transparency_tab(); + let click = |app: &mut VectorcraftApp, label: &str, frames: usize| { + let texts = dialog_frame(app, &ctx, vec![]); + let at = texts.iter().find(|(t, _)| t == label).unwrap_or_else(|| panic!("no {label}: {texts:?}")).1.center(); + let button = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + if frames == 1 { + dialog_frame(app, &ctx, vec![Event::PointerMoved(at), button(true), button(false)]); + } else { + dialog_frame(app, &ctx, vec![Event::PointerMoved(at), button(true)]); + dialog_frame(app, &ctx, vec![button(false)]); + } + }; + click(&mut app, "Light", 2); + ctx.memory_mut(|m| m.request_focus(field)); + dialog_frame(&mut app, &ctx, vec![]); + let select_all = Event::Key { key: egui::Key::A, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::COMMAND }; + dialog_frame(&mut app, &ctx, vec![select_all, Event::Text("123456".into())]); + assert_eq!(ctx.memory(|m| m.focused()), Some(field), "the edit is pending"); + let texts: Vec = dialog_frame(&mut app, &ctx, vec![]).into_iter().map(|(t, _)| t).collect(); + assert!(texts.iter().any(|t| t == "123456") && texts.iter().any(|t| t == "Blue"), "{texts:?}"); + click(&mut app, "Blue", 1); + assert_eq!(dialog_grid(app.ui.dialog.as_ref().unwrap()), ["#123456", "#c4dcff"].map(hex).to_vec()); + } + + /// The picker's OK sets nothing when the dialog under it has no such color or is gone: it is + /// an error, and the picker stays open. + #[test] + fn grid_color_picker_without_its_color_or_its_dialog_is_an_error() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("file.documentSetup", json!({})).unwrap(); + let setup = app.ui.dialog.clone().unwrap(); + let mut short = setup.clone(); + short.fields.insert("gridColors".into(), json!(["#ffffff"])); + let mut orphan = crate::dialogs::color_picker::over_list_entry(&setup, "gridColors", 0, Color::WHITE); + orphan.fields.remove(crate::dialogs::PARENT); + for picker in [crate::dialogs::color_picker::over_list_entry(&short, "gridColors", 1, Color::WHITE), orphan] { + app.ui.dialog = Some(picker); + app.ui.dialog.as_mut().unwrap().fields.insert("color".into(), json!("#ff0000")); + assert!(crate::dialogs::confirm(&mut app).is_err()); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some("colorPicker")); + } + assert_eq!(app.session.active().unwrap().doc.setup.grid_colors, LIGHT.map(hex)); + assert_eq!(undo_steps(&app), 0); + } } diff --git a/crates/ui-egui/src/dialogs/flare_options.rs b/crates/ui-egui/src/dialogs/flare_options.rs index 9c374f3cf5..5b6834d46e 100644 --- a/crates/ui-egui/src/dialogs/flare_options.rs +++ b/crates/ui-egui/src/dialogs/flare_options.rs @@ -16,7 +16,7 @@ use vectorcraft_geom::Point; use vectorcraft_tools::extra::{FLARE_OPTIONS, flare_params}; use super::document_setup::check; -use super::{DialogResult, DialogSpec, form, run_and_close}; +use super::{DialogResult, DialogSpec, form, set_tool_options_and_close}; use crate::state::Dialog; use crate::{VectorcraftApp, widgets}; @@ -155,12 +155,14 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { values.insert(key.into(), json!(d.bool(key))); } if let Some((cmd, params)) = command { + // Options the tool would refuse leave the dialog open, before the flare is accepted. + vectorcraft_tools::option_check::check_values(vectorcraft_tools::create("flare").as_ref(), &values)?; // Accept the preview once; option persistence follows successful artwork creation. let result = form::commit_preview(app, &cmd, params)?; app.run("tool.setOption", json!({ "tool": "flare", "values": values }))?; Ok(result) } else { - run_and_close(app, "tool.setOption", json!({ "tool": "flare", "values": values })) + set_tool_options_and_close(app, json!({ "tool": "flare", "values": values })) } } @@ -312,10 +314,11 @@ mod tests { super::super::confirm(&mut app).unwrap(); let parts = flare_parts(&app); assert_eq!(parts.iter().filter(|p| *p == "Ring").count(), 3, "{parts:?}"); - // Out-of-range values are kept within the option's range. - app.run("tool.setOption", json!({"tool": "flare", "values": {"opacity": 900, "diameter": -4}})).unwrap(); - let o = app.session.tool_options_of("flare"); - assert_eq!((o["opacity"].as_f64(), o["diameter"].as_f64()), (Some(100.0), Some(0.0))); + // An out-of-range value is an error, and no option changes. + let before = app.session.tool_options_of("flare"); + let e = app.run("tool.setOption", json!({"tool": "flare", "values": {"opacity": 50, "diameter": -4}})).unwrap_err(); + assert_eq!(e, "tool `flare`: `diameter` must be a number from 0 to 1000"); + assert_eq!(app.session.tool_options_of("flare"), before); } #[test] 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 93e3a1c2ff..78fdd8bdd1 100644 --- a/crates/ui-egui/src/dialogs/freehand.rs +++ b/crates/ui-egui/src/dialogs/freehand.rs @@ -21,7 +21,7 @@ use serde_json::{Map, Value, json}; use vectorcraft_brush::Variation; use super::document_setup::check; -use super::{DialogSpec, form, run_and_close}; +use super::{DialogSpec, form, set_tool_options_and_close}; use crate::state::Dialog; use crate::theme::Tokens; use crate::{VectorcraftApp, widgets}; @@ -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 { @@ -391,7 +469,7 @@ fn blob_tip_short_ratio(roundness: f64) -> f32 { /// OK: set the tool's options. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { let values: Map = KEYS.iter().filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone()))).collect(); - run_and_close(app, "tool.setOption", json!({ "tool": d.str("tool"), "values": values })) + set_tool_options_and_close(app, json!({ "tool": d.str("tool"), "values": values })) } #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/freehand/tests.rs b/crates/ui-egui/src/dialogs/freehand/tests.rs index 3a73d6f3bb..6ec010a8bd 100644 --- a/crates/ui-egui/src/dialogs/freehand/tests.rs +++ b/crates/ui-egui/src/dialogs/freehand/tests.rs @@ -28,6 +28,24 @@ fn blob_tip_fields_confirm_and_cancel() { assert_eq!(app.session.tool_options_of("blobBrush")["roundness"], json!(0.0)); } +/// OK with a Fidelity the Smooth tool refuses shows the error and keeps the dialog open, with +/// nothing set; a Fidelity it takes then closes it. +#[test] +fn a_refused_fidelity_keeps_the_dialog_open() { + let mut app = app(); + app.run("tool.options", json!({"tool": "smooth"})).unwrap(); + let before = app.session.tool_options_of("smooth"); + app.ui.dialog.as_mut().unwrap().fields.insert("fidelity".into(), json!(0.01)); + let e = super::super::confirm(&mut app).unwrap_err(); + assert_eq!(e, "tool `smooth`: `fidelity` must be a number from 0.05 to 100"); + assert!(app.ui.dialog.is_some(), "the dialog stays open"); + assert_eq!(app.session.tool_options_of("smooth"), before); + app.ui.dialog.as_mut().unwrap().fields.insert("fidelity".into(), json!(5)); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.tool_options_of("smooth")["fidelity"], json!(5.0)); +} + #[test] fn the_tip_preview_is_as_flat_as_the_tip_the_brush_draws() { for roundness in [-5.0, 0.0, 0.05, 0.1, 1.0, 50.0, 100.0, 120.0] { @@ -36,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/import_pdf.rs b/crates/ui-egui/src/dialogs/import_pdf.rs index 4ef8c925d8..bedd3387c2 100644 --- a/crates/ui-egui/src/dialogs/import_pdf.rs +++ b/crates/ui-egui/src/dialogs/import_pdf.rs @@ -3,7 +3,10 @@ //! //! Fields: `mode` (`open` | `place`), `name`, `path?`, `pageCount`, `page` (the page shown, and the //! one placed; 1-based), `allPages`, `range` and `linkPages` (open: Import PDF Pages as Links, for -//! a file read from a path and opened without a password), `cropTo` and `password`. `__locked` is set +//! a file read from a path and opened without a password; `null` until it is checked or cleared, +//! when it follows the pages picked: on for All, off for a range; picking the other of All and +//! Range sets it back to `null`; `__linkable` is false for a file `linkPages` does not take, such as +//! one over its size limit), `cropTo` and `password`. `__locked` is set //! until the password is accepted: OK then unlocks the file, and with `__passwordOnly` (Place with //! Show Import Options off) places its first page at once. `__place` keeps the other `file.place` //! params (Link, Template, `at`…). The file's bytes stay out of the fields, in @@ -144,10 +147,11 @@ pub fn offer(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option Option { } /// Can the pages open linked: the file was read from a path (a linked page is read from its -/// file again) and opens without a password (`document.open`'s `linkPages` refuses one). +/// file again), `document.open`'s `linkPages` takes its size, and it opens without a password +/// (`linkPages` refuses one). fn can_link(d: &Dialog) -> bool { - d.fields.get("path").and_then(Value::as_str).is_some() && password(d).is_none() + d.fields.get("path").and_then(Value::as_str).is_some() && d.bool("__linkable") && password(d).is_none() +} + +/// Import PDF Pages as Links as checked or cleared, or, when it is `null`, as the pages picked +/// default it: on for All, off for a range. +fn link_pages(d: &Dialog) -> bool { + d.fields.get("linkPages").and_then(Value::as_bool).unwrap_or_else(|| d.bool("allPages")) } /// Import PDF Pages as Links is checked, and can be. -fn links_on(d: &Dialog) -> bool { - d.bool("linkPages") && can_link(d) +pub(super) fn links_on(d: &Dialog) -> bool { + link_pages(d) && can_link(d) +} + +/// Picks All (true) or Range. A change of pick sets Import PDF Pages as Links back to that pick's +/// default; picking the one already picked keeps the box as it is. +fn pick_all_pages(d: &mut Dialog, all: bool) { + if d.bool("allPages") != all { + d.fields.insert("allPages".into(), json!(all)); + d.fields.insert("linkPages".into(), Value::Null); + } +} + +/// Records that `ui.dialog.set` sets `field` to `value`: a change of `allPages` sets Import PDF +/// Pages as Links back to its default, as a click on All or Range does. +pub(super) fn note_set(d: &mut Dialog, field: &str, value: &Value) { + if field == "allPages" + && let Some(all) = value.as_bool() + { + pick_all_pages(d, all); + } } /// OK: unlock the file with the password, else open the pages or place the page. @@ -330,20 +360,20 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { ui.label(egui::RichText::new(tl!("Pages")).color(t.text)); let all = d.bool("allPages"); if widgets::radio(ui, tl!("All"), all, true) { - d.fields.insert("allPages".into(), json!(true)); + pick_all_pages(d, true); } ui.horizontal(|ui| { if widgets::radio(ui, tl!("Range:"), !all, true) { - d.fields.insert("allPages".into(), json!(false)); + pick_all_pages(d, false); } if super::form::text_edit_named(ui, d, "range", tl!("Range:"), 90.0).gained_focus() { - d.fields.insert("allPages".into(), json!(false)); + pick_all_pages(d, false); } }); widgets::dim_label(ui, tl!("e.g. 1-3, 5")); ui.add_space(10.0); if widgets::check(ui, tl!("Import PDF pages as links"), links_on(d), can_link(d)) { - d.fields.insert("linkPages".into(), json!(!d.bool("linkPages"))); + d.fields.insert("linkPages".into(), json!(!link_pages(d))); } } }); diff --git a/crates/ui-egui/src/dialogs/liquify.rs b/crates/ui-egui/src/dialogs/liquify.rs index 40aa677f17..18b8e48418 100644 --- a/crates/ui-egui/src/dialogs/liquify.rs +++ b/crates/ui-egui/src/dialogs/liquify.rs @@ -12,7 +12,7 @@ use serde_json::{Map, Value, json}; use vectorcraft_tools::distort::liquify::LiquifyKind; use super::document_setup::check; -use super::{DialogSpec, form, run_and_close}; +use super::{DialogSpec, form, set_tool_options_and_close}; use crate::state::Dialog; use crate::theme::Tokens; use crate::{VectorcraftApp, widgets}; @@ -145,7 +145,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { values.insert(key.into(), json!(d.f64(key, 0.0) / 100.0)); } } - run_and_close(app, "tool.setOption", json!({ "tool": kind(d).id(), "values": values })) + set_tool_options_and_close(app, json!({ "tool": kind(d).id(), "values": values })) } #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/live_paint_bucket.rs b/crates/ui-egui/src/dialogs/live_paint_bucket.rs index f515c3d904..11bdcf5c41 100644 --- a/crates/ui-egui/src/dialogs/live_paint_bucket.rs +++ b/crates/ui-egui/src/dialogs/live_paint_bucket.rs @@ -15,7 +15,7 @@ use vectorcraft_doc::LAYER_COLORS; use vectorcraft_tools::builder::LP_BUCKET_WIDTH_RANGE; use super::tile_edge_color::{checked, resolve}; -use super::{DialogSpec, form, run_and_close}; +use super::{DialogSpec, form, set_tool_options_and_close}; use crate::state::Dialog; use crate::{VectorcraftApp, widgets}; @@ -86,7 +86,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { checked(&d.str("color"))?; } let values: Map = KEYS.iter().filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone()))).collect(); - run_and_close(app, "tool.setOption", json!({ "tool": TOOL, "values": values })) + set_tool_options_and_close(app, json!({ "tool": TOOL, "values": values })) } #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/live_paint_selection.rs b/crates/ui-egui/src/dialogs/live_paint_selection.rs index a1a91ad2b7..95584c2f96 100644 --- a/crates/ui-egui/src/dialogs/live_paint_selection.rs +++ b/crates/ui-egui/src/dialogs/live_paint_selection.rs @@ -13,7 +13,7 @@ use vectorcraft_doc::LAYER_COLORS; use vectorcraft_tools::builder::LP_SELECT_WIDTH_RANGE; use super::tile_edge_color::{checked, resolve}; -use super::{DialogSpec, form, run_and_close}; +use super::{DialogSpec, form, set_tool_options_and_close}; use crate::state::Dialog; use crate::{VectorcraftApp, widgets}; @@ -80,7 +80,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { checked(&d.str("color"))?; } let values: Map = KEYS.iter().filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone()))).collect(); - run_and_close(app, "tool.setOption", json!({ "tool": TOOL, "values": values })) + set_tool_options_and_close(app, json!({ "tool": TOOL, "values": values })) } #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/modal.rs b/crates/ui-egui/src/dialogs/modal.rs index f72383068e..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}; @@ -25,6 +26,8 @@ pub(crate) fn show_at(ctx: &egui::Context, title: &str, id: Id, initial: Vec2 // Not focusable (`Sense::click()` is): Tab goes through the dialog's controls, not the backdrop. ui.allocate_rect(ctx.content_rect(), egui::Sense::CLICK); }); + let pass = ctx.cumulative_pass_nr(); + ctx.data_mut(|d| d.insert_temp(drawn_pass_id(), pass)); let shown = egui::Window::new(title) .id(id) .order(egui::Order::Foreground) @@ -33,17 +36,114 @@ 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 { egui::LayerId::new(egui::Order::Middle, Id::unique("modal-dim")) } +/// The key of the pass in which [`show_at`] last drew a modal window. +fn drawn_pass_id() -> Id { + Id::unique("modal-drawn-pass") +} + +/// Whether [`show_at`] drew a modal window in this pass. Unlike the backdrop's visibility, which +/// also counts the last pass, it is false in the pass after the window closes. +pub(crate) fn drawn_this_pass(ctx: &egui::Context) -> bool { + ctx.data(|d| d.get_temp::(drawn_pass_id())) == Some(ctx.cumulative_pass_nr()) +} + /// The dialog's heading, which also moves the window ([`drag_band`]). pub(crate) fn heading(ui: &mut egui::Ui, text: &str) { let t = Tokens::get(ui.ctx()); @@ -73,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(); } } @@ -146,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/new_swatch.rs b/crates/ui-egui/src/dialogs/new_swatch.rs index 5b6c5b117c..ec2ab707d4 100644 --- a/crates/ui-egui/src/dialogs/new_swatch.rs +++ b/crates/ui-egui/src/dialogs/new_swatch.rs @@ -1,5 +1,5 @@ -//! New Swatch: the Swatch Options fields (name, colour type, Global, mode, sliders and hex) -//! prefilled from the active fill or stroke; a gradient, a pattern or a tint of a global colour +//! New Swatch: the Swatch Options fields (name, colour type, Global, mode, sliders, hex and the +//! colour warnings) prefilled from the active fill or stroke; a gradient, a pattern or a tint of a global colour //! (saved as a tint swatch, "Name 40%") only takes a name. OK runs `swatch.new`. //! //! Fields: `name`, `spot`, `global`, `mode` and `color` as in Swatch Options, `group` (the colour @@ -45,7 +45,7 @@ pub fn open(app: &mut VectorcraftApp, spot: bool, global: bool, group: Option<&s fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { if d.fields.contains_key("__paint") { grid(ui, |ui| name_row(ui, d)); - } else if editor(ui, d) + } else if editor(app, ui, d) && d.str("name") == d.str("__auto") && let Some(st) = app.session.active() { @@ -87,6 +87,30 @@ mod tests { assert_eq!(params(&d), json!({"name": "Dots", "pattern": "Dots"})); } + #[test] + fn a_warning_corrects_the_new_colour_only_until_ok() { + use super::super::swatch_options::tests::{click_at, context, settled, warning_rows}; + let (ctx, mut app) = (context(), VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default())); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + app.run("paint.setFill", json!({"color": "#0000fe"})).unwrap(); + let count = |app: &VectorcraftApp| app.session.active().unwrap().doc.swatches_iter().count(); + let before = count(&app); + open(&mut app, false, false, None).unwrap(); + let rows = warning_rows(&settled(&ctx, &mut app)); + assert_eq!(rows.len(), 2, "out of gamut and out of web colors"); + click_at(&ctx, &mut app, rows[1].1.center()); + let d = app.ui.dialog.clone().unwrap(); + assert_eq!((color_of(&d).to_hex(), d.str("mode")), ("#0000ff".to_string(), "rgb".to_string())); + assert_eq!(count(&app), before, "no swatch before OK"); + assert_eq!(warning_rows(&settled(&ctx, &mut app)).len(), 1, "the web warning is gone"); + let name = app.ui.dialog.as_ref().unwrap().str("name"); + super::super::confirm(&mut app).unwrap(); + assert_eq!(app.session.active().unwrap().doc.swatch(&name).and_then(|s| s.paint.color()).map(|c| c.to_hex()), Some("#0000ff".into())); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(count(&app), before, "one undo step"); + } + #[test] fn a_tint_opens_as_a_named_tint_swatch() { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); diff --git a/crates/ui-egui/src/dialogs/objects_on_path_options.rs b/crates/ui-egui/src/dialogs/objects_on_path_options.rs index 4726e0762a..71aff096fb 100644 --- a/crates/ui-egui/src/dialogs/objects_on_path_options.rs +++ b/crates/ui-egui/src/dialogs/objects_on_path_options.rs @@ -11,7 +11,7 @@ use serde_json::{Map, Value, json}; use vectorcraft_doc::objects_on_path::CENTER; -use super::{DialogSpec, run_and_close}; +use super::{DialogSpec, set_tool_options_and_close}; use crate::state::Dialog; use crate::{VectorcraftApp, widgets}; @@ -73,7 +73,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { /// Save: set the tool's Pivot and Rotate. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { let values: Map = ["pivot", "rotate"].iter().filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone()))).collect(); - run_and_close(app, "tool.setOption", json!({ "tool": TOOL, "values": values })) + set_tool_options_and_close(app, json!({ "tool": TOOL, "values": values })) } #[cfg(test)] 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/png_options.rs b/crates/ui-egui/src/dialogs/png_options.rs index 4fc66757ac..ae70d682c4 100644 --- a/crates/ui-egui/src/dialogs/png_options.rs +++ b/crates/ui-egui/src/dialogs/png_options.rs @@ -63,8 +63,13 @@ pub fn open(app: &mut VectorcraftApp, f: &Format, mut params: Value) { false => export_size(&st.doc, ¶ms), }); if let Some(o) = params.as_object_mut() { - o.insert("ppi".into(), json!(72)); - o.extend(defaults(app, f)); + let mut initial = defaults(app, f); + initial.insert("ppi".into(), json!(72)); + for (key, value) in initial { + if o.get(&key).is_none_or(Value::is_null) { + o.insert(key, value); + } + } if let Some((w, h)) = size { o.insert("__size".into(), json!([w, h])); } 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/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index 8efa96d89b..cfa699b7b9 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -1950,7 +1950,7 @@ fn global_sliders(ui: &mut Ui, d: &mut Dialog, sample: Color) { /// and its number field, showing `shown` with `suffix`. Returns the whole number in `shown`'s /// range that a drag, a key or the field sets. #[allow(clippy::too_many_arguments)] -fn slider_cell( +pub(crate) fn slider_cell( ui: &mut Ui, id: impl std::hash::Hash + Copy, label: &str, diff --git a/crates/ui-egui/src/dialogs/save_for_web.rs b/crates/ui-egui/src/dialogs/save_for_web.rs index f1ef2db34b..6ff967f95a 100644 --- a/crates/ui-egui/src/dialogs/save_for_web.rs +++ b/crates/ui-egui/src/dialogs/save_for_web.rs @@ -57,6 +57,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; @@ -538,10 +540,19 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { take_shift(d); 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| { @@ -549,6 +560,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); @@ -562,16 +577,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() { @@ -616,6 +631,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)); @@ -632,11 +658,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 } @@ -741,7 +771,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); }; diff --git a/crates/ui-egui/src/dialogs/save_pdf.rs b/crates/ui-egui/src/dialogs/save_pdf.rs index f76dcc164b..edfb66e7f4 100644 --- a/crates/ui-egui/src/dialogs/save_pdf.rs +++ b/crates/ui-egui/src/dialogs/save_pdf.rs @@ -152,10 +152,31 @@ fn params(d: &Dialog) -> Value { p } -/// Save PDF: write the file (a PDF copy, or the PDF a Save As / Save a Copy asked for, `__save`); -/// the dialog stays open when that fails (bad range, cancelled save…). While Save Preset… asks for -/// a name, OK (and Enter) saves the preset instead. +/// The field that holds why the last Save PDF failed, shown in the dialog (the status bar sits +/// behind it, #6861). +const ERROR: &str = "__error"; + +/// Save PDF: write the file (see [`write`]). When that fails the dialog stays open and says why, +/// under its sections, as well as in the status bar the dialog covers. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let r = write(app, d); + if let Some(open) = app.ui.dialog.as_mut().filter(|o| o.kind == d.kind) { + match &r { + Err(e) => { + open.fields.insert(ERROR.into(), json!(e)); + } + Ok(_) => { + open.fields.remove(ERROR); + } + } + } + r +} + +/// Write the file (a PDF copy, or the PDF a Save As / Save a Copy asked for, `__save`); the +/// dialog stays open when that fails (bad range, cancelled save…). While Save Preset… asks for a +/// name, OK (and Enter) saves the preset instead. +fn write(app: &mut VectorcraftApp, d: &Dialog) -> Result { if d.fields.contains_key(SAVE_AS) { let mut d = d.clone(); let r = save_preset(app, &mut d); @@ -408,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), @@ -417,6 +439,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { "Summary" => summary(app, ui, d), _ => general(ui, d, editor), }); + if let Some(e) = d.fields.get(ERROR).and_then(Value::as_str) { + ui.add_space(6.0); + ui.label(egui::RichText::new(crate::i18n::message(crate::i18n::current(), e)).color(t.error)); + } }); }); false @@ -452,7 +478,8 @@ pub(super) fn section_list(ui: &mut egui::Ui, d: &mut Dialog, sections: &[&str], /// What choosing `standard` changes: the compatibility, to its version unless it allows the one /// chosen, and off what files of a standard can't have (editing data, passwords; layers in PDF/X-1a -/// and PDF/X-3). +/// and PDF/X-3). In PDF/X-3 and PDF/X-4, Profile inclusion goes back to unset: the picker is +/// disabled there, and `none` would write every CMYK color as DeviceCMYK. fn standard_chosen(d: &mut Dialog, standard: Standard) { if choice::(d, "compatibility").is_some_and(|c| !standard.allows(c)) { set(d, "compatibility", json!(standard.version().id())); @@ -466,6 +493,9 @@ fn standard_chosen(d: &mut Dialog, standard: Standard) { if !standard.allows_layers() { set(d, "createLayers", json!(false)); } + if standard.is_pdfx() && !standard.cmyk_only() { + set(d, "output.profiles", json!(vectorcraft_pdf::UNSET_CHOICE)); + } } /// The Preset row (the presets, built-in and saved, and Save Preset…) and, while Save Preset… @@ -712,6 +742,22 @@ fn output(ui: &mut egui::Ui, d: &mut Dialog) { }); if standard.cmyk_only() { note(ui, tl!("PDF/X-1a files are CMYK: every colour is converted to the destination (blank: the output intent's CMYK profile), untagged.")); + } else if standard.is_pdfx() { + note( + ui, + tl!( + "Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK." + ), + ); + // A preset or the dialog's params can bring `none` with the standard; the picker can't change it. + if choice::(d, "output.profiles") == Some(ProfileInclusion::None) { + note( + ui, + tl!( + "With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile." + ), + ); + } } else if standard != Standard::None { note(ui, tl!("Files of this standard tag their colours with ICC profiles.")); } diff --git a/crates/ui-egui/src/dialogs/save_pdf/tests.rs b/crates/ui-egui/src/dialogs/save_pdf/tests.rs index 91442f111c..6e02006cac 100644 --- a/crates/ui-egui/src/dialogs/save_pdf/tests.rs +++ b/crates/ui-egui/src/dialogs/save_pdf/tests.rs @@ -92,6 +92,27 @@ fn confirm_runs_export_pdf_with_the_dialog_options() { assert!(app.ui.status.starts_with("Saved /tmp/out.pdf"), "{}", app.ui.status); } +/// A Save PDF that fails keeps the dialog open and says why inside it (#6861): the status bar is +/// behind the dialog. Saving again, once it works, clears the message. +#[test] +fn a_failed_save_says_why_in_the_dialog() { + let (mut app, written, _) = app(); + app.run("ui.savePdfDialog", json!({"path": "/tmp/out.pdf"})).unwrap(); + set_field(&mut app, "__allArtboards", json!(false)); + set_field(&mut app, "range", json!("9")); + let e = super::super::confirm(&mut app).unwrap_err(); + assert!(written.borrow().is_empty(), "nothing was written"); + let d = app.ui.dialog.as_ref().expect("the dialog stays open"); + assert_eq!(d.str(ERROR), e, "the dialog holds the reason"); + assert!(!e.is_empty()); + assert!(params(d).get(ERROR).is_none(), "the message is not an option of the export"); + frame(&mut app); + set_field(&mut app, "range", json!("1")); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(written.borrow().len(), 1); +} + /// Opened for a page of the art's bounds (Export As with Use Artboards off), the dialog has no /// Artboards section, and OK writes one page of the art's bounds with its options, a saved preset /// and View PDF after Saving included. @@ -537,6 +558,39 @@ fn choosing_a_pdfx_standard_sets_its_version_and_writes_the_standard() { assert_eq!((get(d, "compatibility"), get(d, "createLayers")), (&json!("1.6"), &json!(true))); } +/// Profile inclusion is disabled with a standard, so choosing PDF/X-3 or PDF/X-4 sets it back to +/// unset: a `none` chosen before would write every CMYK color as DeviceCMYK. +#[test] +fn choosing_pdfx3_or_pdfx4_unsets_profile_inclusion() { + let (mut app, _, _) = app(); + for standard in [Standard::PdfX3, Standard::PdfX4] { + app.run("ui.savePdfDialog", json!({"path": "/tmp/x.pdf", "output": {"profiles": "none"}})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + assert_eq!(get(d, "output.profiles"), &json!("none")); + set(d, "standard", json!(standard.id())); + standard_chosen(d, standard); + assert_eq!(get(d, "output.profiles"), &json!(vectorcraft_pdf::UNSET_CHOICE), "{}", standard.id()); + } +} + +/// Opened with PDF/X-3 or PDF/X-4 and `none` (params or a preset, without choosing the standard), +/// the dialog keeps `none` and its Output note says every CMYK color is written as DeviceCMYK. +#[test] +fn a_loaded_pdfx_standard_with_no_profiles_says_cmyk_is_device_cmyk() { + const NOTE: &str = "every CMYK color is written as DeviceCMYK"; + let (mut app, _, _) = app(); + for (standard, profiles, shown) in + [(Standard::PdfX4, "none", true), (Standard::PdfX3, "none", true), (Standard::PdfX4, "all", false), (Standard::PdfX1a, "none", false)] + { + let params = json!({"path": "/tmp/x.pdf", "standard": standard.id(), "output": {"profiles": profiles}}); + app.run("ui.savePdfDialog", params).unwrap(); + set_field(&mut app, "__section", json!("Output")); + assert_eq!(get(app.ui.dialog.as_ref().unwrap(), "output.profiles"), &json!(profiles)); + let text = crate::tests_labels::painted_text(&mut app, |app, ui| super::super::show(app, ui.ctx())); + assert_eq!(text.contains(NOTE), shown, "{} {profiles}: {text}", standard.id()); + } +} + /// "Write pages longer than 200 in at full size in points" is enabled only without a standard, at /// PDF 1.5 and later: PDF/X files and PDF 1.3 and 1.4 files write long pages in points anyway, and /// PDF/A files keep the `UserUnit`. diff --git a/crates/ui-egui/src/dialogs/shape_builder_options.rs b/crates/ui-egui/src/dialogs/shape_builder_options.rs index 9393e0707e..d4edbad1f9 100644 --- a/crates/ui-egui/src/dialogs/shape_builder_options.rs +++ b/crates/ui-egui/src/dialogs/shape_builder_options.rs @@ -14,7 +14,7 @@ use vectorcraft_color::Color; use vectorcraft_doc::LAYER_COLORS; use super::tile_edge_color::{checked, resolve}; -use super::{DialogSpec, form, run_and_close}; +use super::{DialogSpec, form, set_tool_options_and_close}; use crate::state::Dialog; use crate::{VectorcraftApp, widgets}; @@ -124,7 +124,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { checked(&d.str("highlightColor"))?; } let values: Map = KEYS.iter().filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone()))).collect(); - run_and_close(app, "tool.setOption", json!({ "tool": "shapeBuilder", "values": values })) + set_tool_options_and_close(app, json!({ "tool": "shapeBuilder", "values": values })) } #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/shapes.rs b/crates/ui-egui/src/dialogs/shapes.rs index 3040097a25..c77b9a080e 100644 --- a/crates/ui-egui/src/dialogs/shapes.rs +++ b/crates/ui-egui/src/dialogs/shapes.rs @@ -102,8 +102,8 @@ fn line_length_angle(d: &Dialog) -> (f64, f64) { fn arc_options(d: &Dialog) -> Value { json!({ "closed": d.str("arcType").eq_ignore_ascii_case("closed"), - "lengthX": d.f64("lengthX", 100.0), - "lengthY": d.f64("lengthY", 100.0), + "lengthX": d.f64("lengthX", 100.0).abs(), + "lengthY": d.f64("lengthY", 100.0).abs(), "reference": arc_reference(d), "baseAlong": d.str("baseAlong"), "slope": d.f64("slope", 50.0), @@ -270,8 +270,8 @@ fn arc_form(ui: &mut egui::Ui, d: &mut Dialog, unit: Unit) { const ARC_PREVIEW: egui::Vec2 = egui::vec2(160.0, 120.0); const ARC_PREVIEW_MARGIN: f32 = 12.0; -/// The arc the Arc tool draws with the options OK sets from `d` ([`arc_options`], kept as the tool -/// keeps them: a slope from -100 to 100, a Base Along of Y or else X), as `shape.arc` draws it +/// The arc the Arc tool draws with the options OK sets from `d` ([`arc_options`]; a slope past -100 +/// or 100, which OK refuses, is drawn at that end, and a Base Along other than Y along X), as `shape.arc` draws it /// with its reference point at the origin and General › Constrain Angle `constrain` (degrees) /// turning it about that point. `None` when a length or the slope is not finite. fn arc_preview_path(d: &Dialog, constrain: f64) -> Option { @@ -554,13 +554,11 @@ fn box_origin(d: &Dialog) -> (f64, f64) { fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { // Tool Options: the options the tool's next drag and click use; nothing is drawn. if d.bool(TOOL_OPTIONS) { - let r = app.run("tool.setOption", json!({"tool": d.kind, "values": tool_options(d)})); - app.ui.dialog = None; - return r; + return super::set_tool_options_and_close(app, json!({"tool": d.kind, "values": tool_options(d)})); } let count = match d.kind.as_str() { "polygon" => Some(("sides", 6.0, 3.0)), - "star" => Some(("points", 5.0, 2.0)), + "star" => Some(("points", 5.0, 3.0)), _ => None, }; let options = count @@ -590,7 +588,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { "cx": x, "cy": y, "radius": d.f64("radius", 50.0).max(0.01), - "decay": d.f64("decay", 80.0).clamp(5.0, 150.0), + "decay": d.f64("decay", 80.0).clamp(5.0, 99.99), "segments": (d.f64("segments", 10.0) as u64).clamp(2, 1000), "clockwise": d.bool("clockwise"), }), @@ -648,7 +646,13 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { // On the active plane while the perspective grid shows, sized in plane units from the click; // else along General › Constrain Angle, turned about the point the dialog places at the click // (a grid's reference point, the other shapes' top-left corner or centre). - let options = options.or_else(|| (d.kind == "spiral").then(|| params.clone())); + let options = options.or_else(|| { + (d.kind == "spiral").then(|| json!({"decay": params["decay"], "segments": params["segments"], "clockwise": params["clockwise"]})) + }); + // Options the tool would refuse leave the dialog open, before anything is drawn. + if let Some(Value::Object(o)) = &options { + vectorcraft_tools::option_check::check_values(vectorcraft_tools::create(&d.kind).as_ref(), o)?; + } let result = match vectorcraft_engine::perspective_click(&app.session, id, ¶ms, vectorcraft_geom::Point::new(x, y)) { Some((id, params)) => run_and_close(app, &id, params), None => { @@ -707,6 +711,15 @@ mod tests { assert!(app.ui.dialog.is_none()); assert_eq!(app.session.doc().unwrap().doc.layers[0].children().unwrap().len(), 1); assert_eq!(app.session.tool_options_of("spiral"), json!({"decay": 65.0, "segments": 12, "clockwise": true})); + + // A decay typed past 99.99 % draws the spiral at 99.99 %, the most a spiral draws, and + // keeps that decay. + super::super::open_tool_dialog(&mut app, "spiral", json!({"x": 40.0, "y": 60.0})); + app.ui.dialog.as_mut().unwrap().fields.insert("decay".into(), json!(120.0)); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.doc().unwrap().doc.layers[0].children().unwrap().len(), 2); + assert_eq!(app.session.tool_options_of("spiral")["decay"], json!(99.99)); } /// With General › Constrain Angle at 90°, the Spiral dialog's spiral starts straight up from the @@ -812,21 +825,27 @@ mod tests { } } - /// For values the Arc tool does not keep as typed, the picture shows the arc of the options OK - /// sets: the same picture as a dialog holding those options. + /// For values the dialog reads as other values, the picture shows the arc of the options OK + /// sets: the same picture as a dialog holding those options. A slope outside -100 to 100 or a + /// Base Along other than X or Y is refused: OK leaves the dialog open and keeps the options. #[test] fn the_arc_preview_shows_the_options_ok_sets() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); - for typed in [ - json!({"slope": 140.0}), - json!({"slope": -250.0}), - json!({"slope": "steep"}), - json!({"lengthX": "wide"}), - json!({"lengthY": null}), - json!({"baseAlong": "z"}), - json!({"reference": 12}), + for (typed, error) in [ + (json!({"slope": 140.0}), "`slope` must be a number from -100 to 100"), + (json!({"slope": -250.0}), "`slope` must be a number from -100 to 100"), + (json!({"baseAlong": "z"}), "`baseAlong` must be one of"), ] { + let before = app.session.tool_options_of("arc"); + app.ui.dialog = Some(arc_dialog(typed.clone())); + let r = super::super::confirm(&mut app); + assert!(r.as_ref().is_err_and(|e| e.contains(error)), "{typed}: {r:?}"); + assert!(app.ui.dialog.is_some(), "{typed}"); + assert_eq!(app.session.tool_options_of("arc"), before, "{typed}"); + app.ui.dialog = None; + } + for typed in [json!({"slope": "steep"}), json!({"lengthX": "wide"}), json!({"lengthY": null}), json!({"reference": 12})] { let d = arc_dialog(typed.clone()); let shown = arc_preview_path(&d, 0.0).expect("an arc"); app.ui.dialog = Some(d); @@ -1112,9 +1131,11 @@ mod tests { super::super::open_tool_dialog(&mut app, "ellipse", json!({"x": 10.0, "y": 150.0})); assert_eq!(app.ui.dialog.as_ref().unwrap().f64("anchors", 0.0), 6.0); app.ui.dialog = None; - // `tool.setOption` keeps it from 2 to 1000, and the dialog opens on what it keeps. - for (set, want) in [(json!(1), 2.0), (json!(2000), 1000.0), (json!(7), 7.0)] { - app.run("tool.setOption", json!({"tool": "ellipse", "values": {"anchors": set}})).unwrap(); + // `tool.setOption` takes it from 2 to 1000 and refuses other counts, and the dialog opens on + // what it keeps. + for (set, want) in [(json!(1), 6.0), (json!(2000), 6.0), (json!(2), 2.0), (json!(1000), 1000.0), (json!(7), 7.0)] { + let r = app.run("tool.setOption", json!({"tool": "ellipse", "values": {"anchors": set}})); + assert_eq!(r.is_ok(), set.as_u64().is_some_and(|n| (2..=1000).contains(&n)), "{set}: {r:?}"); super::super::open_tool_dialog(&mut app, "ellipse", json!({"x": 10.0, "y": 150.0})); assert_eq!(app.ui.dialog.as_ref().unwrap().f64("anchors", 0.0), want, "{set}"); app.ui.dialog = None; 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/swatch_options.rs b/crates/ui-egui/src/dialogs/swatch_options.rs index 913a9126a8..044453d0a8 100644 --- a/crates/ui-egui/src/dialogs/swatch_options.rs +++ b/crates/ui-egui/src/dialogs/swatch_options.rs @@ -1,7 +1,10 @@ //! Swatch Options: name, colour type (process or spot), Global, colour mode with sliders and hex, -//! previewed live on the canvas (Cancel rolls the preview back). Double-clicking a swatch opens it -//! for a solid colour; for a gradient it shows the name and the gradient; patterns open pattern -//! editing ([`open`]). +//! and the out-of-gamut and out-of-web-color warnings under the colour, previewed live on the canvas +//! (Cancel rolls the preview back). A click on a warning's icon or colour corrects the colour +//! (https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf, +//! Swatch options; https://helpx.adobe.com/illustrator/using/adjusting-colors.html). +//! Double-clicking a swatch opens it for a solid colour; for a gradient it shows the name and the +//! gradient; patterns open pattern editing ([`open`]). //! //! Fields: `__swatch` (the swatch being edited), `name`, `spot`, `global`, `mode` (`gray`, `rgb`, //! `hsb`, `lab`, `cmyk` or `web`), `color` (`"#rrggbb"` or a colour object such as @@ -14,7 +17,9 @@ use vectorcraft_color::{Color, Paint}; use super::{DialogSpec, form, run_and_close}; use crate::VectorcraftApp; -use crate::panels::color::{Mode, components, from_components, parse_hex, track_color, web_safe}; +use crate::panels::color::{ + GAMUT_WARNING, Mode, WEB_WARNING, components, from_components, gamut_fix, is_web_safe, parse_hex, track_color, warning_chip, web_safe, +}; use crate::state::Dialog; use crate::theme::Tokens; use crate::widgets; @@ -113,7 +118,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { widgets::gradient_chip(ui, r, &g); changed } - None => editor(ui, d), + None => editor(app, ui, d), }; ui.add_space(8.0); let mut pv = d.bool("preview"); @@ -159,9 +164,9 @@ pub(super) fn name_row(ui: &mut egui::Ui, d: &mut Dialog) -> bool { changed } -/// The shared fields of Swatch Options and New Swatch: name, colour type, Global, mode, sliders and -/// hex. Returns true when anything changed. -pub(super) fn editor(ui: &mut egui::Ui, d: &mut Dialog) -> bool { +/// The shared fields of Swatch Options and New Swatch: name, colour type, Global, mode, sliders, +/// hex and the colour warnings. Returns true when anything changed. +pub(super) fn editor(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { let mut changed = false; grid(ui, |ui| { changed |= name_row(ui, d); @@ -193,15 +198,46 @@ pub(super) fn editor(ui: &mut egui::Ui, d: &mut Dialog) -> bool { ui.end_row(); }); ui.add_space(6.0); - changed | sliders(ui, d) + changed | sliders(app, ui, d) } -/// One slider and value field per component of the dialog's mode, the hex field (RGB, HSB and Web) -/// and a chip of the colour. Returns true when the colour changed. -fn sliders(ui: &mut egui::Ui, d: &mut Dialog) -> bool { +/// A warning under the colour of the swatch dialogs. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Warning { + Gamut, + Web, +} + +/// The warnings the swatch dialogs show in `mode`: out of gamut in RGB, HSB and Lab, and out of web +/// colors in every mode but Web Safe RGB. +fn shown_warnings(mode: Mode) -> (bool, bool) { + (matches!(mode, Mode::Rgb | Mode::Hsb | Mode::Lab), mode != Mode::WebSafe) +} + +/// The colour and mode a click on `warning` gives `c`, edited in `mode`: the nearest web-safe colour +/// (in RGB unless the mode is RGB or HSB), or the colour's CMYK equivalent in the active CMYK space +/// (in CMYK). `None` when the conversion returns no CMYK values. +fn corrected(app: &mut VectorcraftApp, warning: Warning, mode: Mode, c: &Color) -> Result, String> { + match warning { + Warning::Web => Ok(Some((web_safe(c), if matches!(mode, Mode::Rgb | Mode::Hsb) { mode } else { Mode::Rgb }))), + Warning::Gamut => { + let r = app.run("color.convert", json!({"color": crate::panels::color_json(c), "to": "cmyk"}))?; + let v = |i: usize| r["values"][i].as_f64().map(|v| v as f32); + Ok(v(0).zip(v(1)).zip(v(2)).zip(v(3)).map(|(((c, m), y), k)| (Color::cmyk(c, m, y, k), Mode::Cmyk))) + } + } +} + +/// One slider and value field per component of the dialog's mode, the hex field (RGB, HSB and Web), +/// a chip of the colour and under it the mode's warnings. Returns true when the colour changed. +fn sliders(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { let t = Tokens::get(ui.ctx()); let mode = mode_of(d); let color = color_of(d); + let (shows_gamut, shows_web) = shown_warnings(mode); + let gamut = if shows_gamut { gamut_fix(app, ui.ctx(), "swatch-gamut", &color) } else { None }; + let web = (shows_web && !is_web_safe(&color)).then(|| web_safe(&color)); + let mut clicked: Option = None; // Keep the displayed components while the colour is unchanged (hue survives S = 0 etc.). let key = format!("{}|{}", mode_id(mode), serde_json::to_string(&color).unwrap_or_default()); let comps: Vec = match d.fields.get("__comps") { @@ -241,13 +277,47 @@ fn sliders(ui: &mut egui::Ui, d: &mut Dialog) -> bool { }); } }); - let (r, _) = ui.allocate_exact_size(vec2(44.0, 44.0), egui::Sense::hover()); - widgets::swatch_tile(ui, r, &Paint::solid(color), false, false); + ui.vertical(|ui| { + let (r, _) = ui.allocate_exact_size(vec2(44.0, 44.0), egui::Sense::hover()); + widgets::swatch_tile(ui, r, &Paint::solid(color), false, false); + let warnings: Vec<_> = [(Warning::Gamut, GAMUT_WARNING, gamut), (Warning::Web, WEB_WARNING, web)] + .into_iter() + .filter_map(|(w, chip, fix)| Some((w, chip, fix?))) + .collect(); + for (w, chip, fix) in &warnings { + ui.add_space(4.0); + if warning_chip(ui, *chip, fix) { + clicked = Some(*w); + } + } + // Room for the mode's other warnings, so the dialog keeps its height as the colour changes. + for _ in warnings.len()..usize::from(shows_gamut) + usize::from(shows_web) { + ui.add_space(4.0); + ui.scope(|ui| { + ui.set_invisible(); + warning_chip(ui, WEB_WARNING, &Color::WHITE) + }); + } + }); }); + let mut mode = mode; + if let Some(w) = clicked { + match corrected(app, w, mode, &color) { + Ok(Some((c, m))) => { + mode = m; + d.fields.insert("mode".into(), json!(mode_id(m))); + new = Some((c, components(m, &c))); + } + Ok(None) => {} + Err(e) => app.status(e), + } + } let Some((c, comps)) = new else { return false }; set_color(d, c); d.fields.insert("__compsKey".into(), json!(format!("{}|{}", mode_id(mode), serde_json::to_string(&c).unwrap_or_default()))); d.fields.insert("__comps".into(), json!(comps)); + // The warnings above were drawn for the colour before the change. + ui.ctx().request_repaint(); true } @@ -279,9 +349,122 @@ fn hex_field(ui: &mut egui::Ui, hex: &str) -> Option { } #[cfg(test)] -mod tests { +pub(super) mod tests { use super::*; + /// A test context with the application's fonts and default theme. + pub(crate) fn context() -> egui::Context { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + crate::theme::apply(&ctx, Default::default()); + ctx + } + + /// Runs one frame of the open dialog with `events` and returns the rectangles it paints. + pub(crate) fn draw(ctx: &egui::Context, app: &mut VectorcraftApp, events: Vec) -> Vec { + fn collect(s: &egui::Shape, out: &mut Vec) { + match s { + egui::Shape::Rect(r) => out.push(r.rect), + egui::Shape::Vec(v) => v.iter().for_each(|s| collect(s, out)), + _ => {} + } + } + let input = + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(1280.0, 900.0))), events, ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| super::super::show(app, ui.ctx())); + out.textures_delta.clear(); + let mut boxes = vec![]; + out.shapes.iter().for_each(|c| collect(&c.shape, &mut boxes)); + boxes + } + + /// Lets the auto-sized dialog settle and returns the rectangles of the next frame. + pub(crate) fn settled(ctx: &egui::Context, app: &mut VectorcraftApp) -> Vec { + for _ in 0..6 { + draw(ctx, app, vec![]); + } + draw(ctx, app, vec![]) + } + + /// A primary-button press and release at `at`, in two frames. + pub(crate) fn click_at(ctx: &egui::Context, app: &mut VectorcraftApp, at: egui::Pos2) { + for pressed in [true, false] { + let button = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + draw(ctx, app, vec![egui::Event::PointerMoved(at), button]); + } + } + + /// The warning rows under the dialog's 44-point colour chip, top first: the centre of each + /// row's icon and the rectangle of its corrected colour. + pub(crate) fn warning_rows(boxes: &[egui::Rect]) -> Vec<(egui::Pos2, egui::Rect)> { + let near = |a: f32, b: f32| (a - b).abs() < 0.5; + let chip = boxes.iter().find(|r| near(r.width(), 44.0) && near(r.height(), 44.0)).copied().unwrap(); + let mut rows: Vec = boxes + .iter() + .filter(|r| near(r.width(), 16.0) && near(r.height(), 16.0)) + .filter(|r| r.top() >= chip.bottom() && r.left() >= chip.left() - 1.0 && r.right() <= chip.right() + 1.0) + .copied() + .collect(); + rows.sort_by(|a, b| a.top().total_cmp(&b.top())); + rows.dedup_by(|a, b| near(a.top(), b.top())); // The tile's fill and border share one rectangle. + rows.into_iter().map(|r| (r.center() - vec2(19.0, 0.0), r)).collect() + } + + fn dialog(app: &VectorcraftApp) -> &Dialog { + app.ui.dialog.as_ref().unwrap() + } + + #[test] + fn swatch_options_shows_and_corrects_both_warnings() { + let (ctx, mut app) = (context(), VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default())); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("swatch.new", json!({"name": "Sky", "color": "#0000fe", "spot": true})).unwrap(); + app.run("ui.swatchOptions", json!({"name": "Sky"})).unwrap(); + let rows = warning_rows(&settled(&ctx, &mut app)); + assert_eq!(rows.len(), 2, "out of gamut and out of web colors"); + // The cube's icon shifts to the nearest web-safe colour, in the same mode. + click_at(&ctx, &mut app, rows[1].0); + assert_eq!((color_of(dialog(&app)).to_hex(), dialog(&app).str("mode")), ("#0000ff".to_string(), "rgb".to_string())); + let rows = warning_rows(&settled(&ctx, &mut app)); + assert_eq!(rows.len(), 1, "web-safe blue is still out of gamut"); + // The triangle's colour shifts to the CMYK equivalent, edited in CMYK. + let ink = corrected(&mut app, Warning::Gamut, Mode::Rgb, &Color::rgb8(0, 0, 255)).unwrap().unwrap().0; + click_at(&ctx, &mut app, rows[0].1.center()); + assert_eq!((color_of(dialog(&app)), dialog(&app).str("mode")), (ink, "cmyk".to_string())); + assert!(app.ui.dialog.is_some(), "a correction only edits the fields"); + super::super::confirm(&mut app).unwrap(); + let sw = app.session.active().unwrap().doc.swatch("Sky").cloned().unwrap(); + assert_eq!((sw.paint.color(), sw.spot, sw.global), (Some(ink), true, true), "still a spot colour"); + app.run("edit.undo", json!({})).unwrap(); + let sw = app.session.active().unwrap().doc.swatch("Sky").cloned().unwrap(); + assert_eq!(sw.paint.color().map(|c| c.to_hex()), Some("#0000fe".into()), "one undo step"); + } + + #[test] + fn swatch_warnings_follow_the_mode() { + let (ctx, mut app) = (context(), VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default())); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("swatch.new", json!({"name": "Mid", "color": "#808080"})).unwrap(); + app.run("ui.swatchOptions", json!({"name": "Mid"})).unwrap(); + let mut rows_in = |mode: &str, c: Color| { + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("mode".into(), json!(mode)); + set_color(d, c); + warning_rows(&settled(&ctx, &mut app)).len() + }; + assert_eq!(rows_in("gray", Color::gray(0.5)), 1, "a gray off the web palette, never out of gamut"); + let cyan = Color::cmyk(1.0, 0.0, 0.0, 0.0); + assert_eq!(rows_in("cmyk", cyan), usize::from(!is_web_safe(&cyan)), "CMYK is never out of gamut"); + assert_eq!(rows_in("web", Color::rgb8(0, 0, 255)), 0, "Web Safe RGB shows no warning"); + assert_eq!(rows_in("rgb", Color::rgb8(0, 0, 255)), 1, "RGB blue is out of gamut"); + assert_eq!(rows_in("lab", Color::lab(30.0, 60.0, -100.0)), 2, "Lab shows both"); + // A web correction of a Lab colour is edited in RGB. + let rows = warning_rows(&settled(&ctx, &mut app)); + click_at(&ctx, &mut app, rows[1].0); + assert_eq!(dialog(&app).str("mode"), "rgb"); + assert!(is_web_safe(&color_of(dialog(&app)))); + } + #[test] fn fields_round_trip_modes_and_colours() { for (m, id) in MODES { 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/symbolism_options.rs b/crates/ui-egui/src/dialogs/symbolism_options.rs index 33d902b90e..05392bbd4f 100644 --- a/crates/ui-egui/src/dialogs/symbolism_options.rs +++ b/crates/ui-egui/src/dialogs/symbolism_options.rs @@ -6,7 +6,7 @@ use serde_json::{Map, Value, json}; -use super::{DialogResult, DialogSpec, form, run_and_close}; +use super::{DialogResult, DialogSpec, form, set_tool_options_and_close}; use crate::state::Dialog; use crate::{VectorcraftApp, widgets}; @@ -50,7 +50,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { /// OK: set the brush the Symbolism tools share (the tool keeps it within its ranges). fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { let values: Map = KEYS.iter().filter(|k| d.fields.contains_key(**k)).map(|k| (k.to_string(), json!(d.f64(k, 0.0)))).collect(); - run_and_close(app, "tool.setOption", json!({ "tool": d.str("tool"), "values": values })) + set_tool_options_and_close(app, json!({ "tool": d.str("tool"), "values": values })) } #[cfg(test)] 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_import_pdf.rs b/crates/ui-egui/src/dialogs/tests_import_pdf.rs index 62e783c267..5ecd7734cb 100644 --- a/crates/ui-egui/src/dialogs/tests_import_pdf.rs +++ b/crates/ui-egui/src/dialogs/tests_import_pdf.rs @@ -95,12 +95,19 @@ fn import_pdf_pages_as_links_opens_each_page_linked() { let path = dir.join("three.pdf").to_string_lossy().into_owned(); std::fs::write(&path, three_pages()).unwrap(); let mut app = app(); + // All pages: checked without a click. io::open_bytes(&mut app, &path, &three_pages(), Some(path.clone())).unwrap(); - assert_eq!(field(&app, "linkPages"), false, "off by default"); frame(&mut app); - set(&mut app, "linkPages", json!(true)); + confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(artboard_widths(&app), [100.0, 200.0, 300.0]); + assert_eq!(placed_pages(&app), [true, true, true], "All opens the pages linked"); + // A range: cleared, and checked by hand it opens the range linked. + io::open_bytes(&mut app, &path, &three_pages(), Some(path.clone())).unwrap(); set(&mut app, "allPages", json!(false)); set(&mut app, "range", json!("1, 3")); + assert!(!import_pdf::links_on(app.ui.dialog.as_ref().unwrap()), "Range: cleared"); + set(&mut app, "linkPages", json!(true)); frame(&mut app); confirm(&mut app).unwrap(); assert!(app.ui.dialog.is_none()); @@ -124,6 +131,41 @@ fn import_pdf_pages_as_links_opens_each_page_linked() { assert_eq!(placed_pages(&app), [false, false]); } +/// Picking All checks Import PDF pages as links and picking Range clears it. A click on the box +/// stands until the other one is picked; picking the one already picked or editing the range keeps +/// it. `ui.dialog.set` picks the way the buttons do. +#[test] +fn picking_all_or_a_range_sets_the_links_default() { + let mut app = app(); + io::open_bytes(&mut app, "three.pdf", &three_pages(), Some("/tmp/three.pdf".into())).unwrap(); + let pick = |app: &mut VectorcraftApp, k: &str, v: serde_json::Value| set_field(app.ui.dialog.as_mut().unwrap(), k.into(), v); + let on = |app: &VectorcraftApp| import_pdf::links_on(app.ui.dialog.as_ref().unwrap()); + assert!(on(&app), "All: checked"); + pick(&mut app, "allPages", json!(false)); + assert!(!on(&app), "Range: cleared"); + pick(&mut app, "linkPages", json!(true)); + pick(&mut app, "allPages", json!(false)); + pick(&mut app, "range", json!("1-2")); + frame(&mut app); + assert!(on(&app), "checked by hand, picking Range again and editing the range keep it"); + pick(&mut app, "allPages", json!(true)); + assert!(on(&app), "All: checked"); + pick(&mut app, "linkPages", json!(false)); + pick(&mut app, "allPages", json!(true)); + frame(&mut app); + assert!(!on(&app), "cleared by hand, picking All again keeps it"); + pick(&mut app, "allPages", json!(false)); + pick(&mut app, "allPages", json!(true)); + assert!(on(&app), "All picked after Range: checked again"); + // A file `linkPages` does not take (one over its size limit) leaves the box clear. + assert_eq!(field(&app, "__linkable"), true); + set(&mut app, "__linkable", json!(false)); + assert!(!on(&app), "a file linkPages does not take"); + // A file given without its path can't link its pages: the box stays clear. + io::open_bytes(&mut app, "three.pdf", &three_pages(), None).unwrap(); + assert!(!on(&app)); +} + #[test] fn single_page_pdfs_open_directly() { let mut app = app(); 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_raster_supplied_options.rs b/crates/ui-egui/src/dialogs/tests_raster_supplied_options.rs new file mode 100644 index 0000000000..a1c22e2db0 --- /dev/null +++ b/crates/ui-egui/src/dialogs/tests_raster_supplied_options.rs @@ -0,0 +1,54 @@ +use serde_json::json; +use vectorcraft_engine::cmd::fileio; + +use super::tests_export::{app, frame, kind}; +use super::{confirm, png_options}; + +#[test] +fn raster_options_preserve_supplied_values_through_the_png_command() { + let (mut app, written) = app(1); + app.run("file.export.png", json!({"ppi": 300, "background": "#204080", "antiAlias": "type", "interlaced": true})).unwrap(); + assert_eq!(kind(&app), Some("pngOptions")); + let fields = &app.ui.dialog.as_ref().unwrap().fields; + assert_eq!(fields["ppi"], 300); + assert_eq!(fields["background"], "#204080"); + assert_eq!(fields["antiAlias"], "type"); + assert_eq!(fields["interlaced"], true); + frame(&mut app); + confirm(&mut app).unwrap(); + { + let output = written.borrow(); + assert_eq!(output.len(), 1); + let png = &output[0].1; + assert_eq!(png[28], 1); + let physical = png.windows(4).position(|w| w == b"pHYs").unwrap(); + assert_eq!(&png[physical + 4..physical + 8], ((300.0f64 / 0.0254).round() as u32).to_be_bytes()); + let decoded = craft_image_codecs::decode(png).unwrap(); + assert_eq!(decoded.dimensions(), (250, 167)); + assert_eq!(&decoded.to_rgba8()[..4], &[0x20, 0x40, 0x80, 255]); + } + + png_options::open(&mut app, fileio::format("jpg").unwrap(), json!({"format": "jpg", "path": "/out/supplied.jpg", "ppi": 144, "quality": 40})); + let fields = &app.ui.dialog.as_ref().unwrap().fields; + assert_eq!(fields["quality"], 40); + assert_eq!(fields["ppi"], 144); + assert_eq!(fields["background"], "white"); + frame(&mut app); + confirm(&mut app).unwrap(); + assert_eq!(written.borrow().len(), 2); + + for omitted in [json!({}), json!({"ppi": null, "background": null, "antiAlias": null, "interlaced": null})] { + app.run("file.export.png", omitted).unwrap(); + let fields = &app.ui.dialog.as_ref().unwrap().fields; + assert_eq!(fields["ppi"], 72); + assert_eq!(fields["background"], "transparent"); + assert_eq!(fields["antiAlias"], "art"); + assert_eq!(fields["interlaced"], false); + app.ui.dialog = None; + } + + app.run("file.export.png", json!({"ppi": 0})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["ppi"], 0); + assert!(confirm(&mut app).unwrap_err().contains("ppi must be a positive number")); + assert_eq!(written.borrow().len(), 2); +} diff --git a/crates/ui-egui/src/dialogs/tests_rectangular_grid.rs b/crates/ui-egui/src/dialogs/tests_rectangular_grid.rs index ef5dca5ede..e2db8b6d75 100644 --- a/crates/ui-egui/src/dialogs/tests_rectangular_grid.rs +++ b/crates/ui-egui/src/dialogs/tests_rectangular_grid.rs @@ -339,6 +339,20 @@ fn rectangular_grid_failed_creation_does_not_save_counts() { assert_eq!(app.session.doc().unwrap().history.undo.len(), before.undo); } +/// Tool Options with a width the tool refuses is an error that keeps the dialog open and sets +/// nothing. +#[test] +fn rectangular_grid_tool_options_with_a_refused_width_stay_open() { + let mut app = app(); + let before = app.session.tool_options_of(KIND); + super::shapes::open_options(&mut app, KIND).unwrap(); + set(&mut app, "width", json!(0)); + let e = super::confirm(&mut app).unwrap_err(); + assert!(e.contains("`width`"), "{e}"); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(KIND)); + assert_eq!(app.session.tool_options_of(KIND), before); +} + /// #1377: the dialog shows the tool's stored skews (sliders under their divider counts) and /// switches; OK draws with them and stores them, and the next drag uses them too. #[test] 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 3091a00cac..39d3d1a8a3 100644 --- a/crates/ui-egui/src/dialogs/three_d_materials.rs +++ b/crates/ui-egui/src/dialogs/three_d_materials.rs @@ -1,6 +1,6 @@ //! 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, or -//! Revolve's side) with their face, position, size and turn. Picking a thumbnail maps that graphic +//! Add as Single Graphic, and the graphics mapped onto the selected 3D object (its planar faces, +//! Extrude & Bevel's side, or Revolve's side) 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. @@ -85,6 +85,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 +121,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 +130,18 @@ 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). if effect != ROTATE && effect != REVOLVE { 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 = PlanarFace::ALL.map(face_label); + let at = PlanarFace::ALL.iter().position(|f| *f == g.face).unwrap_or(0); + if let Some(k) = widgets::dropdown(ui, "three-d-graphic-face", labels[at], &labels, 120.0) + && let Some(face) = PlanarFace::ALL.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/dialogs/width_point.rs b/crates/ui-egui/src/dialogs/width_point.rs index afa27c2abf..b0881b9082 100644 --- a/crates/ui-egui/src/dialogs/width_point.rs +++ b/crates/ui-egui/src/dialogs/width_point.rs @@ -6,12 +6,22 @@ //! OK runs `stroke.widthPoint.set`; Delete removes an existing point (`stroke.widthPoint.remove`) //! or discards a prospective point without changing the document. //! -//! Fields: `id`, `index` (an existing width point, otherwise null), `t` (its place), `side1`, -//! `side2` (the left and right widths, points), `linked`, `adjustAdjoining`; Delete sets `discard: true` and confirms. +//! On either half of a discontinuous point the dialog shows both sets of side widths, Incoming +//! (before the point along the path) and Outgoing (after it), and Single Width Only keeps one of +//! them as a continuous point. OK sets both halves in one `stroke.widthPoint.set` (one undo step), +//! and Delete removes both halves. +//! +//! Fields: `id`, `index` (an existing width point, otherwise null; the incoming half of a +//! discontinuous point), `t` (its place), `side1`, `side2` (the left and right widths, points), +//! `linked`, `adjustAdjoining`; for a discontinuous point also `outIndex`, `outSide1`, `outSide2`, +//! `outLinked` (the outgoing half) and `single` (`""`, `"incoming"` or `"outgoing"`); Delete sets +//! `discard: true` and confirms. use egui::vec2; use serde_json::{Value, json}; +use vectorcraft_doc::Unit; use vectorcraft_engine::doc::NodeId; +use vectorcraft_engine::width_point_pair; use super::swatch_options::{grid, label}; use super::{DialogSpec, run_and_close}; @@ -31,9 +41,20 @@ fn point(app: &VectorcraftApp, id: u64, index: usize) -> Option<(f64, f64, f64)> st.profile.as_ref()?.points.get(index).map(|&(t, l, r)| (t, l * half, r * half)) } +/// The incoming and outgoing halves of the discontinuous point that width point `index` of `id` +/// belongs to, or none when it is a continuous point. The halves are paired by +/// [`width_point_pair`], as `stroke.widthPoint.set` pairs them, so either half finds the same pair. +fn halves(app: &VectorcraftApp, id: u64, index: usize) -> Option<(usize, usize)> { + let points = &app.session.active()?.doc.node(NodeId(id))?.appearance.stroke()?.profile.as_ref()?.points; + points.get(index)?; + let pair = |a: usize| width_point_pair(points, a).map(|b| (a, b)); + pair(index).or_else(|| index.checked_sub(1).and_then(pair)) +} + /// Open Width Point Edit for `index`, or a prospective point at fraction `t` without an index /// (`{id, index?, t?, adjustAdjoining?}`). Opening only samples the stroke: confirmation creates -/// the point. Adjoining adjustment defaults to false. +/// the point. Adjoining adjustment defaults to false. Either half of a discontinuous point opens +/// both. pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { let id = p.get("id").and_then(Value::as_u64).ok_or("give the path `id`")?; let doc = &app.session.active().ok_or("no document")?.doc; @@ -42,6 +63,8 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { Some(v) => Some(v.as_u64().and_then(|i| usize::try_from(i).ok()).ok_or("no such width point")?), None => None, }; + let pair = index.and_then(|i| halves(app, id, i)); + let index = pair.map_or(index, |(a, _)| Some(a)); let (t, l, r) = if let Some(index) = index { point(app, id, index).ok_or("no such width point")? } else { @@ -59,45 +82,86 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { (t, l, r) }; let adjust = p.get("adjustAdjoining").and_then(Value::as_bool).unwrap_or(false); - let fields = json!({"id": id, "index": index, "t": t, "side1": l, "side2": r, "linked": (l - r).abs() < 1e-9, "adjustAdjoining": adjust}); + let mut fields = json!({"id": id, "index": index, "t": t, "side1": l, "side2": r, "linked": (l - r).abs() < 1e-9, "adjustAdjoining": adjust}); + if let Some((_, out)) = pair { + let (_, l, r) = point(app, id, out).ok_or("no such width point")?; + for (key, value) in [ + ("outIndex", json!(out)), + ("outSide1", json!(l)), + ("outSide2", json!(r)), + ("outLinked", json!((l - r).abs() < 1e-9)), + ("single", json!("")), + ] { + fields[key] = value; + } + } app.ui.dialog = Some(Dialog::new(KIND, fields)); Ok(Value::Null) } -fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { - let unit = app.session.stroke_unit(); - let (s1, s2, linked) = (d.f64("side1", 0.0), d.f64("side2", 0.0), d.bool("linked")); - let mut sides = None; +/// Whether the dialog edits a discontinuous point. +fn paired(d: &Dialog) -> bool { + d.fields.get("outIndex").is_some_and(|v| !v.is_null()) +} + +/// One set of side widths: Side 1 with its link, Side 2 and Total Width, kept in the fields `keys` +/// (side 1, side 2, linked) and shown in the number fields `ids`. +fn sides(ui: &mut egui::Ui, d: &mut Dialog, unit: Unit, keys: [&str; 3], ids: [&str; 3]) { + let [k1, k2, kl] = keys; + let (s1, s2, linked) = (d.f64(k1, 0.0), d.f64(k2, 0.0), d.bool(kl)); + let mut new = None; grid(ui, |ui| { label(ui, tl!("Side 1:")); ui.horizontal(|ui| { - if let Some(v) = widgets::num_field(ui, "wp-side1", Some(s1), unit, 90.0) { - sides = Some((v, if linked { v } else { s2 })); + if let Some(v) = widgets::num_field(ui, ids[0], Some(s1), unit, 90.0) { + new = Some((v, if linked { v } else { s2 })); } if widgets::icon_button(ui, if linked { "link" } else { "link-2-off" }, tl!("Keep both sides the same width"), linked, 22.0).clicked() { - d.fields.insert("linked".into(), json!(!linked)); + d.fields.insert(kl.into(), json!(!linked)); if !linked { - sides = Some((s1, s1)); + new = Some((s1, s1)); } } }); ui.end_row(); label(ui, tl!("Side 2:")); - if let Some(v) = widgets::num_field(ui, "wp-side2", Some(s2), unit, 90.0) { - sides = Some((if linked { v } else { s1 }, v)); + if let Some(v) = widgets::num_field(ui, ids[1], Some(s2), unit, 90.0) { + new = Some((if linked { v } else { s1 }, v)); } ui.end_row(); label(ui, tl!("Total Width:")); - if let Some(v) = widgets::num_field(ui, "wp-total", Some(s1 + s2), unit, 90.0) { + if let Some(v) = widgets::num_field(ui, ids[2], Some(s1 + s2), unit, 90.0) { // Both sides in proportion (equal halves from nothing). let k = if s1 + s2 > 1e-9 { v / (s1 + s2) } else { 0.0 }; - sides = Some(if k > 0.0 { (s1 * k, s2 * k) } else { (v / 2.0, v / 2.0) }); + new = Some(if k > 0.0 { (s1 * k, s2 * k) } else { (v / 2.0, v / 2.0) }); } ui.end_row(); }); - if let Some((a, b)) = sides { - d.fields.insert("side1".into(), json!(a.max(0.0))); - d.fields.insert("side2".into(), json!(b.max(0.0))); + if let Some((a, b)) = new { + d.fields.insert(k1.into(), json!(a.max(0.0))); + d.fields.insert(k2.into(), json!(b.max(0.0))); + } +} + +fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + let unit = app.session.stroke_unit(); + let incoming = (["side1", "side2", "linked"], ["wp-side1", "wp-side2", "wp-total"]); + if paired(d) { + widgets::section_header(ui, tl!("Incoming")); + ui.push_id("wp-incoming", |ui| sides(ui, d, unit, incoming.0, incoming.1)); + widgets::section_header(ui, tl!("Outgoing")); + ui.push_id("wp-outgoing", |ui| sides(ui, d, unit, ["outSide1", "outSide2", "outLinked"], ["wp-out-side1", "wp-out-side2", "wp-out-total"])); + widgets::section_header(ui, tl!("Single Width Only")); + ui.horizontal(|ui| { + let single = d.str("single"); + for (value, text) in [("", tl!("None")), ("incoming", tl!("Incoming")), ("outgoing", tl!("Outgoing"))] { + if widgets::radio(ui, text, single == value, true) { + d.fields.insert("single".into(), json!(value)); + } + } + }); + } else { + sides(ui, d, unit, incoming.0, incoming.1); } ui.add_space(4.0); ui.allocate_ui(vec2(ui.available_width(), 22.0), |ui| { @@ -110,16 +174,30 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { let (id, index) = (d.fields.get("id").cloned().unwrap_or_default(), d.fields.get("index").cloned().unwrap_or_default()); + let out = d.fields.get("outIndex").filter(|_| paired(d)).cloned(); if d.bool("discard") { if index.is_null() { // Deleting a prospective point discards the dialog; no document point exists yet. app.ui.dialog = None; return Ok(Value::Null); } - return run_and_close(app, "stroke.widthPoint.remove", json!({"id": id, "index": index})); + let p = match out { + Some(out) => json!({"id": id, "indices": [index, out]}), + None => json!({"id": id, "index": index}), + }; + return run_and_close(app, "stroke.widthPoint.remove", p); } let (left, right) = (d.f64("side1", 0.0), d.f64("side2", 0.0)); - let p = json!({"id": id, "index": index, "t": d.f64("t", 0.0), "left": left, "right": right, "adjustAdjoining": d.bool("adjustAdjoining")}); + let mut p = json!({"id": id, "index": index, "t": d.f64("t", 0.0), "left": left, "right": right, "adjustAdjoining": d.bool("adjustAdjoining")}); + if let Some(out) = out { + p["outIndex"] = out; + p["outLeft"] = json!(d.f64("outSide1", 0.0)); + p["outRight"] = json!(d.f64("outSide2", 0.0)); + let single = d.str("single"); + if !single.is_empty() { + p["single"] = json!(single); + } + } run_and_close(app, "stroke.widthPoint.set", p) } diff --git a/crates/ui-egui/src/dialogs/width_point/tests.rs b/crates/ui-egui/src/dialogs/width_point/tests.rs index 4c5b972f12..bf32a6124f 100644 --- a/crates/ui-egui/src/dialogs/width_point/tests.rs +++ b/crates/ui-egui/src/dialogs/width_point/tests.rs @@ -400,3 +400,176 @@ fn new_width_point_checkbox_adjusts_adjoining_in_one_step() { fn new_width_point_checkbox_off_preserves_adjoining() { creation_adjoining_checkbox(false); } + +/// [`app`]'s line with a discontinuous point in the middle: 4 + 4 pt before it, 2 + 6 pt after it. +fn pair_app() -> (VectorcraftApp, u64) { + let (mut app, id) = app(); + app.run("stroke.widthProfile.set", json!({"ids": [id], "points": [[0, 1, 1], [0.5, 0.8, 0.8], [0.5, 0.4, 1.2], [1, 1, 1]]})).unwrap(); + app.session.doc_mut().unwrap().mark_saved(); + (app, id) +} + +fn assert_pair_fields(d: &Dialog) { + assert_eq!((d.fields["index"].clone(), d.fields["outIndex"].clone()), (json!(1), json!(2))); + assert_eq!((d.f64("side1", 0.0), d.f64("side2", 0.0), d.bool("linked")), (4.0, 4.0, true)); + assert_eq!((d.f64("outSide1", 0.0), d.f64("outSide2", 0.0), d.bool("outLinked")), (2.0, 6.0, false)); + assert_eq!(d.str("single"), ""); +} + +#[test] +fn either_half_of_a_discontinuous_point_shows_both_sets_of_side_widths() { + for index in [1, 2] { + let (mut app, id) = pair_app(); + app.run("ui.widthPointEdit", json!({"id": id, "index": index})).unwrap(); + assert_pair_fields(app.ui.dialog.as_ref().unwrap()); + let shown = frame(&mut app); + for s in ["Incoming", "Outgoing", "Single Width Only", "None", "Adjust Adjoining Width Points", "Delete"] { + assert!(shown.iter().any(|t| t == s), "{s} in {shown:?}"); + } + for s in ["Side 1:", "Side 2:", "Total Width:"] { + assert_eq!(shown.iter().filter(|t| *t == s).count(), 2, "{s} in each set: {shown:?}"); + } + } + // Double-clicking the point with the Width tool opens the same two sets. + let (mut app, _) = pair_app(); + let view = app.view_info(); + app.select_tool("width"); + crate::canvas::dispatch(&mut app, &PointerEvent::new(PointerKind::DoubleClick, 200.0, 150.0), view); + assert_pair_fields(app.ui.dialog.as_ref().expect("Width Point Edit opened")); + // A continuous point keeps one set. + let (mut app, id) = pair_app(); + app.run("ui.widthPointEdit", json!({"id": id, "index": 0})).unwrap(); + assert!(app.ui.dialog.as_ref().unwrap().fields.get("outIndex").is_none()); + let shown = frame(&mut app); + assert!(!shown.iter().any(|t| t == "Incoming" || t == "Outgoing"), "{shown:?}"); + assert_eq!(shown.iter().filter(|t| *t == "Side 1:").count(), 1); +} + +/// Three width points each within 1e-6 of the next, but the outer two farther apart: the halves +/// are paired as `stroke.widthPoint.set` pairs them, from the incoming half's place, whichever +/// of them is opened. The first two make one discontinuous point, and the third stays a +/// continuous point. +#[test] +fn points_in_a_chain_pair_as_the_engine_pairs_them() { + let chain = json!([[0, 1, 1], [0.5, 0.8, 0.8], [0.50000075, 0.4, 1.2], [0.5000015, 0.6, 0.6], [1, 1, 1]]); + for index in [1, 2] { + let (mut app, id) = app(); + app.run("stroke.widthProfile.set", json!({"ids": [id], "points": chain})).unwrap(); + app.run("ui.widthPointEdit", json!({"id": id, "index": index})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + assert_eq!((d.fields["index"].clone(), d.fields["outIndex"].clone()), (json!(1), json!(2)), "opened {index}"); + d.fields.insert("outSide1".into(), json!(1)); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none(), "opened {index}"); + assert_eq!(points(&app, id)[2], (0.50000075, 0.2, 1.2), "opened {index}"); + } + let (mut app, id) = app(); + app.run("stroke.widthProfile.set", json!({"ids": [id], "points": chain})).unwrap(); + app.run("ui.widthPointEdit", json!({"id": id, "index": 3})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + assert_eq!(d.fields["index"], json!(3)); + assert!(d.fields.get("outIndex").is_none()); + d.fields.insert("side1".into(), json!(1)); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(points(&app, id)[3], (0.5000015, 0.2, 0.6)); +} + +#[test] +fn ok_sets_both_halves_of_a_discontinuous_point_in_one_step() { + let (mut app, id) = pair_app(); + let before = app.session.doc().unwrap().doc.clone(); + let history = creation_history(&app); + // Cancel after edits changes nothing. + app.run("ui.widthPointEdit", json!({"id": id, "index": 2})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("outSide1".into(), json!(9)); + super::super::cancel(&mut app); + assert_eq!(app.session.doc().unwrap().doc, before); + assert_eq!(creation_history(&app), history); + app.run("ui.widthPointEdit", json!({"id": id, "index": 2})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + for (key, value) in [("side1", 6), ("side2", 2), ("outSide1", 1), ("outSide2", 3)] { + d.fields.insert(key.into(), json!(value)); + } + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(points(&app, id), vec![(0.0, 1.0, 1.0), (0.5, 1.2, 0.4), (0.5, 0.2, 0.6), (1.0, 1.0, 1.0)]); + assert_eq!(creation_history(&app), (history.0 + 1, 0, true)); + let after = app.session.doc().unwrap().doc.clone(); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.doc().unwrap().doc, before); + app.run("edit.redo", json!({})).unwrap(); + assert_eq!(app.session.doc().unwrap().doc, after); + // OK with nothing changed records no undo step. + app.run("ui.widthPointEdit", json!({"id": id, "index": 1})).unwrap(); + super::super::confirm(&mut app).unwrap(); + assert_eq!(creation_history(&app), (history.0 + 1, 0, true)); +} + +#[test] +fn delete_removes_both_halves_of_a_discontinuous_point() { + let (mut app, id) = pair_app(); + let before = app.session.doc().unwrap().doc.clone(); + let history = creation_history(&app); + app.run("ui.widthPointEdit", json!({"id": id, "index": 1})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("discard".into(), json!(true)); + super::super::confirm(&mut app).unwrap(); + assert_eq!(points(&app, id), vec![(0.0, 1.0, 1.0), (1.0, 1.0, 1.0)]); + assert_eq!(creation_history(&app).0, history.0 + 1); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.doc().unwrap().doc, before); +} + +/// Click the last visible text `label` in the dialog (a radio after a heading of the same name). +fn click_last(app: &mut VectorcraftApp, ctx: &egui::Context, label: &str) { + for _ in 0..4 { + creation_dialog_frame(app, ctx, vec![]); + } + let texts = creation_dialog_frame(app, ctx, vec![]); + let pos = texts.iter().rev().find(|(text, _)| text == label).unwrap_or_else(|| panic!("missing visible control {label}: {texts:?}")).1.center(); + for pressed in [true, false] { + let button = egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + creation_dialog_frame(app, ctx, vec![egui::Event::PointerMoved(pos), button]); + } + creation_dialog_frame(app, ctx, vec![]); +} + +#[test] +fn single_width_only_keeps_the_chosen_half_as_one_point() { + for (choice, kept) in [("Incoming", (0.8, 0.8)), ("Outgoing", (0.4, 1.2))] { + let (mut app, id) = pair_app(); + let before = app.session.doc().unwrap().doc.clone(); + let history = creation_history(&app); + app.run("ui.widthPointEdit", json!({"id": id, "index": 1})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + crate::theme::apply(&ctx, Default::default()); + click_last(&mut app, &ctx, choice); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("single"), choice.to_lowercase()); + click_last(&mut app, &ctx, "OK"); + assert!(app.ui.dialog.is_none()); + assert_eq!(points(&app, id), vec![(0.0, 1.0, 1.0), (0.5, kept.0, kept.1), (1.0, 1.0, 1.0)], "{choice}"); + assert_eq!(creation_history(&app), (history.0 + 1, 0, true)); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.doc().unwrap().doc, before); + } +} + +#[test] +fn a_compound_member_edits_both_halves_of_its_owners_point() { + let (mut app, line) = app(); + let second = app.run("shape.line", json!({"x1": 320, "y1": 50, "x2": 320, "y2": 250})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [line, second]})).unwrap(); + let owner = app.run("object.compoundPath.make", json!({})).unwrap()["id"].as_u64().unwrap(); + app.run("stroke.widthProfile.set", json!({"ids": [owner], "points": [[0, 1, 1], [0.5, 0.8, 0.8], [0.5, 0.4, 1.2], [1, 1, 1]]})).unwrap(); + app.run("ui.widthPointEdit", json!({"id": second, "index": 2})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + assert_eq!(d.fields["id"], json!(owner)); + d.fields.insert("adjustAdjoining".into(), json!(true)); + d.fields.insert("side1".into(), json!(8)); + d.fields.insert("outSide2".into(), json!(3)); + super::super::confirm(&mut app).unwrap(); + // The incoming change (Side 1 doubled) doubles the start's Side 1; the outgoing one (Side 2 + // halved) halves the end's Side 2. + assert_eq!(points(&app, owner), vec![(0.0, 2.0, 1.0), (0.5, 1.6, 0.8), (0.5, 0.4, 0.6), (1.0, 1.0, 0.5)]); +} 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/edit_toolbar/tests.rs b/crates/ui-egui/src/edit_toolbar/tests.rs index b13eb02120..17d605936a 100644 --- a/crates/ui-egui/src/edit_toolbar/tests.rs +++ b/crates/ui-egui/src/edit_toolbar/tests.rs @@ -207,7 +207,7 @@ fn the_commands_add_move_remove_and_reset_tools() { assert_eq!(slots(&app)[2], ["slice"]); let ellipse = slot_of(&app, "ellipse").unwrap(); app.run("toolbar.addTool", json!({"tool": "star", "slot": ellipse, "place": "group"})).unwrap(); - assert_eq!(slots(&app)[ellipse], ["ellipse", "star"]); + assert_eq!(slots(&app)[ellipse], ["ellipse", "circle", "star"]); assert!(!slots(&app)[slot_of(&app, "rectangle").unwrap()].contains(&"star")); // Onto its own group: nothing changes. let before = slots(&app); @@ -217,7 +217,7 @@ fn the_commands_add_move_remove_and_reset_tools() { assert_eq!(crate::toolbar::slots(&app)[0].0, Some("Select")); // Out: one tool, or its whole group; an emptied slot goes. app.run("toolbar.removeTool", json!({"tool": "ellipse"})).unwrap(); - assert_eq!(slots(&app)[ellipse], ["star"]); + assert_eq!(slots(&app)[ellipse], ["circle", "star"]); app.run("toolbar.removeTool", json!({"tool": "addAnchor", "group": true})).unwrap(); assert!(slot_of(&app, "pen").is_none() && slot_of(&app, "addAnchor").is_none()); // Bad params change nothing. @@ -398,7 +398,7 @@ fn tools_drag_between_the_drawer_and_the_toolbar() { let drawer = drawer_rect(&ctx).unwrap(); let (slice, _) = cell_at(&shown, drawer, "Slice Tool"); drag(&mut app, &ctx, 2.0, slice, tools[ellipse].center()); - assert_eq!(slots(&app)[ellipse], ["ellipse", "slice"]); + assert_eq!(slots(&app)[ellipse], ["ellipse", "circle", "slice"]); // A dimmed tool (in the toolbar already) doesn't drag. let before = slots(&app); let shown = frame(&mut app, &ctx, 2.9, vec![]); 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 499446d4f0..855bc3a3f4 100644 --- a/crates/ui-egui/src/font_menu.rs +++ b/crates/ui-egui/src/font_menu.rs @@ -13,9 +13,12 @@ //! they look to it ([`vectorcraft_text::FontDb::similar_families`]), that family first and without the Recent //! Fonts section, until the ≈ chip under the filters clears it or the menu closes. The Font //! Technology filter's Variable lists only variable font families. Preferences › Type › Enable -//! in-menu font previews and Font Preview Size turn the samples off or size the rows. The menu lays -//! out its filters on the same five rows wherever it opens. However narrow its field, it opens at -//! least wide enough for those rows and for a family name up to 220 points wide with its sample +//! in-menu font previews and Font Preview Size turn the samples off or size the rows. While the +//! samples are shown, a row under the filters sets Font Preview Size to Small, Medium or Large +//! ([`apply_preview_size`]), which sizes the rows of every font menu, and the list stays on the +//! rows it showed. The menu lays out its filters on the same five rows wherever it opens, with the +//! size row under them while the samples are shown. However narrow its field, it opens at least +//! wide enough for those rows and for a family name up to 220 points wide with its sample //! beside it, up to 60% of the window; each sample fills its row's height. Recently used families //! appear first, in the order they were last applied, within the same search and filters as the //! remaining families. In the Character and Properties panels and the Control bar, @@ -185,11 +188,7 @@ impl Default for MenuLook<'static> { impl<'a> MenuLook<'a> { pub fn of(app: &'a VectorcraftApp) -> Self { - let row = match app.session.prefs.font_preview_size.as_str() { - "small" => 20.0, - "large" => 32.0, - _ => ROW, - }; + let row = preview_row(&app.session.prefs.font_preview_size); Self { samples: app.session.prefs.font_preview, on_white: app.session.prefs.font_samples_on_white, @@ -211,6 +210,22 @@ impl<'a> MenuLook<'a> { /// Height of a row, in points (Font Preview Size: Medium). const ROW: f32 = 24.0; +/// Font Preview Size's values (Preferences › Type), each with the row height it gives. +const PREVIEW_SIZES: [(&str, f32); 3] = [("small", 20.0), ("medium", ROW), ("large", 32.0)]; + +/// The row height of Font Preview Size `size`: Medium's for a value it does not have. +fn preview_row(size: &str) -> f32 { + PREVIEW_SIZES.iter().find(|(key, _)| *key == size).map_or(ROW, |(_, row)| *row) +} + +/// The label of Font Preview Size `size`, as Preferences names it. +fn preview_size_label(size: &str) -> &'static str { + match size { + "small" => tl!("Small"), + "large" => tl!("Large"), + _ => tl!("Medium"), + } +} /// Width of the star at the end of a family's row. const STAR: f32 = 18.0; /// Width of the Show Similar Fonts button before the star. @@ -453,6 +468,9 @@ struct MenuState { header: f32, /// The width of the widest row of filters without wrapping, last frame. filters: f32, + /// The rows' height last frame, and how far down the list its view began, in rows. At a new + /// height (Font Preview Size) the list scrolls back to the same row. + scrolled: Option<(f32, f32)>, /// The families the wheel steps through, listed at its first notch over the closed field and /// kept for that text selection while the pointer stays on it: each step makes its family a recent one, which would /// otherwise move it in the order. The Document filter's families are kept the same way: a @@ -500,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. @@ -531,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() } @@ -1307,7 +1333,7 @@ fn header<'s>(ui: &mut Ui, db: &'s vectorcraft_text::FontDb, state_id: egui::Id, ui.memory_mut(|m| m.request_focus(field.with("edit"))); } let query = widgets::search_field(ui, field, tl!("Search")).to_lowercase(); - let refilter = filters(ui, st, &t, look.document.is_some()); + let refilter = filters(ui, st, &t, look.document.is_some(), look.samples.then_some(look.row)); let added = added_families(db, st, look); // On the system clock, the list is drawn again when a family's 30 days end. if let (Some(at), None) = (added.as_ref().and_then(|a| a.recheck_at), look.clock) @@ -1440,9 +1466,11 @@ fn filter_rows() -> [Vec; 5] { } /// The filters on their rows ([`filter_rows`]): a row wraps only where the menu is narrower than -/// it. The Document filter is unavailable without a `document`. Records in `st` the width of the -/// widest row unwrapped; whether a filter changed. -fn filters(ui: &mut Ui, st: &mut MenuState, t: &Tokens, document: bool) -> bool { +/// it. The Document filter is unavailable without a `document`. With `row` (the rows' height while +/// samples are shown), a row under them offers Font Preview Size's values, the one of that height +/// selected; a click on one asks for it ([`apply_preview_size`]). Records in `st` the width of the +/// widest row unwrapped, the size row included; whether a filter changed. +fn filters(ui: &mut Ui, st: &mut MenuState, t: &Tokens, document: bool, row: Option) -> bool { let mut refilter = false; let mut widest = 0.0_f32; for row in filter_rows() { @@ -1492,6 +1520,31 @@ fn filters(ui: &mut Ui, st: &mut MenuState, t: &Tokens, document: bool) -> bool widest = widest.max(width); }); } + if let Some(row) = row { + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing = vec2(4.0, 2.0); + let gap = ui.spacing().item_spacing.x; + let text = |s: &str| egui::RichText::new(s).size(FILTER_SIZE); + let mut width = ui.label(text(tl!("Font Preview Size")).color(t.text_dim)).rect.width(); + // Screen readers find the three sizes in a radio group named after the row. + let group = egui::UiBuilder::new().accessibility_role(egui::accesskit::Role::RadioGroup).accessibility_label(tl!("Font Preview Size")); + ui.scope_builder(group, |ui| { + for (size, height) in PREVIEW_SIZES { + let on = (height - row).abs() < 0.5; + let label = preview_size_label(size); + let resp = ui.selectable_label(on, text(label)); + resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::RadioButton, true, on, label)); + width += gap + resp.rect.width(); + if resp.clicked() { + ui.data_mut(|d| d.insert_temp(preview_size_id(), size)); + // A focused button is activated by Enter; the list must not read it as a pick. + ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter)); + } + } + }); + widest = widest.max(width); + }); + } st.filters = widest; // While Show Similar Fonts orders the list: the family it orders by, which clears it. Its // width is left out of the widest row: a long name wraps instead of widening the menu. @@ -1679,8 +1732,16 @@ fn rows(ui: &mut Ui, range: std::ops::Range, h: Listed<'_>, sample: Optio let place = egui::Rect::from_min_size(egui::pos2(left, top + i as f32 * row_h), vec2(width, row_h)); ui.scroll_to_rect_animation(place, align, egui::style::ScrollAnimation::none()); }; + // At a new row height (Font Preview Size, set from the menu), the view stays on the rows it + // showed: the scroll offset is in points. + let at = (ui.clip_rect().top() - top) / row_h; + let kept = st.scrolled.filter(|&(h, _)| !opening && (h - row_h).abs() > 0.5).map(|(_, at)| at); + st.scrolled = Some((row_h, kept.unwrap_or(at))); if let Some((i, align)) = scroll_target(st, &rows, opening, keyed) { scroll_to(ui, i, align); + } else if let Some(at) = kept { + let place = egui::Rect::from_min_size(egui::pos2(left, top + at * row_h), vec2(width, row_h)); + ui.scroll_to_rect_animation(place, Some(egui::Align::TOP), egui::style::ScrollAnimation::none()); } let mut chosen: Option<(String, Option)> = None; let mut hovered: Option = None; @@ -2027,6 +2088,31 @@ fn open_id() -> egui::Id { egui::Id::unique("font-menu-open") } +/// The id under which a font menu keeps the Font Preview Size its buttons asked for, until +/// [`apply_preview_size`] sets it. +fn preview_size_id() -> egui::Id { + egui::Id::unique("font-menu-preview-size") +} + +/// Set the Font Preview Size (Preferences › Type) that a font menu's Small, Medium or Large button +/// asked for in the last pass, which sizes the rows of every font menu, and have the host write the +/// preferences file as it does when Preferences is confirmed. Nothing runs when it is already that +/// size; a saved value that is none of the sizes is replaced. The shell calls it at the start of +/// each frame. +pub(crate) fn apply_preview_size(app: &mut VectorcraftApp, ctx: &egui::Context) { + let Some(size) = ctx.data_mut(|d| d.remove_temp::<&'static str>(preview_size_id())) else { return }; + if app.session.prefs.font_preview_size == size { + return; + } + match app.run("prefs.set", json!({"key": "fontPreviewSize", "value": size})) { + Ok(_) => { + crate::prefs_dialog::snapshot(app); + app.prefs_changed = true; + } + Err(e) => app.ui.status = e, + } +} + /// Undo a preview whose menu is gone (its panel wasn't drawn: the text was deselected, the panel /// closed) or is closing (Escape, a press outside the menu), before anything else sees this /// frame's input: the canvas must not act inside the preview's interaction (a drag would be diff --git a/crates/ui-egui/src/font_menu/tests.rs b/crates/ui-egui/src/font_menu/tests.rs index 958a6c1af1..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] @@ -1468,3 +1520,212 @@ fn the_recently_added_filter_lists_a_font_installed_just_now() { assert!(st.rows.is_empty(), "31 days later: {:?}", st.rows); std::fs::remove_dir_all(&dir).unwrap(); } + +/// While the samples are shown, a row under the filters offers Font Preview Size's Small, Medium +/// and Large at every size of the rows: a click on one asks for that size ([`super::apply_preview_size`] +/// leaves the rows' own size as it is). Without samples the row is not drawn. +#[test] +fn the_preview_size_row_asks_for_the_size_clicked() { + // The bundled fonts alone: fonts that tests running alongside add stay out of the rows. + let db = vectorcraft_text::FontDb::with_font_dirs(vec![]); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut st = super::MenuState::default(); + for size in ["small", "medium", "large"] { + let look = super::MenuLook { row: super::preview_row(size), ..Default::default() }; + let shapes = settle_menu_of(&ctx, &db, &mut st, look, vec![]); + assert!(text_at(&shapes, |t| t == "Font Preview Size").is_some(), "the row is drawn at {size}"); + let mut click = |label: &str| { + let shapes = settle_menu_of(&ctx, &db, &mut st, look, vec![]); + let at = text_at(&shapes, |t| t == label).unwrap_or_else(|| panic!("{label} is drawn at {size}")); + let button = + |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + settle_menu_of(&ctx, &db, &mut st, look, vec![egui::Event::PointerMoved(at), button(true)]); + settle_menu_of(&ctx, &db, &mut st, look, vec![button(false)]); + ctx.data_mut(|d| d.remove_temp::<&'static str>(super::preview_size_id())) + }; + assert_eq!(click("Large"), Some("large"), "at {size}"); + assert_eq!(click("Small"), Some("small"), "at {size}"); + assert_eq!(click("Medium"), Some("medium"), "at {size}"); + } + let look = super::MenuLook { row: super::preview_row("medium"), ..Default::default() }; + let shapes = settle_menu_of(&ctx, &db, &mut st, super::MenuLook { samples: false, ..look }, vec![]); + assert!(text_at(&shapes, |t| t == "Font Preview Size").is_none(), "without samples the row is not drawn"); + super::wait_for_samples(&ctx); +} + +/// Enter on a focused size button asks for that size and picks no font: the key is not also read as +/// the list's Enter, which would apply the highlighted font and close the menu. +#[test] +fn enter_on_a_focused_size_button_picks_no_font() { + let db = vectorcraft_text::FontDb::with_font_dirs(vec![]); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + // The Recently Added filter gives the list rows from the bundled fonts alone. + let mut st = super::MenuState { added_only: true, added: added_in(&db, &["Source Serif 4", "Inter"], None), ..Default::default() }; + let id = egui::Id::unique("size-enter"); + let look = super::MenuLook { row: super::preview_row("small"), clock: Some(clock()), ..Default::default() }; + let area = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 900.0)); + let frame = |st: &mut super::MenuState, events: Vec| { + let mut pick = None; + let mut out = ctx.run_ui(egui::RawInput { events, screen_rect: Some(area), ..Default::default() }, |ui| { + pick = super::list_of(ui, &db, id, st, "Inter", None, look).inner; + }); + out.textures_delta.clear(); + (out.shapes, pick) + }; + frame(&mut st, vec![]); + let (shapes, _) = frame(&mut st, vec![]); + let at = text_at(&shapes, |t| t == "Large").expect("Large is drawn"); + let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(&mut st, vec![egui::Event::PointerMoved(at), button(true)]); + frame(&mut st, vec![button(false)]); + ctx.data_mut(|d| d.remove_temp::<&'static str>(super::preview_size_id())); + let enter = |pressed| egui::Event::Key { + key: egui::Key::Enter, + physical_key: Some(egui::Key::Enter), + pressed, + repeat: false, + modifiers: Default::default(), + }; + let tab = + |pressed| egui::Event::Key { key: egui::Key::Tab, physical_key: Some(egui::Key::Tab), pressed, repeat: false, modifiers: Default::default() }; + assert!(!listed_families(&st).is_empty(), "the list has rows an Enter could pick"); + // Tab moves the focus along the controls until it is on the Large button, where Enter is pressed. + let mut found = None; + for _ in 0..60 { + frame(&mut st, vec![tab(true)]); + frame(&mut st, vec![tab(false)]); + let on_large = ctx.memory(|m| m.focused()).and_then(|f| ctx.read_response(f)).is_some_and(|r| r.rect.contains(at)); + if !on_large { + continue; + } + let (_, pick) = frame(&mut st, vec![enter(true)]); + frame(&mut st, vec![enter(false)]); + if ctx.data_mut(|d| d.remove_temp::<&'static str>(super::preview_size_id())) == Some("large") { + found = Some(pick); + break; + } + } + let pick = found.expect("Enter on the focused Large button asks for the size"); + assert!(pick.is_none(), "Enter on the size button picks no font: {pick:?}"); + super::wait_for_samples(&ctx); +} + +/// The size a font menu's button asked for becomes Font Preview Size, which sizes every font +/// menu's rows, and the host is asked to write the preferences file. The document is left as it +/// was: a font previewed on the selected type stays previewed, and the change adds no undo step. +#[test] +fn a_preview_size_asked_for_sets_the_preference_and_keeps_the_preview() { + let ctx = egui::Context::default(); + let mut app = app_with_type(&[]); + let id = app.run("text.create", serde_json::json!({"x": 20, "y": 90, "text": "Size", "font": "Inter"})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", serde_json::json!({"ids": [id]})).unwrap(); + let font = |app: &crate::VectorcraftApp| match &app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().kind { + vectorcraft_doc::NodeKind::Text(t) => t.first_style().font_family, + _ => String::new(), + }; + super::apply(&mut app, &ctx, super::FontPick::Preview("Source Serif 4".into(), None)); + assert_eq!(font(&app), "Source Serif 4"); + assert_eq!(super::MenuLook::of(&app).row, super::preview_row("medium")); + assert!(!app.take_prefs_changed(), "nothing to write yet"); + let undo_depth = |app: &crate::VectorcraftApp| app.session.doc().unwrap().history.undo.len(); + let depth = undo_depth(&app); + // The rows' own size: nothing changes. + ctx.data_mut(|d| d.insert_temp(super::preview_size_id(), "medium")); + super::apply_preview_size(&mut app, &ctx); + assert_eq!(app.session.prefs.font_preview_size, "medium"); + assert!(!app.take_prefs_changed(), "nothing to write for the size the rows have"); + ctx.data_mut(|d| d.insert_temp(super::preview_size_id(), "large")); + super::apply_preview_size(&mut app, &ctx); + assert_eq!(app.session.prefs.font_preview_size, "large"); + assert_eq!(undo_depth(&app), depth, "the size is not an undo step"); + assert_eq!(super::MenuLook::of(&app).row, super::preview_row("large")); + assert!(app.take_prefs_changed(), "the host is asked to write the preferences file"); + assert_eq!(app.ui.engine_prefs["fontPreviewSize"], "large"); + assert!(app.session.in_interaction(), "the preview is still open"); + assert_eq!(font(&app), "Source Serif 4", "the preview stays on the type"); + // Asked for once, applied once. + super::apply_preview_size(&mut app, &ctx); + assert_eq!(app.session.prefs.font_preview_size, "large"); + assert!(!app.take_prefs_changed(), "nothing more to write"); + // A saved value that is none of the sizes draws Medium's rows, and Medium replaces it. + app.session.prefs.font_preview_size = "huge".into(); + assert_eq!(super::MenuLook::of(&app).row, super::preview_row("medium")); + ctx.data_mut(|d| d.insert_temp(super::preview_size_id(), "medium")); + super::apply_preview_size(&mut app, &ctx); + assert_eq!(app.session.prefs.font_preview_size, "medium"); + assert!(app.take_prefs_changed(), "the replaced value is written"); + super::apply(&mut app, &ctx, super::FontPick::EndPreview); + assert_eq!(font(&app), "Inter"); + app.run("edit.undo", serde_json::json!({})).unwrap(); + assert!( + app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).is_none(), + "undo takes the type away: no step was added for the size" + ); +} + +/// Screen readers find Small, Medium and Large as radio buttons in a group named Font Preview +/// Size, with the size of the rows chosen. +#[test] +fn the_preview_size_row_is_a_radio_group_showing_the_size() { + use crate::widgets::accessibility_tests::{named, role_and_state, tree}; + use egui::accesskit::{Role, Toggled}; + // The bundled fonts alone: fonts that tests running alongside add stay out of the rows. + let db = vectorcraft_text::FontDb::with_font_dirs(vec![]); + let sizes = ["small", "medium", "large"]; + for size in sizes { + let mut st = super::MenuState::default(); + let look = super::MenuLook { row: super::preview_row(size), ..Default::default() }; + let nodes = tree(|ui| { + let _ = super::list_of(ui, &db, egui::Id::unique("size-group"), &mut st, "Inter", None, look); + }); + assert_eq!(named(&nodes, "Font Preview Size").role(), Role::RadioGroup, "at {size}"); + for other in sizes { + let chosen = if other == size { Toggled::True } else { Toggled::False }; + assert_eq!(role_and_state(&nodes, super::preview_size_label(other)), (Role::RadioButton, Some(chosen)), "{other} at {size}"); + } + } +} + +/// A new Font Preview Size chosen in the open menu keeps the list on the rows it showed: the +/// view starts the same number of rows down at the new height, not the same number of points. +#[test] +fn a_new_preview_size_keeps_the_list_on_its_rows() { + // The bundled fonts alone: fonts that tests running alongside add stay out of the rows. + let db = vectorcraft_text::FontDb::with_font_dirs(vec![]); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut st = super::MenuState::default(); + // One frame `height` points high at `size`: the list's offset, top, view height and content height. + let frame = |height: f32, size: &str, st: &mut super::MenuState| { + let area = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, height)); + let look = super::MenuLook { row: super::preview_row(size), ..Default::default() }; + let mut shown = None; + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(area), ..Default::default() }, |ui| { + let mut child = ui.new_child(egui::UiBuilder::new().max_rect(area)); + // Opening on the last family scrolls the list to its end. + let list = super::list_of(&mut child, &db, egui::Id::unique("keep-rows"), st, "Source Serif 4", None, look); + shown = Some((list.state.clamped_offset().y, list.inner_rect.top(), list.inner_rect.height(), list.content_size.y)); + }); + out.textures_delta.clear(); + shown.unwrap_or_else(|| panic!("the list was not drawn")) + }; + let (_, top, _, _) = frame(900.0, "medium", &mut st); + // A fresh opening, with room for fewer rows than the list holds. + let mut st = super::MenuState::default(); + let mut medium = (0.0, 0.0, 0.0, 0.0); + for _ in 0..4 { + medium = frame(top + 64.0, "medium", &mut st); + } + let (offset, _, view, content) = medium; + assert!(content > view + 0.5 && offset > 0.5, "the list is scrolled: {medium:?}"); + let rows_down = offset / super::preview_row("medium"); + let mut large = (0.0, 0.0, 0.0, 0.0); + for _ in 0..3 { + large = frame(top + 64.0, "large", &mut st); + } + let expected = rows_down * super::preview_row("large"); + assert!((large.0 - expected).abs() < 0.5, "the view starts {rows_down} rows down: offset {} for {expected}", large.0); + super::wait_for_samples(&ctx); +} 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 ef34a8547d..3d788ab0f8 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -127,8 +127,12 @@ Add to Swatches Добавяне към образци Add Used Colors Добавяне на използваните цветове Additional Plug-ins Folder Допълнителна папка за плъгини + Plug-in Instruction Budget Бюджет на инструкции за плъгини Additional Fonts Folder Допълнителна папка за шрифтове Adjust Adjoining Width Points Регулиране на прилежащите точки за ширина + Incoming Входяща + Outgoing Изходяща + Single Width Only Само една ширина Adjust Color Balance… Коригиране на цветовия баланс… Adjust Colors Коригиране на цветовете Adjust Options: Параметри на коригиране: @@ -475,6 +479,8 @@ font-technology Variable Променливи Choose a folder Избор на папка Choose… Избор… Circle Кръг + Circle Tool Инструмент Кръг + Circle too large Кръгът е твърде голям Classic Defaults Класически по подразбиране Clean Up… Почистване… Clear Изчистване @@ -856,6 +862,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 Отхвърляне на празен текст @@ -1229,6 +1236,8 @@ font-technology Variable Променливи Files Файлове Files of a PDF standard can't be password-protected. Файлове от PDF стандарт не могат да бъдат защитени с парола. Files of this standard tag their colours with ICC profiles. Файловете от този стандарт етикетират цветовете си с ICC профили. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Файловете от този стандарт етикетират цветовете си с ICC профили, с изключение на CMYK цветовете в профила на предназначението на изхода, които се записват като DeviceCMYK. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. С „Без включване на профили“ и CMYK предназначение на изхода всеки CMYK цвят се записва като DeviceCMYK, освен ако не се преобразува към CMYK местоназначение с друг профил. Fill Запълване Fill & Stroke Запълване и щрих Fill (X), double-click for the Color Picker Запълване (X), щракнете двукратно за избор на цвят @@ -1970,6 +1979,7 @@ font-technology Variable Променливи Load SVG into Clipboard Зареждане на SVG в клипборда Load Text into Clipboard Зареждане на текст в клипборда Local Libraries Локални библиотеки + Locate Layer Намиране на слой Locate Object Намиране на обект Locate Selected Objects Намиране на избраните обекти Location Местоположение @@ -2164,6 +2174,7 @@ font-technology Variable Променливи Scatter: Разпръскване: Rotation: Завъртане: Rotation relative to: Завъртане спрямо: + Hue Jitter: Вариация на оттенъка: Brush Scale Options Опции за мащабиране на четката Scale Proportionately Мащабиране пропорционално Stretch to Fit Stroke Length Разтягане за запълване дължината на щриха @@ -2200,6 +2211,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 Натиск @@ -2626,6 +2638,10 @@ font-technology Variable Променливи Polar Grid Tool Инструмент „Полярна мрежа“ Polygon Многоъгълник Polygon Properties: Свойства на многоъгълника: + Line Properties: Свойства на линията: + Line Length: Дължина на линията: + Line Angle: Ъгъл на линията: + Constrain Pie Angle Запазване на ъгъла на сектора Polygon Tool Инструмент „Многоъгълник“ Portrait Портретна Power Saving (integrated) Пестене на енергия (интегрирано) @@ -2785,6 +2801,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. Системата съгласува цветовете на прозореца с дисплея. @@ -3045,6 +3062,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. „Създаване на режещи знаци“ рисува знаци в японски стил вместо в римски. @@ -3342,6 +3360,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 Последни команди @@ -3422,6 +3443,7 @@ digits Malayalam Малаялам Set Slice Rectangle Задаване на правоъгълник за резен Set Tab Stops Задаване на табулатори Set Text Задаване на текст + Set the current fill or stroke to the selected color Задаване на избрания цвят като текущо запълване или щрих Set the selected color to the current color Задаване на текущия цвят като избран Set Zoom Задаване на мащаб Settings… Настройки… @@ -3543,7 +3565,7 @@ digits Malayalam Малаялам Show Vivid/Muted Показване на ярки/заглушени Show Warm/Cool Показване на топли/студени Show {kind} Brushes Показване на четки от вида {kind} - Show/hide plate (Alt-click: only this plate) Показване/скриване на плака (Alt-клик: само тази плака) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Показване/скриване на плака (Alt-клик: само тази плака; Alt-клик отново: всички плаки) Show: Показване: Shown with the optimised preview. Показано с оптимизирания преглед. Side 1: Страна 1: @@ -4111,6 +4133,8 @@ digits Malayalam Малаялам V Spacing: В. разстояние: V: В: Variable Width Profile Профил с променлива ширина + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Четката на щриха запазва собствения си размер, затова профилът на ширината не го променя. Премахнете четката, за да използвате профил. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Четката на щриха запазва собствения си размер, затова профилът на ширината не го променя. Премахнете четката, за да използвате профил. Variables Променливи New Variable Нова променлива Delete Variable Изтриване на променлива @@ -4384,6 +4408,7 @@ imageTrace Outline Контур Bevel Фаска Offset Отстъп Axis Ос + Axis Angle Ъгъл на оста axis Horizontal Хоризонтално axis Vertical Вертикално axis Both И двете @@ -4812,6 +4837,9 @@ axis Both И двете @msg no such user library няма такава потребителска библиотека @msg no such view няма такъв изглед @msg no such width point няма такава точка за ширина +@msg `single` must be `incoming` or `outgoing` `single` трябва да е `incoming` или `outgoing` +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` и `outIndex` трябва да са двете половини на една прекъсната точка за ширина +@msg a discontinuous width point keeps its place прекъснатата точка за ширина запазва мястото си @msg no swatch `{name}` няма образец `{name}` @msg no swatch library `{l}` (see swatch.library.list) няма библиотека с образци `{l}` (вижте swatch.library.list) @msg no symbol instances selected няма избрани екземпляри на символ @@ -5514,6 +5542,7 @@ lighting Light Светлина Cove Извивка Depth Дълбочина Front Отпред + Side Страна Isometric Bottom Изометрично отдолу Isometric Left Изометрично отляво Isometric Right Изометрично отдясно @@ -6977,6 +7006,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 b94c1adf82..7c77de7661 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 @@ -1752,6 +1753,7 @@ digits Malayalam Malajalam Rule: Pravilo: Save changes to {name} Sačuvaj promjene u {name} Save theme to My Themes Sačuvaj temu u Moje teme + Set the current fill or stroke to the selected color Postavi odabranu boju kao trenutnu ispunu ili potez Set the selected color to the current color Postavi odabranu boju na trenutnu boju Copy All Styles Kopiraj sve stilove Exported {path} Izvezeno: {path} @@ -2214,7 +2216,7 @@ digits Malayalam Malajalam Overprint Preview (separations) Pregled pretiska (separacije) Show All Plates Prikaži sve ploče Show all plates Prikaži sve ploče - Show/hide plate (Alt-click: only this plate) Prikaži/sakrij ploču (Alt-klik: samo ova ploča) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Prikaži/sakrij ploču (Alt-klik: samo ova ploča; ponovni Alt-klik: sve ploče) Simulate Paper Simuliraj papir Use Black Point Compensation Koristi kompenzaciju crne tačke Working CMYK (don't tag) Radni CMYK (bez oznake) @@ -2254,6 +2256,8 @@ digits Malayalam Malajalam Tip extends past the end point Vrh prelazi preko krajnje tačke Tip on the end point Vrh na krajnjoj tački Variable Width Profile Profil promjenjive širine + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Četkica poteza zadržava vlastitu veličinu, pa je profil širine ne mijenja. Uklonite četkicu da biste koristili profil. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Četkica poteza zadržava vlastitu veličinu, pa je profil širine ne mijenja. Uklonite četkicu da biste koristili profil. Weight: Debljina: Art using a deleted global swatch keeps its colour. Crtež koji koristi izbrisani globalni uzorak boje zadržava svoju boju. Color Group: {name} Grupa boja: {name} @@ -2363,6 +2367,10 @@ digits Malayalam Malajalam Flip Horizontal Preokreni vodoravno Flip Vertical Preokreni okomito Polygon Properties: Svojstva mnogougla: + 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 @@ -2404,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 @@ -2442,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: @@ -3113,6 +3123,8 @@ antiAlias Sharp Oštro Every option matches {base}. Sve opcije odgovaraju {base}. Files of a PDF standard can't be password-protected. Datoteke PDF standarda ne mogu se zaštititi lozinkom. Files of this standard tag their colours with ICC profiles. Datoteke ovog standarda označavaju svoje boje ICC profilima. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Datoteke ovog standarda označavaju svoje boje ICC profilima, osim CMYK boja u profilu izlazne namjene, koje se zapisuju kao DeviceCMYK. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. Uz „Ne uključuj profile“ i CMYK izlaznu namjenu, svaka CMYK boja zapisuje se kao DeviceCMYK, osim ako se ne pretvori u CMYK odredište s drugim profilom. Flattener preset: Predložak spljoštavanja: General › Thumbnails Općenito › Sličice Grayscale images Slike u nijansama sive @@ -3361,6 +3373,9 @@ antiAlias Sharp Oštro Variable Options Opcije varijable Define a variable first Prvo definišite varijablu Adjust Adjoining Width Points Podesi susjedne tačke širine + Incoming Ulazna + Outgoing Izlazna + Single Width Only Samo jedna širina Keep both sides the same width Zadrži obje strane iste širine Side 1: Strana 1: Side 2: Strana 2: @@ -3753,6 +3768,7 @@ theme Appearance Izgled Select Art Odaberi crtež Set Current Layer Postavi trenutni sloj Flatten Artwork Spljošti crtež + Locate Layer Pronađi sloj Locate Object Pronađi objekat Lock Others Zaključaj ostale Merge Selected Spoji odabrano @@ -3929,6 +3945,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 @@ -3955,6 +3972,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 @@ -4055,6 +4073,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. @@ -4462,6 +4481,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 @@ -4498,6 +4520,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. @@ -4594,6 +4617,8 @@ font-technology Variable Varijabilni Couldn't paste from the clipboard: {e} Nije moguće zalijepiti iz međuspremnika: {e} Channel Kanal Circle Krug + Circle Tool Alat za krug + Circle too large Krug je prevelik Clip to Art Isijeci prema crtežu Colorize Oboji Gamma Gama @@ -5224,6 +5249,9 @@ imageTrace Outline Obris @msg no such user library nema takve korisničke biblioteke @msg no such view nema takvog pogleda @msg no such width point nema takve tačke širine +@msg `single` must be `incoming` or `outgoing` `single` mora biti `incoming` ili `outgoing` +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` i `outIndex` moraju biti dvije polovine jedne isprekidane tačke širine +@msg a discontinuous width point keeps its place isprekidana tačka širine zadržava svoje mjesto @msg no swatch `{name}` nema uzorka boje `{name}` @msg no swatch library `{l}` (see swatch.library.list) nema biblioteke uzoraka boja `{l}` (vidi swatch.library.list) @msg no symbol instances selected nisu odabrane instance simbola @@ -6034,6 +6062,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 @@ -7026,6 +7055,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 fd33731ebd..4387b09a50 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -223,7 +223,11 @@ 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 + Single Width Only Només una amplada Adjust Color Balance… Ajusta l’equilibri de color… Adjust Colors Ajusta els colors Adjust Options: Opcions d’ajust: @@ -436,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 @@ -714,6 +719,8 @@ antiAlias Sharp Nítid Chrome Crom Chrome… Crom… Circle Cercle + Circle Tool Eina de cercle + Circle too large El cercle és massa gran Circle (open) Cercle (obert) Classic Clàssic Classic Defaults Valors predeterminats clàssics @@ -1259,6 +1266,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 @@ -1731,6 +1739,8 @@ digits Malayalam Malaiàlam Files Fitxers Files of a PDF standard can't be password-protected. Els fitxers d’un estàndard PDF no es poden protegir amb contrasenya. Files of this standard tag their colours with ICC profiles. Els fitxers d’aquest estàndard etiqueten els colors amb perfils ICC. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Els fitxers d’aquest estàndard etiqueten els colors amb perfils ICC, excepte els colors CMYK del perfil d’intenció de sortida, que s’escriuen com a DeviceCMYK. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. Amb «No incloguis els perfils» i una intenció de sortida CMYK, cada color CMYK s’escriu com a DeviceCMYK, tret que es converteixi a una destinació CMYK d’un altre perfil. Fill Farciment Fill & Stroke Farciment i traç Fill (X), double-click for the Color Picker Farciment (X), fes doble clic per al selector de color @@ -1883,6 +1893,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 @@ -2571,6 +2582,7 @@ digits Malayalam Malaiàlam Loads native code Carrega codi natiu Local Libraries Biblioteques locals Locate Library… Localitza la biblioteca… + Locate Layer Localitza la capa Locate Object Localitza l’objecte Locate Selected Objects Localitza els objectes seleccionats Location Ubicació @@ -3402,6 +3414,10 @@ digits Malayalam Malaiàlam Polar Grid Tool Options Opcions de l’eina de quadrícula polar Polygon Polígon Polygon Properties: Propietats del polígon: + 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) @@ -3600,6 +3616,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. @@ -3885,6 +3904,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. @@ -4025,6 +4045,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 @@ -4045,6 +4066,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 @@ -4281,6 +4303,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 @@ -4448,6 +4473,7 @@ digits Malayalam Malaiàlam Set Slice Rectangle Defineix el rectangle del tall Set Tab Stops Defineix les tabulacions Set Text Defineix el text + Set the current fill or stroke to the selected color Defineix el color seleccionat com a farciment o traç actual Set the selected color to the current color Defineix el color seleccionat com a color actual Set Zoom Defineix el zoom Set: Defineix: @@ -4594,7 +4620,7 @@ digits Malayalam Malaiàlam Show Vivid/Muted Mostra els vius/apagats Show Warm/Cool Mostra els càlids/freds Show {kind} Brushes Mostra els pinzells {kind} - Show/hide plate (Alt-click: only this plate) Mostra o amaga la planxa (Alt+clic: només aquesta planxa) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Mostra o amaga la planxa (Alt+clic: només aquesta planxa; Alt+clic de nou: totes les planxes) Show: Mostra: Shown with the optimised preview. Es mostra amb la previsualització optimitzada. Shrink Text to Fit Redueix el text perquè hi càpiga @@ -5377,6 +5403,8 @@ digits Malayalam Malaiàlam Variable Options Opcions de variable Variable Options… Opcions de variable… Variable Width Profile Perfil d’amplada variable + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. El pinzell del traç manté la seva pròpia mida, de manera que un perfil d’amplada no el canvia. Traieu el pinzell per fer servir un perfil. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. El pinzell del traç manté la seva pròpia mida, de manera que un perfil d’amplada no el canvia. Traieu el pinzell per fer servir un perfil. Variables Variables Variation Variació Variation: Variació: @@ -5781,6 +5809,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} @@ -6029,6 +6058,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} @@ -6258,9 +6295,15 @@ 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 three [x, y] pairs of numbers `points` han de ser tres parells de nombres [x, y] -@msg direct-select three anchor points, or give `points` seleccioneu directament tres punts d’ancoratge o indiqueu `points` +@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` @msg no circle passes through these points: two are the same or all three lie on one line cap cercle no passa per aquests punts: dos són iguals o tots tres són en una mateixa recta @msg no app to open files here aquí no hi ha cap aplicació per obrir fitxers @msg no artboard no hi ha tauler @@ -6384,6 +6427,9 @@ liquify-list-end {0}, {1} {0} i {1} @msg no such user library no existeix aquesta biblioteca d’usuari @msg no such view no existeix aquesta vista @msg no such width point no existeix aquest punt d’amplada +@msg `single` must be `incoming` or `outgoing` `single` ha de ser `incoming` o `outgoing` +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` i `outIndex` han de ser les dues meitats d’un mateix punt d’amplada discontinu +@msg a discontinuous width point keeps its place un punt d’amplada discontinu manté la seva posició @msg no swatch `{name}` no hi ha la mostra `{name}` @msg no swatch library `{l}` (see swatch.library.list) no hi ha la biblioteca de mostres `{l}` (vegeu swatch.library.list) @msg no symbol `{n}` no hi ha el símbol `{n}` @@ -6706,7 +6752,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 and Revolve object types Els gràfics s’apliquen als tipus d’objecte Pla, Extrusió i Revolució @@ -7029,6 +7075,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 @@ -7747,6 +7795,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 4c07c56aa6..90b5fe1479 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 @@ -1821,6 +1822,7 @@ digits Malayalam Malajálamské Rule: Pravidlo: Save changes to {name} Uložit změny do {name} Save theme to My Themes Uložit motiv do Mých motivů + Set the current fill or stroke to the selected color Nastavit vybranou barvu jako aktuální výplň nebo tah Set the selected color to the current color Nastavit vybranou barvu jako aktuální barvu Copy All Styles Kopírovat všechny styly Exported {path} Exportováno: {path} @@ -2285,7 +2287,7 @@ digits Malayalam Malajálamské Overprint Preview (separations) Náhled přetisků (separace) Show All Plates Zobrazit všechny desky Show all plates Zobrazit všechny desky - Show/hide plate (Alt-click: only this plate) Zobrazit/skrýt desku (Alt+kliknutí: jen tato deska) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Zobrazit/skrýt desku (Alt+kliknutí: jen tato deska; další Alt+kliknutí: všechny desky) Simulate Paper Simulovat papír Use Black Point Compensation Použít kompenzaci černého bodu Working CMYK (don't tag) Pracovní CMYK (neoznačovat) @@ -2325,6 +2327,8 @@ digits Malayalam Malajálamské Tip extends past the end point Hrot přesahuje koncový bod Tip on the end point Hrot na koncovém bodu Variable Width Profile Profil proměnné šířky + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Štětec tahu si zachovává vlastní velikost, takže ho profil šířky nemění. Chcete-li použít profil, odeberte štětec. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Štětec tahu si zachovává vlastní velikost, takže ho profil šířky nemění. Chcete-li použít profil, odeberte štětec. Weight: Tloušťka: Art using a deleted global swatch keeps its colour. Kresba, která používá odstraněnou globální položku vzorníku, si barvu ponechá. Color Group: {name} Skupina barev: {name} @@ -2434,6 +2438,10 @@ digits Malayalam Malajálamské Flip Horizontal Překlopit vodorovně Flip Vertical Překlopit svisle Polygon Properties: Vlastnosti mnohoúhelníku: + 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 @@ -2477,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 @@ -2515,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: @@ -3195,6 +3205,8 @@ antiAlias Sharp Ostré Every option matches {base}. Všechny možnosti odpovídají: {base}. Files of a PDF standard can't be password-protected. Soubory podle standardu PDF nelze chránit heslem. Files of this standard tag their colours with ICC profiles. Soubory tohoto standardu označují své barvy profily ICC. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Soubory tohoto standardu označují své barvy profily ICC, kromě barev CMYK v profilu výstupního záměru, které se zapisují jako DeviceCMYK. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. S volbou „Nezahrnovat profily“ a výstupním záměrem CMYK se každá barva CMYK zapíše jako DeviceCMYK, pokud se nepřevede do cíle CMYK s jiným profilem. Flattener preset: Přednastavení sloučení: General › Thumbnails Obecné › Miniatury Grayscale images Obrazy ve stupních šedi @@ -3449,6 +3461,9 @@ antiAlias Sharp Ostré Variable Options Možnosti proměnné Define a variable first Nejprve definujte proměnnou Adjust Adjoining Width Points Upravit sousední body šířky + Incoming Příchozí + Outgoing Odchozí + Single Width Only Pouze jedna šířka Keep both sides the same width Zachovat stejnou šířku obou stran Side 1: Strana 1: Side 2: Strana 2: @@ -3857,6 +3872,7 @@ theme Appearance Motiv Select Art Vybrat kresbu Set Current Layer Nastavit aktuální vrstvu Flatten Artwork Sloučit kresbu + Locate Layer Najít vrstvu Locate Object Najít objekt Lock Others Zamknout ostatní Merge Selected Sloučit vybrané @@ -4033,6 +4049,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 @@ -4059,6 +4076,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é @@ -4161,6 +4179,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. @@ -4568,6 +4589,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 @@ -4604,6 +4628,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. @@ -4700,6 +4725,8 @@ font-technology Variable Variabilní Couldn't paste from the clipboard: {e} Nelze vložit ze schránky: {e} Channel Kanál Circle Kruh + Circle Tool Nástroj Kruh + Circle too large Kruh je příliš velký Clip to Art Oříznout podle kresby Colorize Obarvit Gamma Gama @@ -5086,6 +5113,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} @@ -5418,9 +5453,15 @@ 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 three [x, y] pairs of numbers `points` musí být tři dvojice čísel [x, y] -@msg direct-select three anchor points, or give `points` vyberte přímým výběrem tři kotevní body, nebo zadejte `points` +@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` @msg no circle passes through these points: two are the same or all three lie on one line těmito body neprochází žádná kružnice: dva jsou stejné nebo všechny tři leží na jedné přímce @msg no app to open files here zde chybí aplikace pro otevírání souborů @msg no artboard žádná pracovní plocha @@ -5522,6 +5563,9 @@ liquify-list-end {0}, {1} {0} a {1} @msg no such user library taková uživatelská knihovna neexistuje @msg no such view takové zobrazení neexistuje @msg no such width point takový bod šířky neexistuje +@msg `single` must be `incoming` or `outgoing` `single` musí být `incoming` nebo `outgoing` +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` a `outIndex` musí být dvě poloviny jednoho nespojitého bodu šířky +@msg a discontinuous width point keeps its place nespojitý bod šířky si zachovává své místo @msg no swatch `{name}` položka vzorníku `{name}` neexistuje @msg no swatch library `{l}` (see swatch.library.list) knihovna vzorníku `{l}` neexistuje (viz swatch.library.list) @msg no symbol instances selected nejsou vybrány žádné instance symbolů @@ -5886,6 +5930,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 @@ -5976,6 +6022,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á @@ -6405,6 +6452,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 @@ -6499,7 +6547,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 and Revolve object types Grafika se mapuje na typy objektu Rovina, Vysunutí a Rotační těleso @@ -7732,6 +7780,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 @@ -8825,6 +8881,7 @@ breakText Glyphs Glyfy @msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes složené tvary přijímají cesty, složené cesty, skupiny, složené tvary, text, prolnutí a obálky @msg compound {_1} must contain exactly one open path to join složený objekt {_1} musí ke spojení obsahovat právě jednu otevřenou cestu @msg connect needs a path other than the one extended connect vyžaduje jinou cestu než tu prodlužovanou +@msg connect needs extend connect vyžaduje extend @msg connect needs id connect vyžaduje id @msg connect path has no open end cesta v connect nemá žádný otevřený konec @msg continuation must be an array of path chunks continuation musí být pole úseků cesty diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index ce35f2436b..cf96f635c3 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 and Revolve object types Grafik kortlægges på objekttyperne Plan, Ekstrudér og Omdrej @@ -1431,6 +1439,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 @@ -1636,6 +1645,7 @@ liquify-list-end {0}, {1} {0} og {1} @msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes sammensatte figurer tager kurver, sammensatte kurver, grupper, sammensatte figurer, tekst, blandinger og konvolutter @msg compound {_1} must contain exactly one open path to join sammensat {_1} skal indeholde præcis én åben kurve at sammenføje @msg connect needs a path other than the one extended connect kræver en anden kurve end den, der forlænges +@msg connect needs extend connect kræver extend @msg connect needs id connect kræver id @msg connect path has no open end connect-kurven har ingen åben ende @msg continuation must be an array of path chunks continuation skal være et array af kurvestykker @@ -4398,6 +4408,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 @@ -4440,6 +4451,7 @@ digits Malayalam Malayalam Rule: Regel: Save changes to {name} Gem ændringer i {name} Save theme to My Themes Gem tema i Mine temaer + Set the current fill or stroke to the selected color Sæt den aktuelle udfyldning eller streg til den markerede farve Set the selected color to the current color Sæt den markerede farve til den aktuelle farve Copy All Styles Kopiér alle typografier Exported {path} Eksporterede {path} @@ -4798,7 +4810,7 @@ digits Malayalam Malayalam Overprint Preview (separations) Forhåndsvisning af overtryk (separationer) Show All Plates Vis alle plader Show all plates Vis alle plader - Show/hide plate (Alt-click: only this plate) Vis/skjul plade (Alt-klik: kun denne plade) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Vis/skjul plade (Alt-klik: kun denne plade; Alt-klik igen: alle plader) Simulate Paper Simulér papir Use Black Point Compensation Brug sortpunktskompensation Working CMYK (don't tag) Arbejds-CMYK (mærk ikke) @@ -4838,6 +4850,8 @@ digits Malayalam Malayalam Tip extends past the end point Spidsen rager ud over endepunktet Tip on the end point Spidsen på endepunktet Variable Width Profile Variabel breddeprofil + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Stregens pensel beholder sin egen størrelse, så et breddeprofil ændrer den ikke. Fjern penslen for at bruge et profil. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Stregens pensel beholder sin egen størrelse, så et breddeprofil ændrer den ikke. Fjern penslen for at bruge et profil. Weight: Vægt: Art using a deleted global swatch keeps its colour. Grafik, der bruger en slettet global farveprøve, bevarer sin farve. Color Group: {name} Farvegruppe: {name} @@ -4947,6 +4961,10 @@ digits Malayalam Malayalam Flip Horizontal Spejl vandret Flip Vertical Spejl lodret Polygon Properties: Polygonegenskaber: + 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 @@ -4988,6 +5006,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 @@ -5026,6 +5045,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: @@ -5690,6 +5710,8 @@ antiAlias Sharp Skarp Every option matches {base}. Alle indstillinger matcher {base}. Files of a PDF standard can't be password-protected. Filer med en PDF-standard kan ikke beskyttes med adgangskode. Files of this standard tag their colours with ICC profiles. Filer med denne standard mærker deres farver med ICC-profiler. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Filer med denne standard mærker deres farver med ICC-profiler, undtagen CMYK-farver i outputintentens profil, som skrives som DeviceCMYK. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. Med »Medtag ikke profiler« og en CMYK-outputintent skrives alle CMYK-farver som DeviceCMYK, medmindre de konverteres til en CMYK-destination med en anden profil. Flattener preset: Forudindstilling til fladgøring: General › Thumbnails Generelt › Miniaturer Grayscale images Gråtonebilleder @@ -5908,6 +5930,9 @@ antiAlias Sharp Skarp Variable Options Indstillinger for variabel Define a variable first Definér først en variabel Adjust Adjoining Width Points Justér tilstødende breddepunkter + Incoming Indgående + Outgoing Udgående + Single Width Only Kun én bredde Keep both sides the same width Bevar samme bredde på begge sider Side 1: Side 1: Side 2: Side 2: @@ -6296,6 +6321,7 @@ theme Appearance Udseende Select Art Markér grafik Set Current Layer Angiv aktuelt lag Flatten Artwork Fladgør grafik + Locate Layer Lokalisér lag Locate Object Lokalisér objekt Lock Others Lås andre Merge Selected Flet valgte @@ -6472,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 @@ -6498,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 @@ -6586,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. @@ -6982,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 @@ -7018,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. @@ -7114,6 +7149,8 @@ font-technology Variable Variable Couldn't paste from the clipboard: {e} Kunne ikke indsætte fra udklipsholderen: {e} Channel Kanal Circle Cirkel + Circle Tool Cirkelværktøj + Circle too large Cirklen er for stor Clip to Art Beskær til grafik Colorize Farvelæg Gamma Gamma @@ -7600,8 +7637,8 @@ imageTrace Outline Kontur @msg no active document intet aktivt dokument @msg no active perspective plane intet aktivt perspektivplan @msg no anchor points selected ingen ankerpunkter er markeret -@msg `points` must be three [x, y] pairs of numbers `points` skal være tre talpar [x, y] -@msg direct-select three anchor points, or give `points` direkte markér tre ankerpunkter, eller angiv `points` +@msg `points` must be two or three [x, y] pairs of numbers `points` skal være to eller tre talpar [x, y] +@msg direct-select two or three anchor points, or give `points` direkte markér to eller tre ankerpunkter, eller angiv `points` @msg no circle passes through these points: two are the same or all three lie on one line ingen cirkel går gennem disse punkter: to er ens, eller alle tre ligger på én linje @msg no app to open files here ingen app til at åbne filer her @msg no artboard ingen tegneflade @@ -7692,6 +7729,9 @@ imageTrace Outline Kontur @msg no such user library intet sådant brugerbibliotek @msg no such view ingen sådan visning @msg no such width point intet sådant breddepunkt +@msg `single` must be `incoming` or `outgoing` `single` skal være `incoming` eller `outgoing` +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` og `outIndex` skal være de to halvdele af ét diskontinuert breddepunkt +@msg a discontinuous width point keeps its place et diskontinuert breddepunkt bevarer sin placering @msg no swatch `{name}` ingen farveprøve `{name}` @msg no swatch library `{l}` (see swatch.library.list) intet farveprøvebibliotek `{l}` (se swatch.library.list) @msg no symbol instances selected ingen symbolforekomster markeret @@ -8000,6 +8040,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 @@ -8450,6 +8492,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 @@ -9791,6 +9834,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 2f0050f935..c16fcb58e1 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -116,8 +116,12 @@ 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 + Outgoing Ausgehend + Single Width Only Nur eine Breite Adjust Color Balance… Farbbalance anpassen… Adjust Colors Farben anpassen Adjust Options: Anpassungsoptionen: @@ -470,6 +474,8 @@ font-technology Variable Variabel Choose a folder Ordner wählen Choose… Wählen… Circle Kreis + Circle Tool Kreis-Werkzeug + Circle too large Kreis zu groß Classic Defaults Klassische Standardwerte Clean Up… Aufräumen… Clear Löschen @@ -863,6 +869,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 @@ -1256,6 +1263,8 @@ font-technology Variable Variabel Files Dateien Files of a PDF standard can't be password-protected. Dateien eines PDF-Standards können nicht mit einem Kennwort geschützt werden. Files of this standard tag their colours with ICC profiles. Dateien dieses Standards kennzeichnen ihre Farben mit ICC-Profilen. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Dateien dieses Standards kennzeichnen ihre Farben mit ICC-Profilen, außer CMYK-Farben im Profil der Ausgabemethode, die als DeviceCMYK geschrieben werden. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. Mit „Profile nicht einschließen“ und einer CMYK-Ausgabemethode wird jede CMYK-Farbe als DeviceCMYK geschrieben, sofern sie nicht in ein CMYK-Ziel mit einem anderen Profil konvertiert wird. Fill Fläche Fill & Stroke Fläche und Kontur Fill (X), double-click for the Color Picker Fläche (X), Doppelklick öffnet den Farbwähler @@ -2058,6 +2067,7 @@ file-filter Templates Vorlagen Load SVG into Clipboard SVG in die Zwischenablage laden Load Text into Clipboard Text in die Zwischenablage laden Local Libraries Lokale Bibliotheken + Locate Layer Ebene ausfindig machen Locate Object Objekt ausfindig machen Locate Selected Objects Ausgewählte Objekte ausfindig machen Location Speicherort @@ -2246,6 +2256,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 @@ -2685,6 +2696,10 @@ diagnostics ui Oberfläche Polar Grid Tool Radiales-Raster-Werkzeug Polygon Polygon Polygon Properties: Polygoneigenschaften: + 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) @@ -2846,6 +2861,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. @@ -3108,6 +3126,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. @@ -3419,6 +3438,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 @@ -3499,6 +3523,7 @@ digits Malayalam Malayalam Set Slice Rectangle Slice-Rechteck festlegen Set Tab Stops Tabstopps festlegen Set Text Text festlegen + Set the current fill or stroke to the selected color Aktuelle Fläche oder Kontur auf die ausgewählte Farbe setzen Set the selected color to the current color Ausgewählte Farbe auf die aktuelle Farbe setzen Set Zoom Zoom festlegen Settings… Einstellungen… @@ -3622,7 +3647,7 @@ digits Malayalam Malayalam Show Vivid/Muted Lebhaft/Gedeckt einblenden Show Warm/Cool Warm/Kalt einblenden Show {kind} Brushes {kind}pinsel einblenden - Show/hide plate (Alt-click: only this plate) Platte ein-/ausblenden (Alt-Klick: nur diese Platte) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Platte ein-/ausblenden (Alt-Klick: nur diese Platte; erneuter Alt-Klick: alle Platten) Show: Anzeigen: Shown with the optimised preview. Wird mit der optimierten Vorschau angezeigt. Side 1: Seite 1: @@ -4211,6 +4236,8 @@ effect Points Punkte V Spacing: V-Abstand: V: V: Variable Width Profile Variables Breitenprofil + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Der Pinsel der Kontur behält seine eigene Größe, daher ändert ein Breitenprofil die Kontur nicht. Entfernen Sie den Pinsel, um ein Profil zu verwenden. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Der Pinsel der Kontur behält seine eigene Größe, daher ändert ein Breitenprofil die Kontur nicht. Entfernen Sie den Pinsel, um ein Profil zu verwenden. Variables Variablen Variation: Variation: Vector Effects Vektoreffekte @@ -4459,6 +4486,7 @@ imageTrace Outline Kontur Bevel Abgeflacht Offset Versatz Axis Achse + Axis Angle Achsenwinkel axis Horizontal Horizontal axis Vertical Vertikal axis Both Beide @@ -5020,9 +5048,15 @@ 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 three [x, y] pairs of numbers `points` muss aus drei Zahlenpaaren [x, y] bestehen -@msg direct-select three anchor points, or give `points` wählen Sie drei Ankerpunkte direkt aus oder geben Sie `points` an +@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 @msg no circle passes through these points: two are the same or all three lie on one line durch diese Punkte verläuft kein Kreis: zwei sind gleich oder alle drei liegen auf einer Linie @msg no app to open files here hier gibt es keine App zum Öffnen von Dateien @msg no artboard keine Zeichenfläche @@ -5125,6 +5159,9 @@ liquify-list-end {0}, {1} {0} und {1} @msg no such user library keine solche Benutzerbibliothek @msg no such view keine solche Ansicht @msg no such width point kein solcher Breitenpunkt +@msg `single` must be `incoming` or `outgoing` `single` muss `incoming` oder `outgoing` sein +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` und `outIndex` müssen die beiden Hälften eines unterbrochenen Breitenpunkts sein +@msg a discontinuous width point keeps its place ein unterbrochener Breitenpunkt behält seine Position @msg no swatch `{name}` kein Farbfeld `{name}` @msg no swatch library `{l}` (see swatch.library.list) keine Farbfeldbibliothek `{l}` (siehe swatch.library.list) @msg no symbol instances selected keine Symbolinstanzen ausgewählt @@ -5490,6 +5527,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 @@ -5696,6 +5735,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 @@ -5980,6 +6020,7 @@ lighting Light Licht Cove Hohlkehle Depth Tiefe Front Vorne + Side Seite Isometric Bottom Isometrisch unten Isometric Left Isometrisch links Isometric Right Isometrisch rechts @@ -6074,7 +6115,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 and Revolve object types Grafiken werden auf die Objekttypen Ebene, Extrudieren und Kreiseln abgebildet @@ -7327,6 +7368,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 @@ -7693,6 +7742,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 @@ -8507,6 +8564,7 @@ breakText Glyphs Glyphen @msg compound {_1} must contain exactly one open path to join zusammengesetzter Pfad {_1} muss genau einen offenen Pfad zum Zusammenfügen enthalten @msg connect end must be "start" or "end" connect end muss „start“ oder „end“ sein @msg connect needs a path other than the one extended connect braucht einen anderen Pfad als den verlängerten +@msg connect needs extend connect braucht extend @msg connect needs id connect braucht id @msg connect path has no open end der connect-Pfad hat kein offenes Ende @msg copy needs path: the file to copy into the document's folder copy braucht path: die Datei, die in den Ordner des Dokuments kopiert werden soll @@ -9531,6 +9589,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 8329416612..56513ece84 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -121,8 +121,12 @@ Add to Swatches Προσθήκη στα δείγματα χρωμάτων Add Used Colors Προσθήκη των χρησιμοποιημένων χρωμάτων Additional Plug-ins Folder Πρόσθετος φάκελος επεκτάσεων + Plug-in Instruction Budget Προϋπολογισμός εντολών επεκτάσεων Additional Fonts Folder Πρόσθετος φάκελος γραμματοσειρών Adjust Adjoining Width Points Ρύθμιση γειτονικών σημείων πλάτους + Incoming Εισερχόμενο + Outgoing Εξερχόμενο + Single Width Only Μόνο ένα πλάτος Adjust Color Balance… Ρύθμιση ισορροπίας χρωμάτων… Adjust Colors Ρύθμιση χρωμάτων Adjust Options: Επιλογές ρύθμισης: @@ -463,6 +467,8 @@ font-technology Variable Μεταβλητές Choose a folder Επιλογή φακέλου Choose… Επιλογή… Circle Κύκλος + Circle Tool Εργαλείο κύκλου + Circle too large Ο κύκλος είναι πολύ μεγάλος Classic Defaults Κλασικές προεπιλογές Clean Up… Εκκαθάριση… Clear Εκκαθάριση @@ -841,6 +847,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 Απόρριψη κενού κειμένου @@ -1218,6 +1225,8 @@ font-technology Variable Μεταβλητές Files Αρχεία Files of a PDF standard can't be password-protected. Τα αρχεία αυτού του προτύπου PDF δεν μπορούν να προστατεύονται με κωδικό. Files of this standard tag their colours with ICC profiles. Τα αρχεία αυτού του προτύπου χαρακτηρίζουν τα χρώματά τους με προφίλ ICC. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Τα αρχεία αυτού του προτύπου χαρακτηρίζουν τα χρώματά τους με προφίλ ICC, εκτός από τα χρώματα CMYK στο προφίλ προορισμού εξόδου, τα οποία γράφονται ως DeviceCMYK. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. Με «Να μη συμπεριληφθούν προφίλ» και προορισμό εξόδου CMYK, κάθε χρώμα CMYK γράφεται ως DeviceCMYK, εκτός αν μετατραπεί σε προορισμό CMYK άλλου προφίλ. Fill Γέμισμα Fill & Stroke Γέμισμα και περίγραμμα Fill (X), double-click for the Color Picker Γέμισμα (X), διπλό κλικ για τον επιλογέα χρώματος @@ -1931,6 +1940,7 @@ font-technology Variable Μεταβλητές Rotation: Περιστροφή: Flip: Αναστροφή: Fit Προσαρμογή + Roundness Στρογγυλότητα Roundness: Στρογγυλότητα: Fixed Σταθερό Pressure Πίεση @@ -2648,6 +2658,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} @@ -3173,6 +3191,7 @@ theme Appearance Εμφάνιση Load SVG into Clipboard Φόρτωση SVG στο πρόχειρο Load Text into Clipboard Φόρτωση κειμένου στο πρόχειρο Local Libraries Τοπικές βιβλιοθήκες + Locate Layer Εντοπισμός επιπέδου Locate Object Εντοπισμός αντικειμένου Locate Selected Objects Εντοπισμός επιλεγμένων αντικειμένων Lock (⌘2) Κλείδωμα (⌘2) @@ -3318,6 +3337,7 @@ theme Appearance Εμφάνιση Art Brush Options Επιλογές πινέλου σχεδίου Pattern Brush Options Επιλογές πινέλου μοτίβου Rotation relative to: Περιστροφή ως προς: + Hue Jitter: Διακύμανση απόχρωσης: Brush Scale Options Επιλογές κλιμάκωσης πινέλου Scale Proportionately Αναλογική κλιμάκωση Stretch to Fit Stroke Length Επέκταση για προσαρμογή στο μήκος περιγράμματος @@ -3622,6 +3642,10 @@ theme Appearance Εμφάνιση Polar Grid Tool Πολικό πλέγμα (Polar Grid Tool) Polygon Πολύγωνο Polygon Properties: Ιδιότητες πολυγώνου: + Line Properties: Ιδιότητες γραμμής: + Line Length: Μήκος γραμμής: + Line Angle: Γωνία γραμμής: + Constrain Pie Angle Διατήρηση γωνίας κυκλικού τομέα Power Saving (integrated) Εξοικονόμηση ενέργειας (ενσωματωμένη GPU) Portuguese Πορτογαλικά PostScript: PostScript: @@ -3741,6 +3765,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. Το σύστημα προσαρμόζει το παράθυρο στα χρώματα της οθόνης. @@ -3954,6 +3981,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. Η Δημιουργία σημαδιών ξακρίσματος σχεδιάζει σημάδια ιαπωνικού τύπου αντί για ρωμαϊκά. @@ -4151,6 +4179,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 Πρόσφατες εντολές @@ -4219,6 +4250,7 @@ digits Malayalam Μαλαγιάλαμ Set Slice Rectangle Ορισμός ορθογωνίου τομής Set Tab Stops Ορισμός στηλοθετών Set Text Ορισμός κειμένου + Set the current fill or stroke to the selected color Ορισμός επιλεγμένου χρώματος ως τρέχοντος γεμίσματος ή περιγράμματος Set the selected color to the current color Ορισμός επιλεγμένου χρώματος ως τρέχοντος Set Zoom Ορισμός ζουμ Setup… Ρύθμιση… @@ -4321,7 +4353,7 @@ digits Malayalam Μαλαγιάλαμ Show Vivid/Muted Εμφάνιση έντονων/απαλών Show Warm/Cool Εμφάνιση θερμών/ψυχρών Show {kind} Brushes Εμφάνιση πινέλων {kind} - Show/hide plate (Alt-click: only this plate) Εμφάνιση/απόκρυψη πλάκας (Alt-κλικ: μόνο αυτή η πλάκα) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Εμφάνιση/απόκρυψη πλάκας (Alt-κλικ: μόνο αυτή η πλάκα· ξανά Alt-κλικ: όλες οι πλάκες) Shown with the optimised preview. Εμφανίζεται με τη βελτιστοποιημένη προεπισκόπηση. Side 1: Πλευρά 1: Side 2: Πλευρά 2: @@ -4772,6 +4804,8 @@ digits Malayalam Μαλαγιάλαμ V Spacing: Κατακόρυφη απόσταση: V: Κατακόρυφα: Variable Width Profile Προφίλ μεταβλητού πλάτους + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Το πινέλο του περιγράμματος διατηρεί το δικό του μέγεθος, οπότε ένα προφίλ πλάτους δεν το αλλάζει. Αφαιρέστε το πινέλο για να χρησιμοποιήσετε προφίλ. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Το πινέλο του περιγράμματος διατηρεί το δικό του μέγεθος, οπότε ένα προφίλ πλάτους δεν το αλλάζει. Αφαιρέστε το πινέλο για να χρησιμοποιήσετε προφίλ. New Variable Νέα μεταβλητή Delete Variable Διαγραφή μεταβλητής Lock Variables Κλείδωμα μεταβλητών @@ -4911,6 +4945,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 Επαναφορά στη γραμμή εργαλείων @@ -5075,9 +5110,15 @@ 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 three [x, y] pairs of numbers το `points` πρέπει να είναι τρία ζεύγη αριθμών [x, y] -@msg direct-select three anchor points, or give `points` επιλέξτε άμεσα τρία σημεία αγκύρωσης ή δώστε `points` +@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` @msg no circle passes through these points: two are the same or all three lie on one line κανένας κύκλος δεν περνά από αυτά τα σημεία: δύο είναι ίδια ή και τα τρία βρίσκονται σε μία ευθεία @msg no app to open files here δεν υπάρχει εφαρμογή για άνοιγμα αρχείων εδώ @msg no artboard δεν υπάρχει πίνακας σχεδίασης @@ -5179,6 +5220,9 @@ digits Malayalam Μαλαγιάλαμ @msg no such user library δεν υπάρχει τέτοια βιβλιοθήκη χρήστη @msg no such view δεν υπάρχει τέτοια προβολή @msg no such width point δεν υπάρχει τέτοιο σημείο πλάτους +@msg `single` must be `incoming` or `outgoing` το `single` πρέπει να είναι `incoming` ή `outgoing` +@msg `index` and `outIndex` must be the two halves of one discontinuous width point τα `index` και `outIndex` πρέπει να είναι τα δύο μισά ενός ασυνεχούς σημείου πλάτους +@msg a discontinuous width point keeps its place ένα ασυνεχές σημείο πλάτους διατηρεί τη θέση του @msg no swatch `{name}` δεν υπάρχει δείγμα χρώματος `{name}` @msg no swatch library `{l}` (see swatch.library.list) δεν υπάρχει βιβλιοθήκη δειγμάτων `{l}` (δείτε swatch.library.list) @msg no symbol instances selected δεν έχουν επιλεγεί στιγμιότυπα συμβόλων @@ -5541,6 +5585,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 @@ -5673,6 +5719,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} @@ -5801,6 +5848,7 @@ variable-list-end {0}, {1} {0} και {1} Both sides Και οι δύο πλευρές Cove Κοίλη ακμή Front Μπροστά + Side Πλάι Isometric Bottom Ισομετρική κάτω όψη Isometric Left Ισομετρική αριστερή όψη Isometric Right Ισομετρική δεξιά όψη @@ -5887,7 +5935,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 and Revolve object types Τα γραφικά αντιστοιχίζονται στους τύπους αντικειμένου Επίπεδο, Εξώθηση και Περιστροφή γύρω από άξονα @@ -7720,6 +7768,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 02213f4d00..103822028c 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -141,8 +141,12 @@ 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 + Outgoing Saliente + Single Width Only Solo una anchura Adjust Color Balance… Ajustar equilibrio de color… Adjust Colors Ajustar colores Adjust Options: Opciones de ajuste: @@ -493,6 +497,8 @@ font-technology Variable Variables Choose a folder Elige una carpeta Choose… Elegir… Circle Círculo + Circle Tool Herramienta Círculo + Circle too large Círculo demasiado grande Classic Defaults Valores predeterminados clásicos Clean Up… Limpiar… Clear Borrar @@ -882,6 +888,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 @@ -1281,6 +1288,8 @@ font-technology Variable Variables Files Archivos Files of a PDF standard can't be password-protected. Los archivos de un estándar PDF no se pueden proteger con contraseña. Files of this standard tag their colours with ICC profiles. Los archivos de este estándar etiquetan sus colores con perfiles ICC. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Los archivos de este estándar etiquetan sus colores con perfiles ICC, excepto los colores CMYK en el perfil de propósito de salida, que se escriben como DeviceCMYK. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. Con «No incluir perfiles» y un propósito de salida CMYK, cada color CMYK se escribe como DeviceCMYK, salvo que se convierta a un destino CMYK de otro perfil. Fill Relleno Fill & Stroke Relleno y trazo Fill (X), double-click for the Color Picker Relleno (X), doble clic para el selector de color @@ -2057,6 +2066,7 @@ font-technology Variable Variables Load SVG into Clipboard Cargar SVG en el portapapeles Load Text into Clipboard Cargar texto en el portapapeles Local Libraries Bibliotecas locales + Locate Layer Localizar capa Locate Object Localizar objeto Locate Selected Objects Localizar objetos seleccionados Location Ubicación @@ -2253,6 +2263,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 @@ -2289,6 +2300,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 @@ -2724,6 +2736,10 @@ font-technology Variable Variables Polar Grid Tool Herramienta Cuadrícula polar Polygon Polígono Polygon Properties: Propiedades del polígono: + 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) @@ -2883,6 +2899,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. @@ -3144,6 +3163,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. @@ -3453,6 +3473,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 @@ -3533,6 +3556,7 @@ digits Malayalam Malayálam Set Slice Rectangle Definir rectángulo de sector Set Tab Stops Definir tabulaciones Set Text Definir texto + Set the current fill or stroke to the selected color Asignar el color seleccionado al relleno o trazo actual Set the selected color to the current color Asignar el color actual al color seleccionado Set Zoom Definir zoom Settings… Ajustes… @@ -3656,7 +3680,7 @@ digits Malayalam Malayálam Show Vivid/Muted Mostrar vivos/apagados Show Warm/Cool Mostrar cálidos/fríos Show {kind} Brushes Mostrar pinceles de {kind} - Show/hide plate (Alt-click: only this plate) Mostrar/ocultar plancha (Alt+clic: solo esta plancha) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Mostrar/ocultar plancha (Alt+clic: solo esta plancha; Alt+clic otra vez: todas las planchas) Show: Mostrar: Shown with the optimised preview. Se muestra con la vista previa optimizada. Side 1: Lado 1: @@ -4263,6 +4287,8 @@ digits Malayalam Malayálam V Spacing: Espaciado V: V: V: Variable Width Profile Perfil de anchura variable + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. El pincel del trazo mantiene su propio tamaño, así que un perfil de anchura no lo cambia. Quite el pincel para usar un perfil. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. El pincel del trazo mantiene su propio tamaño, así que un perfil de anchura no lo cambia. Quite el pincel para usar un perfil. Variables Variables New Variable Nueva variable Delete Variable Eliminar variable @@ -4541,6 +4567,7 @@ imageTrace Outline Contorno Bevel Bisel Offset Desplazamiento Axis Eje + Axis Angle Ángulo del eje axis Horizontal Horizontal axis Vertical Vertical axis Both Ambos @@ -4792,6 +4819,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} @@ -5125,9 +5160,15 @@ 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 three [x, y] pairs of numbers `points` debe ser tres pares de números [x, y] -@msg direct-select three anchor points, or give `points` seleccione directamente tres puntos de ancla o indique `points` +@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` @msg no circle passes through these points: two are the same or all three lie on one line ningún círculo pasa por estos puntos: dos son iguales o los tres están en una misma línea @msg no app to open files here aquí no hay ninguna aplicación para abrir archivos @msg no artboard no hay mesa de trabajo @@ -5229,6 +5270,9 @@ liquify-list-end {0}, {1} {0}, {1} @msg no such user library no existe esa biblioteca de usuario @msg no such view no existe esa vista @msg no such width point no existe ese punto de anchura +@msg `single` must be `incoming` or `outgoing` `single` debe ser `incoming` u `outgoing` +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` y `outIndex` deben ser las dos mitades de un mismo punto de anchura discontinuo +@msg a discontinuous width point keeps its place un punto de anchura discontinuo conserva su posición @msg no swatch `{name}` no existe la muestra `{name}` @msg no swatch library `{l}` (see swatch.library.list) no existe la biblioteca de muestras `{l}` (consulta swatch.library.list) @msg no symbol instances selected no hay instancias de símbolo seleccionadas @@ -5598,6 +5642,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 @@ -5714,6 +5760,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 @@ -6376,6 +6423,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 @@ -6471,7 +6519,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 and Revolve object types Los gráficos se asignan a los tipos de objeto Plano, Extrusión y Revolución @@ -7708,6 +7756,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 1c3c073fd0..0e0a2bc74e 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 @@ -1797,6 +1798,7 @@ digits Malayalam Malajalam Rule: Sääntö: Save changes to {name} Tallenna muutokset kohteeseen {name} Save theme to My Themes Tallenna teema Omiin teemoihin + Set the current fill or stroke to the selected color Aseta nykyiseksi täytöksi tai viivaksi valittu väri Set the selected color to the current color Aseta valituksi väriksi nykyinen väri Copy All Styles Kopioi kaikki tyylit Exported {path} Viety: {path} @@ -2249,7 +2251,7 @@ digits Malayalam Malajalam Overprint Preview (separations) Päällepainatuksen esikatselu (erottelut) Show All Plates Näytä kaikki painolevyt Show all plates Näytä kaikki painolevyt - Show/hide plate (Alt-click: only this plate) Näytä/piilota painolevy (Alt-napsautus: vain tämä painolevy) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Näytä/piilota painolevy (Alt-napsautus: vain tämä painolevy; uusi Alt-napsautus: kaikki painolevyt) Simulate Paper Simuloi paperia Use Black Point Compensation Käytä mustan pisteen kompensointia Working CMYK (don't tag) Työ-CMYK (ei tunnistetta) @@ -2289,6 +2291,8 @@ digits Malayalam Malajalam Tip extends past the end point Kärki ulottuu päätepisteen yli Tip on the end point Kärki päätepisteessä Variable Width Profile Muuttuvan leveyden profiili + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Viivan sivellin säilyttää oman kokonsa, joten leveysprofiili ei muuta sitä. Poista sivellin, jos haluat käyttää profiilia. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Viivan sivellin säilyttää oman kokonsa, joten leveysprofiili ei muuta sitä. Poista sivellin, jos haluat käyttää profiilia. Weight: Paksuus: Art using a deleted global swatch keeps its colour. Poistettua globaalia värimallia käyttävä kuvitus säilyttää värinsä. Color Group: {name} Väriryhmä: {name} @@ -2398,6 +2402,10 @@ digits Malayalam Malajalam Flip Horizontal Käännä vaakasuunnassa Flip Vertical Käännä pystysuunnassa Polygon Properties: Monikulmion ominaisuudet: + 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 @@ -2439,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 @@ -2477,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: @@ -3142,6 +3152,8 @@ antiAlias Sharp Terävä Every option matches {base}. Kaikki asetukset vastaavat kohdetta {base}. Files of a PDF standard can't be password-protected. PDF-standardin mukaisia tiedostoja ei voi suojata salasanalla. Files of this standard tag their colours with ICC profiles. Tämän standardin tiedostot merkitsevät värinsä ICC-profiileilla. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Tämän standardin tiedostot merkitsevät värinsä ICC-profiileilla, paitsi tulostustavoitteen profiilin CMYK-värit, jotka kirjoitetaan DeviceCMYK-muodossa. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. Kun valintana on ”Älä sisällytä profiileja” ja tulostustavoite on CMYK, jokainen CMYK-väri kirjoitetaan DeviceCMYK-muodossa, ellei sitä muunneta toisen profiilin CMYK-kohteeseen. Flattener preset: Litistyksen esiasetus: General › Thumbnails Yleiset › Pikkukuvat Grayscale images Harmaasävykuvat @@ -3396,6 +3408,9 @@ antiAlias Sharp Terävä Variable Options Muuttujan asetukset Define a variable first Määritä ensin muuttuja Adjust Adjoining Width Points Säädä viereisiä leveyspisteitä + Incoming Saapuva + Outgoing Lähtevä + Single Width Only Vain yksi leveys Keep both sides the same width Pidä molemmat puolet samanlevyisinä Side 1: Puoli 1: Side 2: Puoli 2: @@ -3793,6 +3808,7 @@ theme Appearance Ulkoasu Select Art Valitse kuvitus Set Current Layer Aseta nykyinen taso Flatten Artwork Litistä kuvitus + Locate Layer Paikanna taso Locate Object Paikanna objekti Lock Others Lukitse muut Merge Selected Yhdistä valitut @@ -3969,6 +3985,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ö @@ -3995,6 +4012,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 @@ -4083,6 +4101,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. @@ -4483,6 +4504,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 @@ -4519,6 +4543,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. @@ -4615,6 +4640,8 @@ font-technology Variable Muuttuvat Couldn't paste from the clipboard: {e} Leikepöydältä ei voitu liittää: {e} Channel Kanava Circle Ympyrä + Circle Tool Ympyrätyökalu + Circle too large Ympyrä on liian suuri Clip to Art Rajaa kuvitukseen Colorize Väritä Gamma Gamma @@ -5019,6 +5046,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} @@ -5341,9 +5376,15 @@ 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 three [x, y] pairs of numbers `points` on annettava kolmena lukuparina [x, y] -@msg direct-select three anchor points, or give `points` valitse suoraan kolme ankkuripistettä tai anna `points` +@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` @msg no circle passes through these points: two are the same or all three lie on one line näiden pisteiden kautta ei kulje ympyrää: kaksi pisteistä on samoja tai kaikki kolme ovat samalla suoralla @msg no app to open files here täällä ei ole sovellusta tiedostojen avaamiseen @msg no artboard ei piirtoalustaa @@ -5445,6 +5486,9 @@ liquify-list-end {0}, {1} {0} ja {1} @msg no such user library käyttäjäkirjastoa ei ole @msg no such view näkymää ei ole @msg no such width point leveyspistettä ei ole +@msg `single` must be `incoming` or `outgoing` `single` on oltava `incoming` tai `outgoing` +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` ja `outIndex` on oltava saman epäjatkuvan leveyspisteen kaksi puolikasta +@msg a discontinuous width point keeps its place epäjatkuva leveyspiste pysyy paikallaan @msg no swatch `{name}` ei värimallia `{name}` @msg no swatch library `{l}` (see swatch.library.list) ei värimallikirjastoa `{l}` (ks. swatch.library.list) @msg no symbol instances selected symboli-ilmentymiä ei ole valittu @@ -5806,6 +5850,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 @@ -5896,6 +5942,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} @@ -6309,6 +6356,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 @@ -6404,7 +6452,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 and Revolve object types Grafiikat sijoitetaan objektityypeille Taso, Pursota ja Pyöräytä @@ -7796,6 +7844,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 f7ced65928..0af082e44a 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -142,8 +142,12 @@ 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 + Outgoing Sortant + Single Width Only Une seule largeur Adjust Color Balance… Régler la balance des couleurs… Adjust Colors Régler les couleurs Adjust Options: Options de réglage : @@ -494,6 +498,8 @@ font-technology Variable Variables Choose a folder Choisissez un dossier Choose… Choisir… Circle Cercle + Circle Tool Outil Cercle + Circle too large Cercle trop grand Classic Defaults Valeurs par défaut classiques Clean Up… Nettoyer… Clear Effacer @@ -885,6 +891,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 @@ -1272,6 +1279,8 @@ font-technology Variable Variables Files Fichiers Files of a PDF standard can't be password-protected. Les fichiers conformes à une norme PDF ne peuvent pas être protégés par mot de passe. Files of this standard tag their colours with ICC profiles. Les fichiers conformes à cette norme balisent leurs couleurs avec des profils ICC. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Les fichiers conformes à cette norme balisent leurs couleurs avec des profils ICC, sauf les couleurs CMJN du profil du mode de sortie, qui sont écrites en DeviceCMYK. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. Avec l’option Ne pas inclure les profils et un mode de sortie CMJN, chaque couleur CMJN est écrite en DeviceCMYK, sauf si elle est convertie vers une destination CMJN d’un autre profil. Fill Fond Fill & Stroke Fond et contour Fill (X), double-click for the Color Picker Fond (X), double-cliquez pour ouvrir le Sélecteur de couleurs @@ -2047,6 +2056,7 @@ font-technology Variable Variables Load SVG into Clipboard Charger un SVG dans le presse-papiers Load Text into Clipboard Charger du texte dans le presse-papiers Local Libraries Bibliothèques locales + Locate Layer Localiser le calque Locate Object Localiser l’objet Locate Selected Objects Localiser les objets sélectionnés Location Emplacement @@ -2241,6 +2251,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 @@ -2277,6 +2288,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 @@ -2712,6 +2724,10 @@ font-technology Variable Variables Polar Grid Tool Outil Grille à coordonnées polaires Polygon Polygone Polygon Properties: Propriétés du polygone : + 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) @@ -2871,6 +2887,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. @@ -3132,6 +3151,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. @@ -3441,6 +3461,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 @@ -3521,6 +3544,7 @@ digits Malayalam Malayalam Set Slice Rectangle Définir le rectangle de tranche Set Tab Stops Définir les taquets de tabulation Set Text Définir le texte + Set the current fill or stroke to the selected color Appliquer la couleur sélectionnée au fond ou au contour actuel Set the selected color to the current color Remplacer la couleur sélectionnée par la couleur actuelle Set Zoom Définir le zoom Settings… Réglages… @@ -3644,7 +3668,7 @@ digits Malayalam Malayalam Show Vivid/Muted Afficher vives/atténuées Show Warm/Cool Afficher chaudes/froides Show {kind} Brushes Afficher les formes de type {kind} - Show/hide plate (Alt-click: only this plate) Afficher/masquer la plaque (Alt+clic : cette plaque uniquement) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Afficher/masquer la plaque (Alt+clic : cette plaque uniquement, puis à nouveau toutes les plaques) Show: Afficher : Shown with the optimised preview. Affiché avec l’aperçu optimisé. Side 1: Côté 1 : @@ -4247,6 +4271,8 @@ digits Malayalam Malayalam V Spacing: Espacement V : V: V : Variable Width Profile Profil de largeur variable + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. La forme du contour garde sa propre taille, donc un profil de largeur ne la modifie pas. Supprimez la forme pour utiliser un profil. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. La forme du contour garde sa propre taille, donc un profil de largeur ne la modifie pas. Supprimez la forme pour utiliser un profil. Variables Variables New Variable Nouvelle variable Delete Variable Supprimer la variable @@ -4523,6 +4549,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 @@ -4750,6 +4777,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é @@ -5084,9 +5119,15 @@ 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 three [x, y] pairs of numbers `points` doit contenir trois paires de nombres [x, y] -@msg direct-select three anchor points, or give `points` sélectionnez trois points d’ancrage avec l’outil Sélection directe, ou indiquez `points` +@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` @msg no circle passes through these points: two are the same or all three lie on one line aucun cercle ne passe par ces points : deux sont identiques ou les trois sont alignés @msg no app to open files here aucune application pour ouvrir des fichiers ici @msg no artboard aucun plan de travail @@ -5188,6 +5229,9 @@ liquify-list-end {0}, {1} {0} et {1} @msg no such user library bibliothèque utilisateur inexistante @msg no such view vue inexistante @msg no such width point point de largeur inexistant +@msg `single` must be `incoming` or `outgoing` `single` doit valoir `incoming` ou `outgoing` +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` et `outIndex` doivent être les deux moitiés d’un même point de largeur discontinu +@msg a discontinuous width point keeps its place un point de largeur discontinu garde sa position @msg no swatch `{name}` aucune nuance `{name}` @msg no swatch library `{l}` (see swatch.library.list) aucune bibliothèque de nuances `{l}` (voir swatch.library.list) @msg no symbol instances selected aucune instance de symbole sélectionnée @@ -5551,6 +5595,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 @@ -5691,6 +5737,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 @@ -5972,6 +6019,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 @@ -6066,6 +6114,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 @@ -7727,6 +7776,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 @@ -8685,6 +8742,7 @@ breakText Glyphs Glyphes @msg compound {_1} must contain exactly one open path to join le tracé transparent {_1} doit contenir exactement un tracé ouvert à joindre @msg connect end must be "start" or "end" l’extrémité de connect doit valoir "start" ou "end" @msg connect needs a path other than the one extended connect nécessite un tracé autre que celui qui est prolongé +@msg connect needs extend connect nécessite extend @msg connect needs id connect nécessite id @msg connect path has no open end le tracé de connect n’a pas d’extrémité ouverte @msg continuation must be an array of path chunks continuation doit être une liste de fragments de tracé diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 8cf4d18773..bea830d5c4 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -164,7 +164,11 @@ Add to the Current Shortcuts વર્તમાન શૉર્ટકટમાં ઉમેરો Additional Fonts Folder વધારાનું ફોન્ટ ફોલ્ડર Additional Plug-ins Folder વધારાનું પ્લગ-ઇન ફોલ્ડર + Plug-in Instruction Budget પ્લગ-ઇન સૂચના બજેટ Adjust Adjoining Width Points અડીને આવેલા પહોળાઈ બિંદુઓ ગોઠવો + Incoming આવતી બાજુ + Outgoing જતી બાજુ + Single Width Only ફક્ત એક પહોળાઈ Adjust Color Balance… રંગ બૅલેન્સ ગોઠવો… Adjust Colors રંગ ગોઠવો Adjust Options: ગોઠવણ વિકલ્પો: @@ -227,6 +231,7 @@ Anchors selected: {count} પસંદ કરેલા એન્કર: {count} Anchors: એન્કર: Angle ખૂણો + Axis Angle અક્ષનો ખૂણો Angle: ખૂણો: Angled Strokes… ત્રાંસા સ્ટ્રોક… Angles ખૂણા @@ -571,6 +576,8 @@ Chosen: {n} of {total} પસંદ કરેલ: {total} માંથી {n} Chrome… ક્રોમ… Circle વર્તુળ + Circle Tool વર્તુળ ટૂલ + Circle too large વર્તુળ ખૂબ મોટું છે Circle: વર્તુળ: Classic ક્લાસિક Clean Up સાફ કરો @@ -1009,6 +1016,7 @@ Direction: દિશા: Directives નિર્દેશો Disable Auto Add/Delete ઑટો ઍડ/ડિલીટ બંધ કરો + Interpolate Control Points When Moving Anchors એન્કર બિંદુઓ ખસેડતી વખતે દિશા હેન્ડલ્સ ઇન્ટરપોલેટ કરો Disable Opacity Mask ઓપેસિટી માસ્ક બંધ કરો Disable and Continue બંધ કરો અને ચાલુ રાખો Disabled plug-ins બંધ કરેલા પ્લગ-ઇન્સ @@ -1393,6 +1401,8 @@ Files ફાઇલો Files of a PDF standard can't be password-protected. PDF સ્ટાન્ડર્ડની ફાઇલો પાસવર્ડ-સુરક્ષિત કરી શકાતી નથી. Files of this standard tag their colours with ICC profiles. આ સ્ટાન્ડર્ડની ફાઇલો તેમના રંગોને ICC પ્રોફાઇલ્સ સાથે ટૅગ કરે છે. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. આ સ્ટાન્ડર્ડની ફાઇલો તેમના રંગોને ICC પ્રોફાઇલ્સ સાથે ટૅગ કરે છે, આઉટપુટ ઇન્ટેન્ટ પ્રોફાઇલમાંના CMYK રંગો સિવાય, જે DeviceCMYK તરીકે લખાય છે. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. “પ્રોફાઇલ્સ શામેલ કરશો નહીં” અને CMYK આઉટપુટ ઇન્ટેન્ટ સાથે, દરેક CMYK રંગ DeviceCMYK તરીકે લખાય છે, સિવાય કે તેને બીજી પ્રોફાઇલના CMYK ગંતવ્યમાં રૂપાંતરિત કરવામાં આવે. Fill ભરો Fill & Stroke ભરો અને સ્ટ્રોક Fill (X), double-click for the Color Picker ભરો (X), કલર પીકર માટે ડબલ-ક્લિક કરો @@ -1526,6 +1536,7 @@ From Selection પસંદગીમાંથી From: થી: Front આગળ + Side બાજુ Full Document સંપૂર્ણ દસ્તાવેજ Full Justify સંપૂર્ણ જસ્ટિફાય Full Screen Mode ફુલ સ્ક્રીન મોડ @@ -1925,6 +1936,7 @@ Kashidas કાશીદા Keep Formatting ફોર્મેટિંગ રાખો Keep Original મૂળ રાખો + Keep Originals મૂળ રાખો Keep Plain Text સાદો ટેક્સ્ટ રાખો Keep Shared Points Together વહેંચાયેલા પોઇન્ટ સાથે રાખો Keep Tools Beside the Canvas ટૂલ્સ કેનવાસની બાજુમાં રાખો @@ -2113,6 +2125,7 @@ Loads native code નેટિવ કોડ લોડ કરે છે Local Libraries સ્થાનિક લાઇબ્રેરીઓ Locate Library… લાઇબ્રેરી શોધો… + Locate Layer લેયર શોધો Locate Object ઑબ્જેક્ટ શોધો Locate Selected Objects પસંદ કરેલા ઑબ્જેક્ટ શોધો Location સ્થાન @@ -2780,6 +2793,10 @@ Polish પોલિશ Polygon બહુકોણ Polygon Properties: બહુકોણના ગુણધર્મો: + Line Properties: રેખાના ગુણધર્મો: + Line Length: રેખાની લંબાઈ: + Line Angle: રેખાનો કોણ: + Constrain Pie Angle પાઇ કોણ મર્યાદિત કરો Polygon Tool બહુકોણ ટૂલ Polygonal Lasso બહુકોણીય લાસો Polygonal Lasso Tool બહુકોણીય લાસો ટૂલ @@ -3205,6 +3222,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. ટ્રિમ માર્ક્સ બનાવો રોમન ને બદલે જાપાની શૈલીના ચિહ્નો દોરે છે. @@ -3329,6 +3347,7 @@ Rotation Y પરિભ્રમણ Y Rotation Z પરિભ્રમણ Z Rotation relative to: આના સાપેક્ષે પરિભ્રમણ: + Hue Jitter: રંગછટામાં ફેરફાર: Rotation: પરિભ્રમણ: Rough Pastels… રફ પેસ્ટલ્સ… Roughen… રફ બનાવો… @@ -3340,6 +3359,7 @@ Rounded Rectangle ગોળાકાર લંબચોરસ Rounded Rectangle Tool ગોળાકાર લંબચોરસ ટૂલ Rounded Rectangle… ગોળાકાર લંબચોરસ… + Roundness ગોળાઈ Roundness: ગોળાઈ: Row Size: પંક્તિનું માપ: Rows પંક્તિઓ @@ -3550,6 +3570,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 તાજેતરના આદેશો @@ -3664,6 +3690,7 @@ Set Zoom ઝૂમ સેટ કરો Set as Default ડિફૉલ્ટ તરીકે સેટ કરો Set base color to the current color બેઝ રંગ વર્તમાન રંગ પર સેટ કરો + Set the current fill or stroke to the selected color વર્તમાન ભરો અથવા સ્ટ્રોક પસંદ કરેલ રંગ પર સેટ કરો Set the selected color to the current color પસંદ કરેલ રંગ વર્તમાન રંગ પર સેટ કરો Set {n} {n} સેટ કરો Settings સેટિંગ્સ @@ -3781,7 +3808,7 @@ Show its progress, see Cancel and write log lines તેની પ્રગતિ બતાવવી, રદ કરવાની વિનંતી જોવી અને લૉગ લાઇનો લખવી Show segmented color wheel સેગમેન્ટેડ રંગ ચક્ર બતાવો Show smooth color wheel સ્મૂધ રંગ ચક્ર બતાવો - Show/hide plate (Alt-click: only this plate) પ્લેટ બતાવો/છુપાવો (Alt-ક્લિક: માત્ર આ પ્લેટ) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) પ્લેટ બતાવો/છુપાવો (Alt-ક્લિક: માત્ર આ પ્લેટ; ફરી Alt-ક્લિક: બધી પ્લેટ) Show: બતાવો: Shown with the optimised preview. ઑપ્ટિમાઇઝ્ડ પ્રીવ્યૂ સાથે બતાવેલ. Side 1: બાજુ 1: @@ -3856,6 +3883,8 @@ Report Results પરિણામોનો અહેવાલ Smooth સ્મૂધ Smooth Anchors… એન્કર સ્મૂધ કરો… + Smooth Bridge સ્મૂધ બ્રિજ + Smooth Bridge… સ્મૂધ બ્રિજ… Smooth Tool સ્મૂધ ટૂલ Smooth… સ્મૂધ કરો… Smudge Stick… સ્મજ સ્ટિક… @@ -4382,6 +4411,8 @@ Variable Font વેરિએબલ ફૉન્ટ Variable Options… વેરિએબલ વિકલ્પો… Variable Width Profile વેરિએબલ પહોળાઈ પ્રોફાઇલ + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. સ્ટ્રોકનું બ્રશ પોતાનું કદ જાળવે છે, તેથી પહોળાઈ પ્રોફાઇલ તેને બદલતી નથી. પ્રોફાઇલ વાપરવા માટે બ્રશ દૂર કરો. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. સ્ટ્રોકનું બ્રશ પોતાનું કદ જાળવે છે, તેથી પહોળાઈ પ્રોફાઇલ તેને બદલતી નથી. પ્રોફાઇલ વાપરવા માટે બ્રશ દૂર કરો. Variables વેરિએબલ્સ Variation: વેરિએશન: Vector Effects વેક્ટર અસરો @@ -4690,6 +4721,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 c80c840142..420bc72304 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -257,7 +257,11 @@ Add Used Colors उपयोग किए रंग जोड़ें Additional Fonts Folder अतिरिक्त फ़ॉन्ट फ़ोल्डर Additional Plug-ins Folder अतिरिक्त प्लग-इन फ़ोल्डर + Plug-in Instruction Budget प्लग-इन निर्देश बजट Adjust Adjoining Width Points सटे हुए चौड़ाई पॉइंट समायोजित करें + Incoming आने वाली ओर + Outgoing जाने वाली ओर + Single Width Only केवल एक चौड़ाई Adjust Color Balance… कलर बैलेंस समायोजित करें… Adjust Colors रंग समायोजित करें Adjust Options: समायोजन ऑप्शन्स: @@ -534,6 +538,7 @@ antiAlias Sharp शार्प Average… औसत… Away from the Line लाइन से दूर Axis अक्ष + Axis Angle अक्ष कोण Axis side अक्ष की तरफ़ Axis: अक्ष: B4 B4 @@ -833,6 +838,8 @@ antiAlias Sharp शार्प Chrome क्रोम Chrome… क्रोम… Circle वृत्त + Circle Tool वृत्त टूल + Circle too large वृत्त बहुत बड़ा है Circle (open) सर्किल (ओपन) Circle: वृत्त: Classic क्लासिक @@ -1419,6 +1426,7 @@ antiAlias Sharp शार्प Direction: दिशा: Directives निर्देश Disable Auto Add/Delete ऑटो जोड़ना/हटाना अक्षम करें + Interpolate Control Points When Moving Anchors एंकर पॉइंट खिसकाते समय निर्देशन हैंडल इंटरपोलेट करें Disable Opacity Mask ओपेसिटी मास्क अक्षम करें Discard डिस्कर्ड Discard Empty Type खाली टाइप हटाएँ @@ -1923,6 +1931,8 @@ antiAlias Sharp शार्प Files फ़ाइलें Files of a PDF standard can't be password-protected. एक PDF मानक की फ़ाइलें पासवर्ड की रक्षा नहीं की जा सकती है। Files of this standard tag their colours with ICC profiles. इस मानक की फ़ाइलें ICC प्रोफ़ाइल के साथ उनके रंगों को टैग करती हैं। + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. इस मानक की फ़ाइलें ICC प्रोफ़ाइल के साथ उनके रंगों को टैग करती हैं, आउटपुट इंटेंट प्रोफ़ाइल के CMYK रंगों को छोड़कर, जो DeviceCMYK के रूप में लिखे जाते हैं। + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. “प्रोफ़ाइल शामिल नहीं है” और CMYK आउटपुट इंटेंट के साथ, हर CMYK रंग DeviceCMYK के रूप में लिखा जाता है, जब तक कि उसे किसी अन्य प्रोफ़ाइल के CMYK गंतव्य में रूपांतरित न किया जाए। Fill फ़िल Fill (X), double-click for the Color Picker फ़िल (X), कलर पिकर के लिए डबल-क्लिक करें Fill & Stroke भरें और स्ट्रोक करें @@ -2085,6 +2095,7 @@ antiAlias Sharp शार्प From Selection सिलेक्शन से From: से: Front सामने + Side बगल Frosted फ़्रॉस्टेड Full Document पूरा डॉक्यूमेंट Full Justify फुल जस्टिफ़ाई @@ -2591,6 +2602,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 साझा पॉइंट्स एक साथ रखें @@ -2817,6 +2829,7 @@ antiAlias Sharp शार्प Loads native code मूल कोड लोड करता है Local Libraries स्थानीय लाइब्रेरी Locate Library… लाइब्रेरी… + Locate Layer लेयर का पता लगाएं Locate Object ऑब्जेक्ट का पता लगाएं Locate Selected Objects सिलेक्टेड ऑब्जेक्ट्स का पता लगाएँ Location स्थान @@ -3735,6 +3748,10 @@ antiAlias Sharp शार्प Polish पोलिश Polygon बहुभुज Polygon Properties: बहुभुज प्रॉपर्टीज़: + Line Properties: रेखा प्रॉपर्टीज़: + Line Length: रेखा की लंबाई: + Line Angle: रेखा का कोण: + Constrain Pie Angle पाई एंगल बनाए रखें Polygon Tool पॉलीगोन टूल Polygonal Lasso बहुभुज लैस्सो Polygonal Lasso Tool बहुभुज लैस्सो टूल @@ -3939,6 +3956,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. सिस्टम विंडो को डिस्प्ले के रंगों से मिलाता है। @@ -4256,6 +4276,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. ट्रिम मार्क्स बनाएं रोमन की जगह जापानी शैली के निशान ड्रॉ करता है। @@ -4401,6 +4422,7 @@ antiAlias Sharp शार्प Rotate… घुमाव… Rotation घुमाव Rotation relative to: इसके सापेक्ष: + Hue Jitter: रंगत में भिन्नता: Rotation X रोटेशन X Rotation Y रोटेशन वाई Rotation Z रोटेशन Z @@ -4421,6 +4443,7 @@ antiAlias Sharp शार्प Rounded Rectangle गोल आयत Rounded Rectangle Tool राउंडेड रेक्टेंगल टूल Rounded Rectangle… गोल आयत… + Roundness राउंडनेस Roundness: राउंडनेस: Row Size: पंक्ति का आकार: Rows पंक्तियाँ @@ -4632,6 +4655,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 हाल के आदेश @@ -4764,6 +4790,7 @@ antiAlias Sharp शार्प Set Slice Rectangle सेट स्लाइस आयत Set Tab Stops टैब स्टॉप्स सेट करें Set Text टेक्स्ट सेट करें + Set the current fill or stroke to the selected color वर्तमान फ़िल या स्ट्रोक को सिलेक्टेड रंग में सेट करें Set the selected color to the current color सिलेक्टेड रंग को वर्तमान रंग में सेट करें Set Zoom ज़ूम सेट करें Set: सेट: @@ -4938,7 +4965,7 @@ antiAlias Sharp शार्प Show Vivid/Muted चमकीले/मंद दिखाएँ Show Warm/Cool शो वार्म / कूल Show: दिखाएँ: - Show/hide plate (Alt-click: only this plate) प्लेट दिखाएँ/छिपाएँ (Alt-क्लिक: केवल यही प्लेट) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) प्लेट दिखाएँ/छिपाएँ (Alt-क्लिक: केवल यही प्लेट; फिर से Alt-क्लिक: सभी प्लेटें) Shown with the optimised preview. आशावादी प्रीव्यू के साथ दिखाया गया है। Shrink Text to Fit टेक्स्ट को फिट करने के लिए सिकोड़ें Side 1: साइड 1: @@ -5033,6 +5060,8 @@ antiAlias Sharp शार्प Smooth स्मूथ Smooth Anchors चिकना एंकर Smooth Anchors… चिकना एंकर… + Smooth Bridge स्मूद ब्रिज + Smooth Bridge… स्मूद ब्रिज… Smooth Color चिकना रंग Smooth Tool चिकना टूल Smooth… चिकना करें… @@ -5799,6 +5828,8 @@ antiAlias Sharp शार्प Variable Options वेरिएबल ऑप्शन्स Variable Options… वेरिएबल ऑप्शन्स… Variable Width Profile वेरिएबल चौड़ाई प्रोफ़ाइल + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. स्ट्रोक का ब्रश अपना आकार बनाए रखता है, इसलिए चौड़ाई प्रोफ़ाइल उसे नहीं बदलती। प्रोफ़ाइल का उपयोग करने के लिए ब्रश निकालें। +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. स्ट्रोक का ब्रश अपना आकार बनाए रखता है, इसलिए चौड़ाई प्रोफ़ाइल उसे नहीं बदलती। प्रोफ़ाइल का उपयोग करने के लिए ब्रश निकालें। Variables वेरिएबल्स Variation वैरिएशन Variation: भिन्नता: @@ -6264,6 +6295,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} अंतर नहीं किया जा सकता है @@ -6824,6 +6857,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} @@ -6978,6 +7012,7 @@ antiAlias Sharp शार्प @msg compressed (RLE) bitmaps can't be read yet संकुचित (RLE) bitmaps अभी तक पढ़ा नहीं जा सकता है @msg connect end must be "start" or "end" कनेक्ट अंत "start" या "end" होना चाहिए @msg connect needs a path other than the one extended connect के लिए बढ़ाए गए पाथ के अलावा कोई दूसरा पाथ चाहिए +@msg connect needs extend connect के लिए extend चाहिए @msg connect needs id connect के लिए id चाहिए @msg connect path has no open end कनेक्ट पाथ का कोई खुला अंत नहीं है @msg Contour: select paths or shapes कंटूर: पाथ या आकृतियों सिलेक्ट करें @@ -7167,6 +7202,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} @@ -7753,9 +7796,15 @@ 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 three [x, y] pairs of numbers `points` में संख्याओं के तीन [x, y] जोड़े होने चाहिए -@msg direct-select three anchor points, or give `points` तीन एंकर पॉइंट्स डायरेक्ट-सिलेक्ट करें, या `points` दें +@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` दें @msg no circle passes through these points: two are the same or all three lie on one line इन पॉइंट्स से होकर कोई वृत्त नहीं गुज़रता: दो एक जैसे हैं या तीनों एक ही रेखा पर हैं @msg no app to open files here यहां फ़ाइलों को ओपन करने के लिए कोई ऐप नहीं है @msg no appearance item {index} कोई उपस्थिति आइटम {index} @@ -7954,6 +8003,9 @@ liquify-list-end {0}, {1} {0} और {1} @msg no such user library ऐसी कोई उपयोगकर्ता लाइब्रेरी नहीं @msg no such view कोई ऐसा दृश्य नहीं @msg no such width point ऐसी कोई चौड़ाई बिंदु नहीं +@msg `single` must be `incoming` or `outgoing` `single` का मान `incoming` या `outgoing` होना चाहिए +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` और `outIndex` एक ही असतत चौड़ाई बिंदु के दो हिस्से होने चाहिए +@msg a discontinuous width point keeps its place असतत चौड़ाई बिंदु अपनी जगह पर रहता है @msg no swatch `{keep}` कोई स्वॉच `{keep}` नहीं @msg no swatch `{n}` कोई स्वॉच `{n}` नहीं @msg no swatch `{n}` (swatches and colour groups move separately) कोई स्वॉच `{n}` नहीं (स्वॉच और रंग समूह अलग-अलग मूव होते हैं) @@ -8101,6 +8153,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 केवल ग्लोबल एडिट का एक ऑब्जेक्ट, इसके अलावा इसे शुरू किया जा सकता है, छोड़ दिया जा सकता है @@ -8446,6 +8499,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 वितरित करने के लिए दो या दो से अधिक ऑब्जेक्ट चुनें @@ -8590,7 +8644,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 and Revolve object types ग्राफ़िक्स समतल, एक्सट्रूड और रिवॉल्व ऑब्जेक्ट प्रकारों पर लगते हैं @@ -8631,6 +8685,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 d18c10c081..7ad0e9c259 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -211,7 +211,11 @@ 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ő + Single Width Only Csak egy szélesség Adjust Color Balance… Színegyensúly beállítása… Adjust Colors Színek beállítása Adjust Options: Módosítandó: @@ -384,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 @@ -655,6 +660,8 @@ font-technology Variable Változó Choose a folder Válassz mappát Choose… Kiválasztás… Circle Kör + Circle Tool Kör eszköz + Circle too large A kör túl nagy Circle (open) Kör (nyitott) Classic Defaults Klasszikus alapértékek Clean Up… Tisztítás… @@ -1130,6 +1137,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 @@ -1590,6 +1598,8 @@ digits Malayalam Malajálam Files Fájlok Files of a PDF standard can't be password-protected. A PDF-szabványnak megfelelő fájlok nem védhetők jelszóval. Files of this standard tag their colours with ICC profiles. Ennek a szabványnak a fájljai ICC-profillal jelölik a színeiket. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Ennek a szabványnak a fájljai ICC-profillal jelölik a színeiket, kivéve a kimeneti cél profiljában lévő CMYK-színeket, amelyek DeviceCMYK-ként íródnak. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. „Profilok nélkül” beállítással és CMYK kimeneti céllal minden CMYK-szín DeviceCMYK-ként íródik, kivéve, ha egy másik profil CMYK-céljába konvertálódik. Fill Kitöltés Fill & Stroke Kitöltés és körvonal Fill (X), double-click for the Color Picker Kitöltés (X), dupla kattintás: Színválasztó @@ -2557,6 +2567,7 @@ file-filter Templates Sablonok Load Texture… Textúra betöltése… Loaded Texture Betöltött textúra Local Libraries Helyi könyvtárak + Locate Layer Réteg megkeresése Locate Object Objektum megkeresése Locate Selected Objects Kijelölt objektumok megkeresése Location Hely @@ -3274,6 +3285,10 @@ diagnostics ui felület Polar Grid Tool Polárrács Polygon Sokszög Polygon Properties: Sokszög tulajdonságai: + 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) @@ -3453,6 +3468,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. @@ -3726,6 +3744,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. @@ -3864,6 +3883,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 @@ -3882,6 +3902,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 @@ -4075,6 +4096,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 @@ -4168,6 +4192,7 @@ mark-style Japanese Japán Set Slice Rectangle Szelet téglalapjának beállítása Set Tab Stops Tabulátorpontok beállítása Set Text Szöveg beállítása + Set the current fill or stroke to the selected color Az aktuális kitöltés vagy körvonal legyen a kijelölt szín Set the selected color to the current color A kijelölt szín legyen az aktuális szín Set Zoom Nagyítás beállítása Set: Készlet: @@ -4310,7 +4335,7 @@ mark-style Japanese Japán Show Vivid/Muted Élénk/tompa változatok Show Warm/Cool Meleg/hideg változatok Show {kind} Brushes Ecsetek megjelenítése: {kind} - Show/hide plate (Alt-click: only this plate) Nyomólemez megjelenítése/elrejtése (Alt+kattintás: csak ez a lemez) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Nyomólemez megjelenítése/elrejtése (Alt+kattintás: csak ez a lemez; újabb Alt+kattintás: minden lemez) Show: Megjelenítés: Shown with the optimised preview. Az optimalizált előnézettel együtt látható. Shrink Text to Fit Szöveg zsugorítása a kerethez @@ -5011,6 +5036,8 @@ mark-style Japanese Japán Variable Options Változó beállításai Variable Options… Változó beállításai… Variable Width Profile Változó szélességprofil + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. A körvonal ecsetje megtartja a saját méretét, ezért a szélességprofil nem változtatja meg. Profil használatához távolítsa el az ecsetet. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. A körvonal ecsetje megtartja a saját méretét, ezért a szélességprofil nem változtatja meg. Profil használatához távolítsa el az ecsetet. Variables Változók Variation Ingadozás Variation: Ingadozás: @@ -5377,6 +5404,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} @@ -5597,6 +5625,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} @@ -5788,9 +5824,15 @@ 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 three [x, y] pairs of numbers a `points` három [x, y] számpár legyen -@msg direct-select three anchor points, or give `points` jelölj ki közvetlen kijelöléssel három horgonypontot, vagy add meg a `points` értéket +@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 @msg no circle passes through these points: two are the same or all three lie on one line ezeken a pontokon nem halad át kör: kettő egybeesik, vagy mindhárom egy egyenesen van @msg no app to open files here itt nincs fájlmegnyitó alkalmazás @msg no artboard nincs rajztábla @@ -5901,6 +5943,9 @@ liquify-list-end {0}, {1} {0} és {1} @msg no such user library nincs ilyen felhasználói könyvtár @msg no such view nincs ilyen nézet @msg no such width point nincs ilyen szélességi pont +@msg `single` must be `incoming` or `outgoing` a `single` értéke `incoming` vagy `outgoing` lehet +@msg `index` and `outIndex` must be the two halves of one discontinuous width point az `index` és az `outIndex` egyetlen szakadásos szélességi pont két fele kell legyen +@msg a discontinuous width point keeps its place a szakadásos szélességi pont megtartja a helyét @msg no swatch `{name}` nincs ilyen színminta: `{name}` @msg no swatch library `{l}` (see swatch.library.list) nincs ilyen színminta-könyvtár: `{l}` (lásd: swatch.library.list) @msg no symbol instances selected nincs kijelölt szimbólumpéldány @@ -6369,6 +6414,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) @@ -6389,6 +6436,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 @@ -6483,7 +6531,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 and Revolve object types A grafikák a Sík, a Kihúzás és a Forgatás tengely körül objektumtípusra kerülnek @@ -7717,6 +7765,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 @@ -8695,6 +8751,7 @@ breakText Glyphs Glifák @msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes összetett alakzatba útvonalak, összetett útvonalak, csoportok, összetett alakzatok, szöveg, összemosások és burkolók kerülhetnek @msg compound {_1} must contain exactly one open path to join az összetett objektumnak ({_1}) pontosan egy összekapcsolható nyitott útvonalat kell tartalmaznia @msg connect needs a path other than the one extended connect: a meghosszabbított útvonaltól különböző útvonal kell +@msg connect needs extend connect: extend is kell hozzá @msg connect needs id connect: id is kell hozzá @msg connect path has no open end connect: az útvonalnak nincs nyitott vége @msg continuation must be an array of path chunks continuation: útvonaldarabok tömbje kell diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 51cc3788e5..3003ce0494 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 @@ -1679,6 +1680,7 @@ digits Malayalam Malayalam Rule: Aturan: Save changes to {name} Simpan perubahan ke {name} Save theme to My Themes Simpan tema ke Tema saya + Set the current fill or stroke to the selected color Atur isian atau stroke saat ini ke warna terpilih Set the selected color to the current color Atur warna terpilih ke warna saat ini Copy All Styles Salin semua gaya Exported {path} Diekspor ke {path} @@ -2037,7 +2039,7 @@ digits Malayalam Malayalam Overprint Preview (separations) Pratinjau overprint (separasi) Show All Plates Tampilkan semua pelat Show all plates Tampilkan semua pelat - Show/hide plate (Alt-click: only this plate) Tampilkan/sembunyikan pelat (Alt-klik: hanya pelat ini) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Tampilkan/sembunyikan pelat (Alt-klik: hanya pelat ini; Alt-klik lagi: semua pelat) Simulate Paper Simulasikan kertas Use Black Point Compensation Gunakan kompensasi titik hitam Working CMYK (don't tag) CMYK kerja (tanpa tag) @@ -2077,6 +2079,8 @@ digits Malayalam Malayalam Tip extends past the end point Ujung melewati titik akhir Tip on the end point Ujung pada titik akhir Variable Width Profile Profil lebar variabel + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Kuas pada guratan mempertahankan ukurannya sendiri, sehingga profil lebar tidak mengubahnya. Hapus kuas untuk menggunakan profil. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Kuas pada guratan mempertahankan ukurannya sendiri, sehingga profil lebar tidak mengubahnya. Hapus kuas untuk menggunakan profil. Weight: Ketebalan: Art using a deleted global swatch keeps its colour. Karya seni yang memakai swatch global terhapus tetap mempertahankan warnanya. Color Group: {name} Grup warna: {name} @@ -2186,6 +2190,10 @@ digits Malayalam Malayalam Flip Horizontal Balik horizontal Flip Vertical Balik vertikal Polygon Properties: Properti poligon: + 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 @@ -2227,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 @@ -2265,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: @@ -2922,6 +2932,8 @@ antiAlias Sharp Tajam Every option matches {base}. Setiap opsi cocok dengan {base}. Files of a PDF standard can't be password-protected. File standar PDF tidak dapat dilindungi kata sandi. Files of this standard tag their colours with ICC profiles. File standar ini menandai warnanya dengan profil ICC. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. File standar ini menandai warnanya dengan profil ICC, kecuali warna CMYK dalam profil output intent, yang ditulis sebagai DeviceCMYK. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. Dengan “Jangan sertakan profil” dan output intent CMYK, setiap warna CMYK ditulis sebagai DeviceCMYK, kecuali dikonversi ke tujuan CMYK dengan profil lain. Flattener preset: Preset flattener: General › Thumbnails Umum › Miniatur Grayscale images Gambar skala abu-abu @@ -3140,6 +3152,9 @@ antiAlias Sharp Tajam Variable Options Opsi variabel Define a variable first Tentukan variabel terlebih dahulu Adjust Adjoining Width Points Sesuaikan titik lebar bersebelahan + Incoming Masuk + Outgoing Keluar + Single Width Only Hanya satu lebar Keep both sides the same width Pertahankan kedua sisi tetap sama lebar Side 1: Sisi 1: Side 2: Sisi 2: @@ -3524,6 +3539,7 @@ theme Appearance Tampilan Select Art Pilih karya seni Set Current Layer Tetapkan lapisan saat ini Flatten Artwork Ratakan karya seni + Locate Layer Temukan lapisan Locate Object Temukan objek Lock Others Kunci lainnya Merge Selected Gabungkan terpilih @@ -3700,6 +3716,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 @@ -3726,6 +3743,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 @@ -3814,6 +3832,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. @@ -4210,6 +4229,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 @@ -4246,6 +4268,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. @@ -4342,6 +4365,8 @@ font-technology Variable Variabel Couldn't paste from the clipboard: {e} Tidak dapat menempel dari papan klip: {e} Channel Saluran Circle Lingkaran + Circle Tool Alat lingkaran + Circle too large Lingkaran terlalu besar Clip to Art Pangkas ke karya seni Colorize Warnai Gamma Gamma @@ -4913,6 +4938,9 @@ imageTrace Outline Kontur @msg no such user library tidak ada pustaka pengguna seperti itu @msg no such view tidak ada tampilan seperti itu @msg no such width point tidak ada titik lebar seperti itu +@msg `single` must be `incoming` or `outgoing` `single` harus `incoming` atau `outgoing` +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` dan `outIndex` harus berupa dua bagian dari satu titik lebar terputus +@msg a discontinuous width point keeps its place titik lebar terputus tetap di tempatnya @msg no swatch `{name}` tidak ada swatch `{name}` @msg no swatch library `{l}` (see swatch.library.list) tidak ada pustaka swatch `{l}` (lihat swatch.library.list) @msg no symbol instances selected tidak ada instans simbol yang dipilih @@ -5664,6 +5692,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 @@ -6994,6 +7023,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 04580a8239..8de4bebafb 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -141,8 +141,12 @@ 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 + Outgoing In uscita + Single Width Only Solo una larghezza Adjust Color Balance… Regola bilanciamento colore… Adjust Colors Regola colori Adjust Options: Opzioni di regolazione: @@ -495,6 +499,8 @@ font-technology Variable Variabili Choose a folder Scegli una cartella Choose… Scegli… Circle Cerchio + Circle Tool Strumento Cerchio + Circle too large Cerchio troppo grande Classic Defaults Valori predefiniti classici Clean Up… Pulisci… Clear Cancella @@ -884,6 +890,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 @@ -1293,6 +1300,8 @@ font-technology Variable Variabili Files File Files of a PDF standard can't be password-protected. I file conformi a uno standard PDF non possono essere protetti da password. Files of this standard tag their colours with ICC profiles. I file conformi a questo standard contrassegnano i colori con profili ICC. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. I file conformi a questo standard contrassegnano i colori con profili ICC, tranne i colori CMYK nel profilo dell'intento di output, che vengono scritti come DeviceCMYK. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. Con «Non includere i profili» e un intento di output CMYK, ogni colore CMYK viene scritto come DeviceCMYK, a meno che non venga convertito in una destinazione CMYK di un altro profilo. Fill Riempimento Fill & Stroke Riempimento e traccia Fill (X), double-click for the Color Picker Riempimento (X), fai doppio clic per il selettore colore @@ -2098,6 +2107,7 @@ file-filter Templates Modelli Load SVG into Clipboard Carica SVG negli appunti Load Text into Clipboard Carica testo negli appunti Local Libraries Librerie locali + Locate Layer Individua livello Locate Object Individua oggetto Locate Selected Objects Individua oggetti selezionati Location Posizione @@ -2294,6 +2304,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 @@ -2330,6 +2341,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 @@ -2769,6 +2781,10 @@ diagnostics ui interfaccia Polar Grid Tool Strumento Griglia polare Polygon Poligono Polygon Properties: Proprietà poligono: + 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) @@ -2930,6 +2946,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. @@ -3192,6 +3211,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. @@ -3503,6 +3523,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 @@ -3583,6 +3608,7 @@ digits Malayalam Malayalam Set Slice Rectangle Imposta rettangolo sezione Set Tab Stops Imposta tabulazioni Set Text Imposta testo + Set the current fill or stroke to the selected color Imposta il riempimento o la traccia corrente sul colore selezionato Set the selected color to the current color Imposta il colore selezionato sul colore corrente Set Zoom Imposta zoom Settings… Impostazioni… @@ -3706,7 +3732,7 @@ digits Malayalam Malayalam Show Vivid/Muted Mostra vivaci/tenui Show Warm/Cool Mostra caldi/freddi Show {kind} Brushes Mostra pennelli di tipo {kind} - Show/hide plate (Alt-click: only this plate) Mostra/nascondi lastra (Alt+clic: solo questa lastra) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Mostra/nascondi lastra (Alt+clic: solo questa lastra; di nuovo Alt+clic: tutte le lastre) Show: Mostra: Shown with the optimised preview. Mostrato con l'anteprima ottimizzata. Side 1: Lato 1: @@ -4314,6 +4340,8 @@ digits Malayalam Malayalam V Spacing: Spaziatura verticale: V: V: Variable Width Profile Profilo larghezza variabile + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Il pennello della traccia mantiene la propria dimensione, quindi un profilo di larghezza non la modifica. Rimuovi il pennello per usare un profilo. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Il pennello della traccia mantiene la propria dimensione, quindi un profilo di larghezza non la modifica. Rimuovi il pennello per usare un profilo. Variables Variabili New Variable Nuova variabile Delete Variable Elimina variabile @@ -4597,6 +4625,7 @@ imageTrace Outline Contorno Bevel Smussato Offset Spostamento Axis Asse + Axis Angle Angolo dell'asse axis Horizontal Orizzontale axis Vertical Verticale axis Both Entrambi @@ -5157,9 +5186,15 @@ 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 three [x, y] pairs of numbers `points` deve essere composto da tre coppie di numeri [x, y] -@msg direct-select three anchor points, or give `points` seleziona con Selezione diretta tre punti di ancoraggio oppure indica `points` +@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` @msg no circle passes through these points: two are the same or all three lie on one line nessun cerchio passa per questi punti: due coincidono oppure tutti e tre sono allineati @msg no app to open files here nessuna app per aprire file qui @msg no artboard nessuna tavola da disegno @@ -5261,6 +5296,9 @@ liquify-list-end {0}, {1} {0} e {1} @msg no such user library libreria utente inesistente @msg no such view vista inesistente @msg no such width point punto di larghezza inesistente +@msg `single` must be `incoming` or `outgoing` `single` deve essere `incoming` o `outgoing` +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` e `outIndex` devono essere le due metà di un unico punto di larghezza discontinuo +@msg a discontinuous width point keeps its place un punto di larghezza discontinuo mantiene la sua posizione @msg no swatch `{name}` nessun campione `{name}` @msg no swatch library `{l}` (see swatch.library.list) nessuna libreria campioni `{l}` (vedi swatch.library.list) @msg no symbol instances selected nessuna istanza di simbolo selezionata @@ -5626,6 +5664,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 @@ -5742,6 +5782,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 @@ -6026,6 +6067,7 @@ lighting Light Luce Cove Guscio Depth Profondità Front Fronte + Side Lato Isometric Bottom Isometrica sotto Isometric Left Isometrica sinistra Isometric Right Isometrica destra @@ -6120,7 +6162,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 and Revolve object types Le grafiche si applicano ai tipi di oggetto Piano, Estrusione e Rivoluzione @@ -7365,6 +7407,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 @@ -7734,6 +7784,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] @@ -8560,6 +8618,7 @@ breakText Glyphs Glifi @msg compound {_1} must contain exactly one open path to join il composto {_1} deve contenere esattamente un tracciato aperto da unire @msg connect end must be "start" or "end" end di connect deve essere "start" o "end" @msg connect needs a path other than the one extended connect richiede un tracciato diverso da quello esteso +@msg connect needs extend connect richiede extend @msg connect needs id connect richiede id @msg connect path has no open end il tracciato di connect non ha un'estremità aperta @msg copy needs path: the file to copy into the document's folder copy richiede path: il file da copiare nella cartella del documento diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index ee41e2c90a..0c19958002 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1093,8 +1093,12 @@ digits Malayalam マラヤーラム数字 Add to Selection 選択範囲に追加 Add to Swatches スウォッチに追加 Additional Plug-ins Folder 追加プラグインフォルダー + Plug-in Instruction Budget プラグインの命令予算 Additional Fonts Folder 追加フォントフォルダー Adjust Adjoining Width Points 隣接する幅ポイントを調整 + Incoming 入り側 + Outgoing 出側 + Single Width Only 1 つの幅のみ Adjust Colors カラーを調整 Adjust Options: 調整オプション: Advanced Options 詳細オプション @@ -1330,6 +1334,8 @@ antiAlias Sharp シャープ Choose a folder フォルダーを選択 Choose… 選択… Circle 円 + Circle Tool 円ツール + Circle too large 円が大きすぎます Clear All Tabs すべてのタブを消去 Above Text テキストの上 Position Panel Above Text テキストの上にパネルを配置 @@ -1579,6 +1585,7 @@ antiAlias Sharp シャープ Dimensions 寸法 Direct Selection Tool ダイレクト選択ツール Disable Auto Add/Delete 自動追加/削除機能を使用しない + Interpolate Control Points When Moving Anchors アンカーポイントの移動時に方向線ハンドルを補間 Disable Opacity Mask 不透明マスクを無効にする Discard 破棄 Preserve 保持 @@ -1868,6 +1875,8 @@ antiAlias Sharp シャープ Files ファイル Files of a PDF standard can't be password-protected. PDF 規格のファイルにはパスワードを設定できません。 Files of this standard tag their colours with ICC profiles. この規格のファイルでは、カラーに ICC プロファイルが付けられます。 + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. この規格のファイルでは、カラーに ICC プロファイルが付けられます。ただし、出力インテントのプロファイルの CMYK カラーは DeviceCMYK として書き出されます。 + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. 「プロファイルを含めない」と CMYK の出力インテントでは、別のプロファイルの CMYK 変換先に変換されない限り、すべての CMYK カラーが DeviceCMYK として書き出されます。 Fill 塗り Fill New Type Objects With Placeholder Text 新規テキストオブジェクトをダミーテキストで埋める Start Lists From Typed Markers 入力した記号からリストを開始 @@ -2372,6 +2381,7 @@ antiAlias Sharp シャープ Load SVG into Clipboard SVG をクリップボードに読み込む Load Text into Clipboard テキストをクリップボードに読み込む Local Libraries ローカルライブラリ + Locate Layer レイヤーを検索 Locate Object オブジェクトを検索 Locate Selected Objects 選択したオブジェクトを検索 Location 場所 @@ -2493,6 +2503,7 @@ antiAlias Sharp シャープ Scatter: 散布: Rotation: 回転: Rotation relative to: 回転の基準: + Hue Jitter: 色相のばらつき: Brush Scale Options ブラシ伸縮オプション Scale Proportionately 縦横比を保持して拡大・縮小 Stretch to Fit Stroke Length ストロークの長さに合わせて伸縮 @@ -2529,6 +2540,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 筆圧 @@ -2862,6 +2874,10 @@ diagnostics ui UI Polar Grid Tool 同心円グリッドツール Polygon 多角形 Polygon Properties: 多角形のプロパティ: + Line Properties: 線のプロパティ: + Line Length: 線の長さ: + Line Angle: 線の角度: + Constrain Pie Angle 扇形の角度を固定 Polygon Tool 多角形ツール Portrait 縦置き Portuguese ポルトガル語 @@ -2963,6 +2979,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. システムがウィンドウをディスプレイのカラーに合わせます。 @@ -3176,6 +3195,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. トリムマークを作成で、西洋式ではなく日本式のトンボを描きます。 @@ -3388,6 +3408,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 最近使ったコマンド @@ -3445,6 +3468,7 @@ mark-style Japanese 日本式 Set Text テキストを設定 Set Zoom ズーム率を設定 Set base color to the current color 基本カラーを現在のカラーに設定 + Set the current fill or stroke to the selected color 現在の塗りまたは線を選択したカラーに設定 Set the selected color to the current color 選択したカラーを現在のカラーに設定 Setup… 設定… Shape Builder シェイプ形成ツール @@ -3503,7 +3527,7 @@ mark-style Japanese 日本式 Show all plates すべての版を表示 Show handles when multiple anchors are selected 複数のアンカーを選択したときにハンドルを表示 Show {kind} Brushes {kind}ブラシを表示 - Show/hide plate (Alt-click: only this plate) 版の表示/非表示 (Alt+クリック: この版のみ) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) 版の表示/非表示 (Alt+クリック: この版のみ、もう一度 Alt+クリック: すべての版) Show: 表示: Shown with the optimised preview. 最適化プレビューで表示されます。 Side 1: 辺 1: @@ -3858,6 +3882,8 @@ mark-style Japanese 日本式 User Swatch Library 9 ユーザースウォッチライブラリ 9 V Spacing: 垂直方向の間隔: Variable Width Profile 可変幅プロファイル + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. 線のブラシは独自のサイズを保つため、幅プロファイルでは変わりません。プロファイルを使うにはブラシを削除してください。 +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. 線のブラシは独自のサイズを保つため、幅プロファイルでは変わりません。プロファイルを使うにはブラシを削除してください。 Variation: バリエーション: Vector Halftone ベクトルハーフトーン Vector illustration — fast, open, scriptable. ベクターイラスト — 高速・オープン・スクリプト対応 @@ -4538,6 +4564,7 @@ imageTrace Outline アウトライン Bevel ベベル Offset オフセット Axis 軸 + Axis Angle 軸の角度 axis Horizontal 水平方向 axis Vertical 垂直方向 axis Both 両方 @@ -4927,8 +4954,8 @@ variable-list-end {0}, {1} {0}、{1} @msg image would be too large; lower the resolution 画像が大きくなりすぎるため、解像度を下げてください @msg clipboard is empty クリップボードが空です @msg no anchor points selected アンカーポイントが選択されていません -@msg `points` must be three [x, y] pairs of numbers `points` は 3 組の数値 [x, y] にしてください -@msg direct-select three anchor points, or give `points` アンカーポイントを 3 つダイレクト選択するか、`points` を指定してください +@msg `points` must be two or three [x, y] pairs of numbers `points` は 2 組または 3 組の数値 [x, y] にしてください +@msg direct-select two or three anchor points, or give `points` アンカーポイントを 2 つまたは 3 つダイレクト選択するか、`points` を指定してください @msg no circle passes through these points: two are the same or all three lie on one line これらの点を通る円はありません: 2 つの点が同じか、3 点すべてが一直線上にあります @msg select at least two objects オブジェクトを 2 つ以上選択してください @msg exit isolation mode first 先に分離モードを終了してください @@ -5302,6 +5329,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} はインストールされていません @@ -5352,6 +5385,9 @@ variable-list-end {0}, {1} {0}、{1} @msg `{color}` is not a colour (#rrggbb or a preset name) `{color}` はカラーではありません (#rrggbb またはプリセット名で指定してください) @msg give the path `id` and the width point `index` パスの `id` と幅ポイントの `index` を指定してください @msg no such width point 指定された幅ポイントが見つかりません +@msg `single` must be `incoming` or `outgoing` `single` は `incoming` または `outgoing` にしてください +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` と `outIndex` は 1 つの不連続な幅ポイントの 2 つの半分である必要があります +@msg a discontinuous width point keeps its place 不連続な幅ポイントの位置は変わりません @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 のうち 1 つだけを指定してください @@ -5616,6 +5652,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} @@ -5733,6 +5777,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}` は組み込みのワークスペースなので、別の名前を指定してください @@ -5784,6 +5830,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 自動化のパスを拒否しました: パスが空です @@ -6069,6 +6116,7 @@ lighting Light ライト Cove 凹面 Depth 奥行き Front 正面 + Side 側面 Isometric Bottom 等角図(底面) Isometric Left 等角図(左) Isometric Right 等角図(右) @@ -6163,7 +6211,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 and Revolve object types グラフィックはオブジェクトの種類が平面、押し出し、回転体のときにマッピングされます @@ -7708,6 +7756,7 @@ axis Y Axis Y 軸 @msg compound {_1} must contain exactly one open path to join 連結するには、複合パス {_1} にオープンパスがちょうど 1 つ含まれている必要があります @msg connect end must be "start" or "end" connect の end には "start" または "end" を指定してください @msg connect needs a path other than the one extended connect には、延長したパスとは別のパスが必要です +@msg connect needs extend connect には extend が必要です @msg connect needs id connect には id が必要です @msg connect path has no open end connect のパスに開いた端点がありません @msg copy needs path: the file to copy into the document's folder copy には path が必要です: ドキュメントのフォルダーにコピーするファイルを指定してください @@ -9248,6 +9297,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 3c6261ef1b..c62a2aefcb 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -733,6 +733,7 @@ @msg compound {_1} must contain exactly one open path to join შედგენილი {_1} შესაერთებლად ზუსტად ერთ ღია ტრაექტორიას უნდა შეიცავდეს @msg connect end must be "start" or "end" connect-ის end უნდა იყოს "start" ან "end" @msg connect needs a path other than the one extended connect-ს სჭირდება ტრაექტორია, რომელიც გაგრძელებულისგან განსხვავდება +@msg connect needs extend connect-ს სჭირდება extend @msg connect needs id connect-ს სჭირდება id @msg connect path has no open end connect-ის ტრაექტორიას ღია ბოლო არ აქვს @msg continuation must be an array of path chunks continuation უნდა იყოს ტრაექტორიის ნაწილების მასივი @@ -2065,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] @@ -3814,6 +3816,7 @@ digits Malayalam მალაიალამური Underline ხაზგასმული Vertical Scale % ვერტიკალური მასშტაბი % Axis ღერძი + Axis Angle ღერძის კუთხე ICF Top/Right ICF ზედა/მარჯვენა ICF Bottom/Left ICF ქვედა/მარცხენა Show Font Height Options შრიფტის სიმაღლის პარამეტრების ჩვენება @@ -3856,6 +3859,7 @@ digits Malayalam მალაიალამური Rule: წესი: Save changes to {name} ცვლილებების შენახვა: {name} Save theme to My Themes თემის შენახვა „ჩემ თემებში“ + Set the current fill or stroke to the selected color მიმდინარე შევსების ან კონტურის მონიშნულ ფერად დაყენება Set the selected color to the current color მონიშნული ფერის მიმდინარე ფერად დაყენება Copy All Styles ყველა სტილის კოპირება Exported {path} ექსპორტირებულია: {path} @@ -4205,7 +4209,7 @@ digits Malayalam მალაიალამური Overprint Preview (separations) ზედდაბეჭდვის წინასწარი ნახვა (სეპარაციები) Show All Plates ყველა ფირფიტის ჩვენება Show all plates ყველა ფირფიტის ჩვენება - Show/hide plate (Alt-click: only this plate) ფირფიტის ჩვენება/დამალვა (Alt-დაწკაპუნებით: მხოლოდ ეს ფირფიტა) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) ფირფიტის ჩვენება/დამალვა (Alt-დაწკაპუნებით: მხოლოდ ეს ფირფიტა; ხელახლა Alt-დაწკაპუნებით: ყველა ფირფიტა) Simulate Paper ქაღალდის იმიტაცია Use Black Point Compensation შავი წერტილის კომპენსაციის გამოყენება Working CMYK (don't tag) სამუშაო CMYK (ტეგის გარეშე) @@ -4245,6 +4249,8 @@ digits Malayalam მალაიალამური Tip extends past the end point წვერი ბოლო წერტილს სცდება Tip on the end point წვერი ბოლო წერტილზე Variable Width Profile ცვლადი სიგანის პროფილი + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. კონტურის ფუნჯი საკუთარ ზომას ინარჩუნებს, ამიტომ სიგანის პროფილი მას არ ცვლის. პროფილის გამოსაყენებლად მოხსენით ფუნჯი. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. კონტურის ფუნჯი საკუთარ ზომას ინარჩუნებს, ამიტომ სიგანის პროფილი მას არ ცვლის. პროფილის გამოსაყენებლად მოხსენით ფუნჯი. Weight: სისქე: Art using a deleted global swatch keeps its colour. წაშლილი გლობალური ფერის ნიმუშის მქონე ნახატი თავის ფერს ინარჩუნებს. Color Group: {name} ფერთა ჯგუფი: {name} @@ -4353,6 +4359,10 @@ digits Malayalam მალაიალამური Flip Horizontal ჰორიზონტალურად არეკვლა Flip Vertical ვერტიკალურად არეკვლა Polygon Properties: მრავალკუთხედის თვისებები: + Line Properties: ხაზის თვისებები: + Line Length: ხაზის სიგრძე: + Line Angle: ხაზის კუთხე: + Constrain Pie Angle სექტორის კუთხის შენარჩუნება Rectangle Properties: მართკუთხედის თვისებები: Shape Properties: ფიგურის თვისებები: Shape Properties ფიგურის თვისებები @@ -4393,6 +4403,7 @@ digits Malayalam მალაიალამური Scatter: გაფანტვა: Rotation: შემობრუნება: Rotation relative to: შემობრუნების ათვლა: + Hue Jitter: ელფერის ვარიაცია: Brush Scale Options ფუნჯის მასშტაბირების პარამეტრები Scale Proportionately პროპორციული მასშტაბირება Stretch to Fit Stroke Length კონტურის სიგრძეზე გაწელვა @@ -4431,6 +4442,7 @@ digits Malayalam მალაიალამური Size: ზომა: Calligraphic Brush Options კალიგრაფიული ფუნჯის პარამეტრები Bristle Brush Options ჯაგრის ფუნჯის პარამეტრები + Roundness სიმრგვალე Roundness: სიმრგვალე: Shape: ფორმა: Bristle Length: ჯაგრის სიგრძე: @@ -5065,6 +5077,8 @@ antiAlias Sharp მკვეთრი Every option matches {base}. ყველა პარამეტრი ემთხვევა {base}-ს. Files of a PDF standard can't be password-protected. PDF სტანდარტის ფაილების პაროლით დაცვა შეუძლებელია. Files of this standard tag their colours with ICC profiles. ამ სტანდარტის ფაილები ფერებს ICC პროფილებით აღნიშნავს. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. ამ სტანდარტის ფაილები ფერებს ICC პროფილებით აღნიშნავს, გარდა გამოტანის მიზნის პროფილის CMYK ფერებისა, რომლებიც DeviceCMYK-ად იწერება. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. „პროფილების გარეშე“ და CMYK გამოტანის მიზნით ყველა CMYK ფერი DeviceCMYK-ად იწერება, თუ ის სხვა პროფილის CMYK დანიშნულებაში არ გარდაიქმნება. Flattener preset: გაბრტყელების პრესეტი: General › Thumbnails ზოგადი › ესკიზები Grayscale images ნაცრისფერი გამოსახულებები @@ -5223,6 +5237,9 @@ antiAlias Sharp მკვეთრი Variable Options ცვლადის პარამეტრები Define a variable first ჯერ განსაზღვრეთ ცვლადი Adjust Adjoining Width Points მეზობელი სიგანის წერტილების მორგება + Incoming შემავალი + Outgoing გამავალი + Single Width Only მხოლოდ ერთი სიგანე Keep both sides the same width ორივე მხარის ერთნაირი სიგანე Side 1: მხარე 1: Side 2: მხარე 2: @@ -5619,6 +5636,7 @@ theme Appearance იერსახე Select Art ნახატის მონიშვნა Set Current Layer მიმდინარე შრედ დაყენება Flatten Artwork ნახატის გაბრტყელება + Locate Layer შრის მოძებნა Locate Object ობიექტის მოძებნა Lock Others დანარჩენების ჩაკეტვა Merge Selected მონიშნულების შერწყმა @@ -5793,6 +5811,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 საყრდენი წერტილების, სახელურებისა და შემომსაზღვრელი ჩარჩოს ჩვენება @@ -5819,6 +5838,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 პიქსელურ ნახვაში ბიტმაპების ანტიალიასინგიან გამოსახულებებად ჩვენება @@ -5907,6 +5927,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. სისტემა ფანჯარას ეკრანის ფერებს უსადაგებს. @@ -6277,6 +6300,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 ბოლოდროინდელი ბრძანებები @@ -6314,6 +6340,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. ჭრის ნიშნების შექმნა რომაულის ნაცვლად იაპონური სტილის ნიშნებს ხატავს. @@ -6410,6 +6437,8 @@ font-technology Variable ცვლადი Couldn't paste from the clipboard: {e} გაცვლის ბუფერიდან ჩასმა ვერ მოხერხდა: {e} Channel არხი Circle წრე + Circle Tool წრის ხელსაწყო + Circle too large წრე ზედმეტად დიდია Clip to Art ნახატზე მოჭრა Colorize გაფერადება Gamma გამა @@ -6895,8 +6924,8 @@ font-technology Variable ცვლადი @msg no active document აქტიური დოკუმენტი არ არის @msg no active perspective plane აქტიური პერსპექტივის სიბრტყე არ არის @msg no anchor points selected საყრდენი წერტილები მონიშნული არ არის -@msg `points` must be three [x, y] pairs of numbers `points` უნდა იყოს რიცხვების სამი [x, y] წყვილი -@msg direct-select three anchor points, or give `points` პირდაპირი მონიშვნით მონიშნეთ სამი საყრდენი წერტილი ან მიუთითეთ `points` +@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` @msg no circle passes through these points: two are the same or all three lie on one line ამ წერტილებზე წრეწირი არ გადის: ორი ერთნაირია ან სამივე ერთ წრფეზე მდებარეობს @msg no app to open files here აქ ფაილების გასახსნელი აპი არ არის @msg no artboard სამუშაო დაფა არ არის @@ -6993,6 +7022,9 @@ font-technology Variable ცვლადი @msg no such user library მომხმარებლის ასეთი ბიბლიოთეკა არ არის @msg no such view ასეთი ხედი არ არის @msg no such width point ასეთი სიგანის წერტილი არ არის +@msg `single` must be `incoming` or `outgoing` `single` უნდა იყოს `incoming` ან `outgoing` +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` და `outIndex` უნდა იყოს ერთი წყვეტილი სიგანის წერტილის ორი ნახევარი +@msg a discontinuous width point keeps its place წყვეტილი სიგანის წერტილი თავის ადგილს ინარჩუნებს @msg no swatch `{name}` ფერის ნიმუში `{name}` არ არის @msg no swatch library `{l}` (see swatch.library.list) ფერის ნიმუშების ბიბლიოთეკა `{l}` არ არის (იხ. swatch.library.list) @msg no symbol instances selected სიმბოლოს ეგზემპლარები მონიშნული არ არის @@ -7321,6 +7353,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 @@ -7785,6 +7819,7 @@ font-technology Variable ცვლადი Cove ღარი Depth სიღრმე Front წინიდან + Side გვერდიდან Isometric Bottom იზომეტრია ქვემოდან Isometric Left იზომეტრია მარცხნიდან Isometric Right იზომეტრია მარჯვნიდან @@ -7864,7 +7899,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 and Revolve object types გრაფიკა თავსდება ობიექტის ტიპებზე „სიბრტყე“, „ამოწევა“ და „ბრუნვა“ @@ -9943,6 +9978,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 4189baa6b3..c9b99adfcd 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1083,8 +1083,12 @@ digits Malayalam 말라얄람어 Add to Selection 선택 영역에 추가 Add to Swatches 견본에 추가 Additional Plug-ins Folder 추가 플러그인 폴더 + Plug-in Instruction Budget 플러그인 명령어 예산 Additional Fonts Folder 추가 글꼴 폴더 Adjust Adjoining Width Points 인접한 너비 점 조정 + Incoming 들어오는 쪽 + Outgoing 나가는 쪽 + Single Width Only 한 너비만 Adjust Colors 색상 조정 Adjust Options: 조정 옵션: Advanced Options 고급 옵션 @@ -1320,6 +1324,8 @@ antiAlias Sharp 날카롭게 Choose a folder 폴더 선택 Choose… 선택… Circle 원 + Circle Tool 점 기준 원 도구 + Circle too large 원이 너무 큽니다 Clear All Tabs 모든 탭 지우기 Above Text 문자 위 Position Panel Above Text 패널을 문자 위에 배치 @@ -1569,6 +1575,7 @@ antiAlias Sharp 날카롭게 Dimensions 치수 Direct Selection Tool 직접 선택 도구 Disable Auto Add/Delete 자동 추가/삭제 사용 안 함 + Interpolate Control Points When Moving Anchors 앵커 포인트 이동 시 방향 핸들 보간 Disable Opacity Mask 불투명 마스크 사용 안 함 Discard 삭제 Preserve 보존 @@ -1858,6 +1865,8 @@ antiAlias Sharp 날카롭게 Files 파일 Files of a PDF standard can't be password-protected. PDF 표준 파일은 암호로 보호할 수 없습니다. Files of this standard tag their colours with ICC profiles. 이 표준의 파일은 ICC 프로파일로 색상을 태그합니다. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. 이 표준의 파일은 ICC 프로파일로 색상을 태그합니다. 단, 출력 의도 프로파일의 CMYK 색상은 DeviceCMYK로 기록됩니다. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. '프로파일 포함 안 함'과 CMYK 출력 의도를 사용하면, 다른 프로파일의 CMYK 대상으로 변환되지 않는 한 모든 CMYK 색상이 DeviceCMYK로 기록됩니다. Fill 칠 Fill New Type Objects With Placeholder Text 새 문자 개체를 대체 텍스트로 채우기 Start Lists From Typed Markers 입력한 기호로 목록 시작 @@ -2362,6 +2371,7 @@ antiAlias Sharp 날카롭게 Load SVG into Clipboard SVG를 클립보드로 불러오기 Load Text into Clipboard 텍스트를 클립보드로 불러오기 Local Libraries 로컬 라이브러리 + Locate Layer 레이어 찾기 Locate Object 개체 찾기 Locate Selected Objects 선택한 개체 찾기 Location 위치 @@ -2483,6 +2493,7 @@ antiAlias Sharp 날카롭게 Scatter: 흩뿌림: Rotation: 회전: Rotation relative to: 회전 기준: + Hue Jitter: 색조 변화: Brush Scale Options 브러시 크기 조절 옵션 Scale Proportionately 비율에 맞게 크기 조절 Stretch to Fit Stroke Length 선 길이에 맞게 늘이기 @@ -2519,6 +2530,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 필압 @@ -2852,6 +2864,10 @@ diagnostics ui UI Polar Grid Tool 극좌표 격자 도구 Polygon 다각형 Polygon Properties: 다각형 속성: + Line Properties: 선 속성: + Line Length: 선 길이: + Line Angle: 선 각도: + Constrain Pie Angle 파이 각도 고정 Polygon Tool 다각형 도구 Portrait 세로 Portuguese Português @@ -2953,6 +2969,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. 시스템이 창을 디스플레이 색상에 맞춥니다. @@ -3165,6 +3184,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. 트림 마크 만들기에서 서양식 대신 일본식 표시를 그립니다. @@ -3377,6 +3397,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 최근 명령 @@ -3434,6 +3459,7 @@ mark-style Japanese 일본식 Set Text 문자 설정 Set Zoom 확대/축소 설정 Set base color to the current color 기준 색상을 현재 색상으로 설정 + Set the current fill or stroke to the selected color 현재 칠 또는 선을 선택한 색상으로 설정 Set the selected color to the current color 선택한 색상을 현재 색상으로 설정 Setup… 설정… Shape Builder 모양 빌더 @@ -3492,7 +3518,7 @@ mark-style Japanese 일본식 Show all plates 모든 분판 표시 Show handles when multiple anchors are selected 여러 앵커 선택 시 핸들 표시 Show {kind} Brushes {kind} 브러시 표시 - Show/hide plate (Alt-click: only this plate) 분판 표시/숨기기(Alt 클릭: 이 분판만) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) 분판 표시/숨기기(Alt 클릭: 이 분판만, 다시 Alt 클릭: 모든 분판) Show: 표시: Shown with the optimised preview. 최적화된 미리 보기와 함께 표시됩니다. Side 1: 면 1: @@ -3847,6 +3873,8 @@ mark-style Japanese 일본식 User Swatch Library 9 사용자 견본 라이브러리 9 V Spacing: 세로 간격: Variable Width Profile 가변 너비 프로파일 + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. 선의 브러시는 고유한 크기를 유지하므로 너비 프로파일로 바뀌지 않습니다. 프로파일을 사용하려면 브러시를 제거하세요. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. 선의 브러시는 고유한 크기를 유지하므로 너비 프로파일로 바뀌지 않습니다. 프로파일을 사용하려면 브러시를 제거하세요. Variation: 변형: Vector Halftone 벡터 하프톤 Vector illustration — fast, open, scriptable. 벡터 일러스트레이션 — 빠르고 개방적이며 스크립트 지원. @@ -4522,6 +4550,7 @@ imageTrace Outline 윤곽선 Bevel 베벨 Offset 오프셋 Axis 축 + Axis Angle 축 각도 axis Horizontal 가로 axis Vertical 세로 axis Both 양쪽 @@ -4854,8 +4883,8 @@ variable-list-end {0}, {1} {0} 및 {1} @msg image would be too large; lower the resolution 이미지가 너무 커집니다. 해상도를 낮추세요 @msg clipboard is empty 클립보드가 비어 있습니다 @msg no anchor points selected 선택한 앵커 포인트가 없습니다 -@msg `points` must be three [x, y] pairs of numbers `points`는 숫자 쌍 [x, y] 세 개여야 합니다 -@msg direct-select three anchor points, or give `points` 앵커 포인트 세 개를 직접 선택하거나 `points`를 지정하세요 +@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`를 지정하세요 @msg no circle passes through these points: two are the same or all three lie on one line 이 점들을 지나는 원이 없습니다: 두 점이 같거나 세 점이 모두 한 직선 위에 있습니다 @msg select at least two objects 개체를 두 개 이상 선택하세요 @msg exit isolation mode first 먼저 격리 모드를 종료하세요 @@ -5229,6 +5258,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}이(가) 설치되어 있지 않습니다 @@ -5279,6 +5314,9 @@ variable-list-end {0}, {1} {0} 및 {1} @msg `{color}` is not a colour (#rrggbb or a preset name) `{color}`은(는) 색상이 아닙니다(#rrggbb 또는 프리셋 이름) @msg give the path `id` and the width point `index` 패스 `id`와 너비 점 `index`를 지정하세요 @msg no such width point 해당 너비 점이 없습니다 +@msg `single` must be `incoming` or `outgoing` `single`은 `incoming` 또는 `outgoing`이어야 합니다 +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index`와 `outIndex`는 하나의 불연속 너비 점의 두 절반이어야 합니다 +@msg a discontinuous width point keeps its place 불연속 너비 점은 위치를 유지합니다 @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 중 하나만 지정하세요 @@ -5543,6 +5581,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} @@ -5660,6 +5706,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}`은(는) 기본 제공 작업 영역입니다: 다른 이름을 선택하세요 @@ -5711,6 +5759,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 자동화 경로가 거부되었습니다: 경로가 비어 있습니다 @@ -5988,6 +6037,7 @@ lighting Light 광원 Cove 오목 Depth 깊이 Front 앞면 + Side 옆면 Isometric Bottom 등각 밑면 Isometric Left 등각 왼쪽 Isometric Right 등각 오른쪽 @@ -6082,7 +6132,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 and Revolve object types 그래픽은 평면, 돌출, 회전체 개체 유형에 매핑됩니다 @@ -7329,6 +7379,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 공통 접선 @@ -8427,6 +8485,7 @@ breakText Glyphs 글리프 @msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes 컴파운드 모양에는 패스, 컴파운드 패스, 그룹, 컴파운드 모양, 문자, 블렌드, 엔벨로프를 넣을 수 있습니다 @msg compound {_1} must contain exactly one open path to join 컴파운드 {_1}에는 연결할 열린 패스가 정확히 하나 있어야 합니다 @msg connect needs a path other than the one extended connect에는 연장한 패스가 아닌 다른 패스가 필요합니다 +@msg connect needs extend connect에는 extend가 필요합니다 @msg connect needs id connect에는 id가 필요합니다 @msg connect path has no open end connect 패스에 열린 끝이 없습니다 @msg continuation must be an array of path chunks continuation은 패스 조각의 배열이어야 합니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index f7f64ea240..ac9e496cde 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 @@ -2315,6 +2324,7 @@ digits Malayalam Malayalam Rule: Regel: Save changes to {name} Wijzigingen opslaan in {name} Save theme to My Themes Thema opslaan in Mijn thema's + Set the current fill or stroke to the selected color De huidige vulling of contour op de geselecteerde kleur instellen Set the selected color to the current color De geselecteerde kleur op de huidige kleur instellen Copy All Styles Alle stijlen kopiëren Exported {path} {path} geëxporteerd @@ -2673,7 +2683,7 @@ digits Malayalam Malayalam Overprint Preview (separations) Overprintvoorbeeld (separaties) Show All Plates Alle platen weergeven Show all plates Alle platen weergeven - Show/hide plate (Alt-click: only this plate) Plaat weergeven/verbergen (Alt-klik: alleen deze plaat) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Plaat weergeven/verbergen (Alt-klik: alleen deze plaat; nogmaals Alt-klik: alle platen) Simulate Paper Papier simuleren Use Black Point Compensation Zwartpuntcompensatie gebruiken Working CMYK (don't tag) Werk-CMYK (niet taggen) @@ -2713,6 +2723,8 @@ digits Malayalam Malayalam Tip extends past the end point Punt steekt uit voorbij het eindpunt Tip on the end point Punt op het eindpunt Variable Width Profile Variabel breedteprofiel + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Het penseel van de contour behoudt zijn eigen grootte, dus een breedteprofiel verandert de contour niet. Verwijder het penseel om een profiel te gebruiken. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Het penseel van de contour behoudt zijn eigen grootte, dus een breedteprofiel verandert de contour niet. Verwijder het penseel om een profiel te gebruiken. Weight: Dikte: Art using a deleted global swatch keeps its colour. Artwork met een verwijderd globaal staal behoudt zijn kleur. Color Group: {name} Kleurgroep: {name} @@ -2822,6 +2834,10 @@ digits Malayalam Malayalam Flip Horizontal Horizontaal spiegelen Flip Vertical Verticaal spiegelen Polygon Properties: Veelhoekeigenschappen: + Line Properties: Lijneigenschappen: + Line Length: Lijnlengte: + Line Angle: Lijnhoek: + Constrain Pie Angle Taarthoek vastleggen Rectangle Properties: Rechthoekeigenschappen: Shape Properties: Vormeigenschappen: Shape Properties Vormeigenschappen @@ -2863,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 @@ -2901,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: @@ -3565,6 +3583,8 @@ antiAlias Sharp Scherp Every option matches {base}. Elke optie komt overeen met {base}. Files of a PDF standard can't be password-protected. Bestanden volgens een PDF-standaard kunnen niet met een wachtwoord worden beveiligd. Files of this standard tag their colours with ICC profiles. Bestanden volgens deze standaard voorzien hun kleuren van ICC-profielen. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Bestanden volgens deze standaard voorzien hun kleuren van ICC-profielen, behalve CMYK-kleuren in het profiel voor uitvoerintentie, die als DeviceCMYK worden geschreven. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. Met ‘Geen profielen opnemen’ en een CMYK-uitvoerintentie wordt elke CMYK-kleur als DeviceCMYK geschreven, tenzij deze wordt omgezet naar een CMYK-bestemming met een ander profiel. Flattener preset: Voorinstelling voor afvlakking: General › Thumbnails Algemeen › Miniaturen Grayscale images Grijswaardenafbeeldingen @@ -3783,6 +3803,9 @@ antiAlias Sharp Scherp Variable Options Variabeleopties Define a variable first Definieer eerst een variabele Adjust Adjoining Width Points Aangrenzende breedtepunten aanpassen + Incoming Inkomend + Outgoing Uitgaand + Single Width Only Slechts één breedte Keep both sides the same width Beide zijden dezelfde breedte houden Side 1: Zijde 1: Side 2: Zijde 2: @@ -4171,6 +4194,7 @@ theme Appearance Vormgeving Select Art Kunst selecteren Set Current Layer Huidige laag instellen Flatten Artwork Kunst afvlakken + Locate Layer Laag lokaliseren Locate Object Object lokaliseren Lock Others Overigen vergrendelen Merge Selected Selectie samenvoegen @@ -4347,6 +4371,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 @@ -4373,6 +4398,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 @@ -4461,6 +4487,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. @@ -4857,6 +4886,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 @@ -4893,6 +4925,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. @@ -4989,6 +5022,8 @@ font-technology Variable Variabel Couldn't paste from the clipboard: {e} Kon niet vanaf het klembord plakken: {e} Channel Kanaal Circle Cirkel + Circle Tool Cirkelgereedschap + Circle too large Cirkel te groot Clip to Art Clippen op artwork Colorize Inkleuren Gamma Gamma @@ -5473,9 +5508,15 @@ 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 three [x, y] pairs of numbers `points` moet uit drie getallenparen [x, y] bestaan -@msg direct-select three anchor points, or give `points` selecteer met directe selectie drie ankerpunten of geef `points` op +@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 @msg no circle passes through these points: two are the same or all three lie on one line er gaat geen cirkel door deze punten: twee zijn gelijk of alle drie liggen op één lijn @msg no app to open files here hier is geen app om bestanden mee te openen @msg no artboard geen tekengebied @@ -5566,6 +5607,9 @@ imageTrace Outline Contour @msg no such user library gebruikersbibliotheek bestaat niet @msg no such view weergave bestaat niet @msg no such width point breedtepunt bestaat niet +@msg `single` must be `incoming` or `outgoing` `single` moet `incoming` of `outgoing` zijn +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` en `outIndex` moeten de twee helften van één onderbroken breedtepunt zijn +@msg a discontinuous width point keeps its place een onderbroken breedtepunt behoudt zijn plaats @msg no swatch `{name}` geen staal `{name}` @msg no swatch library `{l}` (see swatch.library.list) geen stalenbibliotheek `{l}` (zie swatch.library.list) @msg no symbol instances selected geen symboolinstanties geselecteerd @@ -5875,6 +5919,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 @@ -6448,6 +6494,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 @@ -6647,6 +6694,7 @@ imageTrace Outline Contour @msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes samengestelde vormen accepteren paden, samengestelde paden, groepen, samengestelde vormen, tekst, mengsels en omvormingen @msg compound {_1} must contain exactly one open path to join samengesteld object {_1} moet precies één open pad bevatten om te verbinden @msg connect needs a path other than the one extended connect heeft een ander pad nodig dan het pad dat wordt verlengd +@msg connect needs extend connect heeft extend nodig @msg connect needs id connect heeft id nodig @msg connect path has no open end het pad van connect heeft geen open uiteinde @msg continuation must be an array of path chunks continuation moet een array van padstukken zijn @@ -8159,6 +8207,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 @@ -8253,7 +8302,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 @@ -9623,6 +9672,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 18e70c4e2a..091e3622ad 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 @@ -1733,6 +1734,7 @@ digits Malayalam Malajalam Rule: Reguła: Save changes to {name} Zapisz zmiany w {name} Save theme to My Themes Zapisz motyw w Moich motywach + Set the current fill or stroke to the selected color Ustaw bieżące wypełnienie lub obrys na zaznaczony kolor Set the selected color to the current color Ustaw zaznaczony kolor na bieżący Copy All Styles Kopiuj wszystkie style Exported {path} Wyeksportowano {path} @@ -2203,7 +2205,7 @@ digits Malayalam Malajalam Overprint Preview (separations) Podgląd nadruku (rozbarwienia) Show All Plates Pokaż wszystkie płyty Show all plates Pokaż wszystkie płyty - Show/hide plate (Alt-click: only this plate) Pokaż/ukryj płytę (kliknięcie z Alt: tylko ta płyta) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Pokaż/ukryj płytę (kliknięcie z Alt: tylko ta płyta; ponowne kliknięcie z Alt: wszystkie płyty) Simulate Paper Symuluj papier Use Black Point Compensation Użyj kompensacji punktu czerni Working CMYK (don't tag) Roboczy CMYK (bez znacznika) @@ -2243,11 +2245,13 @@ digits Malayalam Malajalam Tip extends past the end point Czubek wystaje poza punkt końcowy Tip on the end point Czubek na punkcie końcowym Variable Width Profile Profil zmiennej szerokości + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Pędzel obrysu zachowuje własny rozmiar, więc profil szerokości go nie zmienia. Usuń pędzel, aby użyć profilu. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Pędzel obrysu zachowuje własny rozmiar, więc profil szerokości go nie zmienia. Usuń pędzel, aby użyć profilu. 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 @@ -2353,6 +2357,10 @@ digits Malayalam Malajalam Flip Horizontal Odbij w poziomie Flip Vertical Odbij w pionie Polygon Properties: Właściwości wielokąta: + 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 @@ -2393,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 @@ -2431,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: @@ -2685,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 @@ -3085,6 +3095,8 @@ antiAlias Sharp Ostre Every option matches {base}. Wszystkie opcje są zgodne z {base}. Files of a PDF standard can't be password-protected. Plików standardu PDF nie można chronić hasłem. Files of this standard tag their colours with ICC profiles. Pliki tego standardu oznaczają kolory profilami ICC. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Pliki tego standardu oznaczają kolory profilami ICC, z wyjątkiem kolorów CMYK w profilu docelowych warunków wyjściowych, które są zapisywane jako DeviceCMYK. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. Przy opcji „Nie dołączaj profili” i docelowych warunkach wyjściowych CMYK każdy kolor CMYK jest zapisywany jako DeviceCMYK, chyba że zostanie przekonwertowany do miejsca docelowego CMYK z innym profilem. Flattener preset: Ustawienie spłaszczania: General › Thumbnails Ogólne › Miniatury Grayscale images Obrazy w skali szarości @@ -3261,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} @@ -3330,6 +3342,9 @@ antiAlias Sharp Ostre Variable Options Opcje zmiennej Define a variable first Najpierw zdefiniuj zmienną Adjust Adjoining Width Points Dopasuj sąsiednie punkty szerokości + Incoming Wejściowa + Outgoing Wyjściowa + Single Width Only Tylko jedna szerokość Keep both sides the same width Zachowaj jednakową szerokość obu stron Side 1: Strona 1: Side 2: Strona 2: @@ -3738,6 +3753,7 @@ theme Appearance Wygląd Select Art Zaznacz kompozycję Set Current Layer Ustaw bieżącą warstwę Flatten Artwork Spłaszcz kompozycję + Locate Layer Znajdź warstwę Locate Object Znajdź obiekt Lock Others Zablokuj pozostałe Merge Selected Scal zaznaczone @@ -3912,6 +3928,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 @@ -3938,6 +3955,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 @@ -4026,6 +4044,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. @@ -4411,6 +4432,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 @@ -4434,23 +4458,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. @@ -4463,7 +4488,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. @@ -4509,22 +4534,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? @@ -4543,6 +4568,8 @@ font-technology Variable Zmienne Couldn't paste from the clipboard: {e} Nie udało się wkleić ze schowka: {e} Channel Kanał Circle Okrąg + Circle Tool Narzędzie Okrąg + Circle too large Okrąg jest za duży Clip to Art Przytnij do kompozycji Colorize Koloruj Gamma Gamma @@ -5168,7 +5195,7 @@ 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 @@ -5243,9 +5270,15 @@ 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 three [x, y] pairs of numbers `points` musi zawierać trzy pary liczb [x, y] -@msg direct-select three anchor points, or give `points` zaznacz bezpośrednio trzy punkty kontrolne lub podaj `points` +@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` @msg no circle passes through these points: two are the same or all three lie on one line przez te punkty nie przechodzi żaden okrąg: dwa są takie same albo wszystkie trzy leżą na jednej prostej @msg no app to open files here brak aplikacji do otwierania plików @msg no artboard brak obszaru kompozycji @@ -5347,6 +5380,9 @@ liquify-list-end {0}, {1} {0} i {1} @msg no such user library brak takiej biblioteki użytkownika @msg no such view brak takiego widoku @msg no such width point brak takiego punktu szerokości +@msg `single` must be `incoming` or `outgoing` `single` musi mieć wartość `incoming` lub `outgoing` +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` i `outIndex` muszą być dwiema połówkami jednego nieciągłego punktu szerokości +@msg a discontinuous width point keeps its place nieciągły punkt szerokości zachowuje swoje położenie @msg no swatch `{name}` brak próbki `{name}` @msg no swatch library `{l}` (see swatch.library.list) brak biblioteki próbek `{l}` (patrz swatch.library.list) @msg no symbol instances selected nie zaznaczono wystąpień symboli @@ -5714,6 +5750,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 @@ -5724,7 +5762,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 @@ -5748,7 +5786,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 @@ -5781,7 +5819,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} @@ -5804,6 +5842,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 @@ -6237,6 +6276,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 @@ -6309,11 +6349,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ą @@ -6331,21 +6371,21 @@ 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 and Revolve object types Grafiki są nakładane na obiekty typu Płaszczyzna, Wyciągnięcie i Obrót @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 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 @@ -6600,8 +6640,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 @@ -6660,7 +6700,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 @@ -7097,7 +7137,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 @@ -7216,7 +7256,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 @@ -7238,7 +7278,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 @@ -7555,9 +7595,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 @@ -7595,6 +7635,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 @@ -7679,7 +7727,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 @@ -7735,7 +7783,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 @@ -7913,9 +7961,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% @@ -7958,11 +8006,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 @@ -7971,6 +8019,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] @@ -8160,8 +8216,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 @@ -8211,7 +8267,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] @@ -8224,7 +8280,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}` @@ -8251,7 +8307,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ę @@ -8285,8 +8341,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ą @@ -8295,7 +8351,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 @@ -8365,7 +8421,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} @@ -8554,7 +8610,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 @@ -8595,7 +8651,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} @@ -8707,7 +8763,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 @@ -8801,6 +8857,7 @@ breakText Glyphs Glify @msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes kształty złożone przyjmują ścieżki, ścieżki złożone, grupy, kształty złożone, tekst, przejścia i koperty @msg compound {_1} must contain exactly one open path to join obiekt złożony {_1} musi zawierać dokładnie jedną otwartą ścieżkę do połączenia @msg connect needs a path other than the one extended connect wymaga ścieżki innej niż przedłużana +@msg connect needs extend connect wymaga extend @msg connect needs id connect wymaga id @msg connect path has no open end ścieżka w connect nie ma otwartego końca @msg copy needs path: the file to copy into the document's folder copy wymaga path: pliku do skopiowania do folderu dokumentu @@ -8981,7 +9038,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 @@ -9100,7 +9157,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 @@ -9163,7 +9220,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) @@ -9223,10 +9280,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 @@ -9273,12 +9330,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 @@ -9292,7 +9349,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 @@ -9373,9 +9430,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 @@ -9388,11 +9445,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 @@ -9466,7 +9523,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 @@ -9501,7 +9558,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}` @@ -9516,7 +9573,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ć @@ -9529,10 +9586,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 @@ -9751,7 +9808,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 @@ -9799,7 +9856,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 e4c0468c95..c382eddada 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -147,8 +147,12 @@ 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 + Outgoing Saída + Single Width Only Somente Uma Largura Adjust Color Balance… Ajustar Equilíbrio de Cores… Adjust Colors Ajustar Cores Adjust Options: Opções de Ajuste: @@ -460,6 +464,8 @@ antiAlias Sharp Nítido Choose a folder Escolher uma pasta Choose… Escolher… Circle Círculo + Circle Tool Ferramenta Círculo + Circle too large Círculo grande demais Clean Up… Limpar… Clear Limpar Clear All Tabs Limpar Todas as Paradas de Tabulação @@ -794,6 +800,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 @@ -1166,6 +1173,8 @@ antiAlias Sharp Nítido Files Arquivos Files of a PDF standard can't be password-protected. Arquivos de um padrão PDF não podem ser protegidos por senha. Files of this standard tag their colours with ICC profiles. Os arquivos deste padrão etiquetam suas cores com perfis ICC. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Os arquivos deste padrão etiquetam suas cores com perfis ICC, exceto as cores CMYK no perfil de intenção de saída, que são gravadas como DeviceCMYK. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. Com “Não incluir perfis” e uma intenção de saída CMYK, cada cor CMYK é gravada como DeviceCMYK, a menos que seja convertida para um destino CMYK de outro perfil. Fill Preenchimento Fill & Stroke Preenchimento e Traçado Fill Color Cor de Preenchimento @@ -1739,6 +1748,7 @@ antiAlias Sharp Nítido Load SVG into Clipboard Carregar SVG na Área de Transferência Load Text into Clipboard Carregar Texto na Área de Transferência Local Libraries Bibliotecas Locais + Locate Layer Localizar Camada Locate Object Localizar Objeto Location Local Location: Local: @@ -2253,6 +2263,10 @@ antiAlias Sharp Nítido Polar Grid Tool Ferramenta Grade Polar Polygon Polígono Polygon Properties: Propriedades do Polígono: + 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 @@ -2395,6 +2409,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. @@ -2631,6 +2648,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. @@ -2907,6 +2925,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 @@ -2978,6 +2999,7 @@ digits Malayalam Malaiala Set Text Definir Texto Set Zoom Definir Zoom Set base color to the current color Definir cor base para a cor atual + Set the current fill or stroke to the selected color Definir o preenchimento ou traçado atual para a cor selecionada Set the selected color to the current color Definir a cor selecionada para a cor atual Setup… Configuração… Shadows and Glows Sombras e Brilhos @@ -3085,7 +3107,7 @@ digits Malayalam Malaiala Show handles when multiple anchors are selected Mostrar alças quando vários pontos de ancoragem estão selecionados Show in Folder Mostrar na Pasta Show {kind} Brushes Mostrar Pincéis de {kind} - Show/hide plate (Alt-click: only this plate) Mostrar/ocultar placa (Alt-clique: somente esta placa) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Mostrar/ocultar placa (Alt-clique: somente esta placa; Alt-clique de novo: todas as placas) Show: Mostrar: Shown with the optimised preview. Exibido com a visualização otimizada. Side 1: Lado 1: @@ -3491,6 +3513,8 @@ digits Malayalam Malaiala V Spacing: Espaçamento V: V: V: Variable Width Profile Perfil de Largura Variável + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. O pincel do traçado mantém o próprio tamanho, então um perfil de largura não o altera. Remova o pincel para usar um perfil. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. O pincel do traçado mantém o próprio tamanho, então um perfil de largura não o altera. Remova o pincel para usar um perfil. Variables Variáveis New Variable… Nova variável… Unbind Variable Desassociar variável @@ -3899,6 +3923,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 @@ -4391,9 +4416,15 @@ 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 three [x, y] pairs of numbers `points` deve ter três pares de números [x, y] -@msg direct-select three anchor points, or give `points` selecione diretamente três pontos de ancoragem ou informe `points` +@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` @msg no circle passes through these points: two are the same or all three lie on one line nenhum círculo passa por esses pontos: dois são iguais ou os três estão na mesma reta @msg no app to open files here nenhum aplicativo para abrir arquivos aqui @msg no artboard nenhuma prancheta @@ -4495,6 +4526,9 @@ axis Both Ambos @msg no such user library biblioteca do usuário inexistente @msg no such view vista inexistente @msg no such width point ponto de largura inexistente +@msg `single` must be `incoming` or `outgoing` `single` deve ser `incoming` ou `outgoing` +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` e `outIndex` devem ser as duas metades de um mesmo ponto de largura descontínuo +@msg a discontinuous width point keeps its place um ponto de largura descontínuo mantém sua posição @msg no swatch `{name}` nenhuma amostra `{name}` @msg no swatch library `{l}` (see swatch.library.list) nenhuma biblioteca de amostras `{l}` (veja swatch.library.list) @msg no symbol instances selected nenhuma instância de símbolo selecionada @@ -4857,6 +4891,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 @@ -4936,6 +4972,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 @@ -5418,6 +5455,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 @@ -5693,6 +5731,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 @@ -6363,6 +6402,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 @@ -6457,7 +6497,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 and Revolve object types Os gráficos são mapeados nos tipos de objeto Plano, Extrusão e Revolver @@ -7759,6 +7799,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 @@ -8344,6 +8392,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] @@ -8887,6 +8943,7 @@ swatch Yellow Green Verde-amarelado @msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes formas compostas aceitam caminhos, caminhos compostos, grupos, formas compostas, texto, mesclagens e envelopes @msg compound {_1} must contain exactly one open path to join o composto {_1} deve conter exatamente um caminho aberto para unir @msg connect needs a path other than the one extended connect precisa de um caminho diferente do que foi estendido +@msg connect needs extend connect precisa de extend @msg connect needs id connect precisa de id @msg connect path has no open end o caminho de connect não tem extremidade aberta @msg continuation must be an array of path chunks continuation deve ser uma matriz de trechos de caminho diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index f387bed74d..cd5956df34 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -139,8 +139,12 @@ Add to Swatches Добавить в образцы Add Used Colors Добавить использованные цвета Additional Plug-ins Folder Папка дополнительных модулей + Plug-in Instruction Budget Бюджет инструкций модулей Additional Fonts Folder Папка дополнительных шрифтов Adjust Adjoining Width Points Настроить смежные точки ширины + Incoming Входящая + Outgoing Исходящая + Single Width Only Только одна ширина Adjust Color Balance… Настроить цветовой баланс… Adjust Colors Настроить цвета Adjust Options: Параметры настройки: @@ -491,6 +495,8 @@ font-technology Variable Вариативные Choose a folder Выберите папку Choose… Выбрать… Circle Круг + Circle Tool Инструмент «Круг» + Circle too large Круг слишком большой Classic Defaults Классические значения по умолчанию Clean Up… Очистить… Clear Очистить @@ -880,6 +886,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 Отменить пустой текст @@ -1279,6 +1286,8 @@ font-technology Variable Вариативные Files Файлы Files of a PDF standard can't be password-protected. Файлы стандарта PDF не могут быть защищены паролем. Files of this standard tag their colours with ICC profiles. Файлы этого стандарта помечают свои цвета профилями ICC. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Файлы этого стандарта помечают свои цвета профилями ICC, кроме цветов CMYK в профиле назначения вывода, которые записываются как DeviceCMYK. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. При «Не включать профили» и назначении вывода CMYK каждый цвет CMYK записывается как DeviceCMYK, если он не преобразуется в назначение CMYK с другим профилем. Fill Заливка Fill & Stroke Заливка и обводка Fill (X), double-click for the Color Picker Заливка (X), дважды щёлкните для палитры цветов @@ -2084,6 +2093,7 @@ file-filter Templates Шаблоны Load SVG into Clipboard Загрузить SVG в буфер обмена Load Text into Clipboard Загрузить текст в буфер обмена Local Libraries Локальные библиотеки + Locate Layer Найти слой Locate Object Найти объект Locate Selected Objects Находить выделенные объекты Location Расположение @@ -2278,6 +2288,7 @@ file-filter Templates Шаблоны Scatter: Рассеивание: Rotation: Поворот: Rotation relative to: Поворот относительно: + Hue Jitter: Разброс тона: Brush Scale Options Параметры масштабирования кисти Scale Proportionately Масштабировать пропорционально Stretch to Fit Stroke Length Растянуть по длине обводки @@ -2314,6 +2325,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 Нажим @@ -2751,6 +2763,10 @@ diagnostics ui интерфейс Polar Grid Tool Инструмент «Полярная сетка» Polygon Многоугольник Polygon Properties: Свойства многоугольника: + Line Properties: Свойства линии: + Line Length: Длина линии: + Line Angle: Угол линии: + Constrain Pie Angle Сохранять угол сектора Polygon Tool Инструмент «Многоугольник» Portrait Книжная Power Saving (integrated) Энергосбережение (встроенная) @@ -2912,6 +2928,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. Система согласует цвета окна с дисплеем. @@ -3174,6 +3193,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. «Создать метки подрезки» рисует метки в японском стиле вместо западных. @@ -3485,6 +3505,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 Недавние команды @@ -3565,6 +3588,7 @@ digits Malayalam Малаялам Set Slice Rectangle Задать прямоугольник фрагмента Set Tab Stops Задать табуляции Set Text Задать текст + Set the current fill or stroke to the selected color Назначить выбранный цвет текущей заливке или обводке Set the selected color to the current color Назначить текущий цвет выбранному цвету Set Zoom Задать масштаб Settings… Параметры… @@ -3688,7 +3712,7 @@ digits Malayalam Малаялам Show Vivid/Muted Показать яркие/приглушённые Show Warm/Cool Показать тёплые/холодные Show {kind} Brushes Показать кисти {kind} - Show/hide plate (Alt-click: only this plate) Показать/скрыть пластину (Alt+щелчок: только эту пластину) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Показать/скрыть пластину (Alt+щелчок: только эту пластину; повторный Alt+щелчок: все пластины) Show: Показать: Shown with the optimised preview. Показано с оптимизированным просмотром. Side 1: Сторона 1: @@ -4292,6 +4316,8 @@ digits Malayalam Малаялам V Spacing: Интервал по вертикали: V: В: Variable Width Profile Профиль переменной ширины + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Кисть обводки сохраняет собственный размер, поэтому профиль ширины её не меняет. Чтобы использовать профиль, уберите кисть. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Кисть обводки сохраняет собственный размер, поэтому профиль ширины её не меняет. Чтобы использовать профиль, уберите кисть. Variables Переменные New Variable Новая переменная Delete Variable Удалить переменную @@ -4575,6 +4601,7 @@ imageTrace Outline Контур Bevel Скос Offset Смещение Axis Ось + Axis Angle Угол оси axis Horizontal Горизонтально axis Vertical Вертикально axis Both Оба @@ -4813,6 +4840,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} @@ -5146,9 +5181,15 @@ 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 three [x, y] pairs of numbers `points` должен содержать три пары чисел [x, y] -@msg direct-select three anchor points, or give `points` выделите прямым выделением три опорные точки или задайте `points` +@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` @msg no circle passes through these points: two are the same or all three lie on one line через эти точки не проходит ни одна окружность: две точки совпадают или все три лежат на одной прямой @msg no app to open files here здесь нет приложения для открытия файлов @msg no artboard нет монтажной области @@ -5250,6 +5291,9 @@ liquify-list-end {0}, {1} {0} и {1} @msg no such user library такой пользовательской библиотеки нет @msg no such view такого вида нет @msg no such width point такой точки ширины нет +@msg `single` must be `incoming` or `outgoing` `single` должен быть `incoming` или `outgoing` +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` и `outIndex` должны быть двумя половинами одной разрывной точки ширины +@msg a discontinuous width point keeps its place разрывная точка ширины сохраняет своё место @msg no swatch `{name}` нет образца `{name}` @msg no swatch library `{l}` (see swatch.library.list) нет библиотеки образцов `{l}` (см. swatch.library.list) @msg no symbol instances selected экземпляры символов не выделены @@ -5617,6 +5661,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 @@ -5735,6 +5781,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 путь автоматизации отклонён: путь пуст @@ -6017,6 +6064,7 @@ lighting Light Свет Cove Выкружка Depth Глубина Front Спереди + Side Сбоку Isometric Bottom Изометрия снизу Isometric Left Изометрия слева Isometric Right Изометрия справа @@ -6111,7 +6159,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 and Revolve object types Графика наносится на объекты типов «Плоскость», «Выдавливание» и «Вращение» @@ -7722,6 +7770,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 Общие касательные @@ -8806,6 +8862,7 @@ shape Open Открытый @msg compound {_1} must contain exactly one open path to join составной объект {_1} должен содержать ровно один открытый контур для соединения @msg connect end must be "start" or "end" end для connect должно быть "start" или "end" @msg connect needs a path other than the one extended для connect нужен контур, отличный от продлеваемого +@msg connect needs extend для connect нужен extend @msg connect needs id для connect нужен id @msg connect path has no open end у контура для connect нет открытого конца @msg continuation must be an array of path chunks continuation должно быть массивом фрагментов контура diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 9336b09ee7..43eec441c4 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -129,8 +129,12 @@ 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 + Outgoing Utgående + Single Width Only Endast en bredd Adjust Color Balance… Justera färgbalans… Adjust Colors Justera färger Adjust Options: Justeringsalternativ: @@ -482,6 +486,8 @@ font-technology Variable Variabla Choose a folder Välj en mapp Choose… Välj… Circle Cirkel + Circle Tool Cirkelverktyg + Circle too large Cirkeln är för stor Classic Defaults Klassiska standardvärden Clean Up… Rensa upp… Clear Rensa @@ -870,6 +876,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 @@ -1252,6 +1259,8 @@ font-technology Variable Variabla Files Filer Files of a PDF standard can't be password-protected. Filer enligt en PDF-standard kan inte lösenordsskyddas. Files of this standard tag their colours with ICC profiles. Filer enligt den här standarden märker sina färger med ICC-profiler. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Filer enligt den här standarden märker sina färger med ICC-profiler, utom CMYK-färger i profilen för utgångsavsikt, som skrivs som DeviceCMYK. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. Med ”Inkludera inte profiler” och en CMYK-utgångsavsikt skrivs varje CMYK-färg som DeviceCMYK, om den inte konverteras till ett CMYK-mål med en annan profil. Fill Fyllning Fill & Stroke Fyllning och kontur Fill (X), double-click for the Color Picker Fyllning (X), dubbelklicka för färgväljaren @@ -1991,6 +2000,7 @@ font-technology Variable Variabla Load SVG into Clipboard Läs in SVG till urklipp Load Text into Clipboard Läs in text till urklipp Local Libraries Lokala bibliotek + Locate Layer Hitta lager Locate Object Hitta objekt Locate Selected Objects Hitta markerade objekt Location Plats @@ -2185,6 +2195,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 @@ -2221,6 +2232,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 @@ -2649,6 +2661,10 @@ font-technology Variable Variabla Polar Grid Tool Verktyg för polärt rutnät Polygon Polygon Polygon Properties: Polygonegenskaper: + 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) @@ -2808,6 +2824,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. @@ -3068,6 +3087,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. @@ -3365,6 +3385,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 @@ -3445,6 +3468,7 @@ digits Malayalam Malayalam Set Slice Rectangle Ange skivrektangel Set Tab Stops Ange tabbstopp Set Text Ange text + Set the current fill or stroke to the selected color Ersätt den aktuella fyllningen eller konturen med den markerade färgen Set the selected color to the current color Ersätt den markerade färgen med den aktuella färgen Set Zoom Ange zoom Settings… Inställningar… @@ -3566,7 +3590,7 @@ digits Malayalam Malayalam Show Vivid/Muted Visa livfull/dämpad Show Warm/Cool Visa varm/kall Show {kind} Brushes Visa {kind}-penslar - Show/hide plate (Alt-click: only this plate) Visa/dölj plåt (Alt-klick: endast den här plåten) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Visa/dölj plåt (Alt-klick: endast den här plåten; Alt-klick igen: alla plåtar) Show: Visa: Shown with the optimised preview. Visas med den optimerade förhandsgranskningen. Side 1: Sida 1: @@ -4175,6 +4199,8 @@ digits Malayalam Malayalam V Spacing: V-avstånd: V: V: Variable Width Profile Profil för variabel bredd + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Konturens pensel behåller sin egen storlek, så en breddprofil ändrar inte konturen. Ta bort penseln för att använda en profil. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Konturens pensel behåller sin egen storlek, så en breddprofil ändrar inte konturen. Ta bort penseln för att använda en profil. Variables Variabler New Variable Ny variabel Delete Variable Radera variabel @@ -4448,6 +4474,7 @@ imageTrace Outline Kontur Bevel Fasning Offset Förskjutning Axis Axel + Axis Angle Axelvinkel axis Horizontal Horisontell axis Vertical Vertikal axis Both Båda @@ -4694,6 +4721,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} @@ -5015,9 +5050,15 @@ 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 three [x, y] pairs of numbers `points` måste vara tre talpar [x, y] -@msg direct-select three anchor points, or give `points` direktmarkera tre ankarpunkter eller ange `points` +@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` @msg no circle passes through these points: two are the same or all three lie on one line ingen cirkel går genom de här punkterna: två är samma punkt eller så ligger alla tre på en linje @msg no app to open files here det finns ingen app för att öppna filer här @msg no artboard ingen rityta @@ -5119,6 +5160,9 @@ liquify-list-end {0}, {1} {0} och {1} @msg no such user library användarbiblioteket finns inte @msg no such view vyn finns inte @msg no such width point breddpunkten finns inte +@msg `single` must be `incoming` or `outgoing` `single` måste vara `incoming` eller `outgoing` +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` och `outIndex` måste vara de två halvorna av en och samma diskontinuerliga breddpunkt +@msg a discontinuous width point keeps its place en diskontinuerlig breddpunkt behåller sin plats @msg no swatch `{name}` ingen färgruta `{name}` @msg no swatch library `{l}` (see swatch.library.list) inget färgrutebibliotek `{l}` (se swatch.library.list) @msg no symbol instances selected inga symbolinstanser är markerade @@ -5477,6 +5521,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 @@ -5613,6 +5659,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 @@ -5889,6 +5936,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 @@ -5984,7 +6032,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 and Revolve object types Grafik placeras på objekttyperna Plan, Extrudera och Rotera runt axel @@ -7766,6 +7814,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 @@ -8473,6 +8529,7 @@ digits Hindi Hindi @msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes sammansatta former tar banor, sammansatta banor, grupper, sammansatta former, text, övergångar och kuvert @msg connect end must be "start" or "end" connect end måste vara "start" eller "end" @msg connect needs a path other than the one extended connect behöver en annan bana än den som förlängs +@msg connect needs extend connect behöver extend @msg connect needs id connect behöver id @msg connect path has no open end connect-banan har ingen öppen ände @msg Contour: select paths or shapes Kontur: markera banor eller former diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 9fdcc038e9..1ef955c627 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] @@ -607,6 +634,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.", @@ -776,6 +804,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] @@ -3577,9 +3620,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"]), @@ -5109,6 +5152,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] @@ -5199,6 +5291,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] @@ -5950,7 +6121,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"]), ( @@ -6156,7 +6327,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), @@ -6179,6 +6351,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 @@ -6778,6 +6951,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 b4a8c3d133..4fafc4258a 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -126,8 +126,12 @@ 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 + Outgoing Giden + Single Width Only Yalnızca Tek Genişlik Adjust Color Balance… Renk Dengesini Ayarlayın… Adjust Colors Renkleri Ayarla Adjust Options: Seçenekleri Ayarlayın: @@ -475,6 +479,8 @@ font-technology Variable Değişken Choose a folder Bir klasör seçin Choose… Seç… Circle daire + Circle Tool Daire Aracı + Circle too large Daire çok büyük Classic Defaults Klasik Varsayılanlar Clean Up… Temizleme… Clear Temizle @@ -861,6 +867,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 @@ -1242,6 +1249,8 @@ font-technology Variable Değişken Files Dosyalar Files of a PDF standard can't be password-protected. PDF standardının dosyaları parola korumalı olamaz. Files of this standard tag their colours with ICC profiles. Bu standardın dosyaları renklerini ICC profilleriyle etiketler. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Bu standardın dosyaları renklerini ICC profilleriyle etiketler, ancak çıkış amacı profilindeki CMYK renkleri DeviceCMYK olarak yazılır. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. “Profilleri ekleme” ve bir CMYK çıkış amacıyla, başka bir profilin CMYK hedefine dönüştürülmedikçe her CMYK rengi DeviceCMYK olarak yazılır. Fill Dolgu Fill & Stroke Doldur ve Konturla Fill (X), double-click for the Color Picker Doldur (X), Renk Seçici için çift tıklayın @@ -1878,6 +1887,7 @@ font-technology Variable Değişken Load SVG into Clipboard SVG'yi Panoya yükleyin Load Text into Clipboard Metni Panoya Yükle Local Libraries Yerel Kütüphaneler + Locate Layer Katmanı Bul Locate Object Nesneyi Bul Location Konum Location: Konum: @@ -2066,6 +2076,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 @@ -2095,6 +2106,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ç @@ -2496,6 +2508,10 @@ shape Open Açık Polar Grid Tool Yuvarlak Izgara Aracı Polygon Çokgen Polygon Properties: Poligon Özellikleri: + 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) @@ -2654,6 +2670,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. @@ -2911,6 +2930,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. @@ -3243,6 +3263,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 @@ -3323,6 +3346,7 @@ digits Malayalam Malayalam Set Slice Rectangle Dilim Dikdörtgenini Ayarla Set Tab Stops Sekme Duraklarını Ayarla Set Text Metni Ayarla + Set the current fill or stroke to the selected color Geçerli dolguyu veya konturu seçilen renge ayarla Set the selected color to the current color Seçilen rengi geçerli renge ayarla Set Zoom Yakınlaştırmayı Ayarla Settings… Ayarlar… @@ -3443,7 +3467,7 @@ digits Malayalam Malayalam Show Vivid/Muted Canlı/Sessiz Göster Show Warm/Cool Sıcak/Soğuk Göster Show {kind} Brushes {kind} Fırçalarını Göster - Show/hide plate (Alt-click: only this plate) Plakayı göster/gizle (Alt tuşuyla tıklayın: yalnızca bu plaka) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Plakayı göster/gizle (Alt tuşuyla tıklayın: yalnızca bu plaka; yeniden Alt tuşuyla tıklayın: tüm plakalar) Show: Göster: Shown with the optimised preview. Optimize edilmiş önizlemeyle gösterilir. Side 1: 1. Taraf: @@ -4031,6 +4055,8 @@ digits Malayalam Malayalam V Spacing: V Aralığı: V: V: Variable Width Profile Değişken Genişlik Profili + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Konturun fırçası kendi boyutunu korur, bu yüzden genişlik profili konturu değiştirmez. Profil kullanmak için fırçayı kaldırın. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Konturun fırçası kendi boyutunu korur, bu yüzden genişlik profili konturu değiştirmez. Profil kullanmak için fırçayı kaldırın. Variables Değişkenler New Variable Yeni Değişken Delete Variable Değişkeni Sil @@ -4302,6 +4328,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 @@ -4528,6 +4555,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} @@ -4839,9 +4874,15 @@ 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 three [x, y] pairs of numbers `points` üç [x, y] sayı çifti olmalıdır -@msg direct-select three anchor points, or give `points` üç bağlantı noktasını doğrudan seçin veya `points` verin +@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 @msg no circle passes through these points: two are the same or all three lie on one line bu noktalardan geçen bir çember yok: ikisi aynı ya da üçü de aynı doğru üzerinde @msg no app to open files here burada dosyaları açacak uygulama yok @msg no artboard çalışma yüzeyi yok @@ -4937,6 +4978,9 @@ liquify-list-end {0}, {1} {0} ve {1} @msg no such user library böyle bir kullanıcı kütüphanesi yok @msg no such view öyle bir görüş yok @msg no such width point böyle bir genişlik noktası yok +@msg `single` must be `incoming` or `outgoing` `single`, `incoming` veya `outgoing` olmalıdır +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` ve `outIndex`, tek bir süreksiz genişlik noktasının iki yarısı olmalıdır +@msg a discontinuous width point keeps its place süreksiz genişlik noktası yerini korur @msg no swatch `{name}` renk örneği yok `{name}` @msg no swatch library `{l}` (see swatch.library.list) renk örneği kitaplığı yok `{l}` (bkz. swatch.library.list) @msg no symbol instances selected sembol örneği seçilmedi @@ -5303,6 +5347,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 @@ -5645,7 +5691,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ü @@ -5716,6 +5762,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ğ @@ -5810,7 +5857,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 and Revolve object types Grafikler Düzlem, Ekstrüzyon ve Eksen Etrafında Döndür nesne türlerine eşlenir @@ -5833,22 +5880,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ış @@ -7488,7 +7535,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} @@ -7557,6 +7604,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) @@ -7629,7 +7677,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 @@ -8088,6 +8136,7 @@ axis Y Axis Y ekseni @msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes bileşik şekiller yolları, bileşik yolları, grupları, bileşik şekilleri, metni, karışımları ve zarfları alır @msg compound {_1} must contain exactly one open path to join bileşik {_1}, birleştirilecek tam olarak bir açık yol içermelidir @msg connect needs a path other than the one extended connect için uzatılan yoldan başka bir yol gerekir +@msg connect needs extend connect için extend gerekir @msg connect needs id connect için id gerekir @msg connect path has no open end connect yolunun açık ucu yok @msg copy needs path: the file to copy into the document's folder copy için path gerekir: belgenin klasörüne kopyalanacak dosya @@ -9621,6 +9670,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 58fccabd0c..d6adb88c94 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -135,8 +135,12 @@ Add to Swatches Додати до зразків Add Used Colors Додати використані кольори Additional Plug-ins Folder Папка додаткових модулів + Plug-in Instruction Budget Бюджет інструкцій модулів Additional Fonts Folder Папка додаткових шрифтів Adjust Adjoining Width Points Налаштувати суміжні точки ширини + Incoming Вхідна + Outgoing Вихідна + Single Width Only Лише одна ширина Adjust Color Balance… Налаштувати колірний баланс… Adjust Colors Налаштувати кольори Adjust Options: Параметри налаштування: @@ -489,6 +493,8 @@ font-technology Variable Варіативні Choose a folder Виберіть папку Choose… Вибрати… Circle Коло + Circle Tool Інструмент «Коло» + Circle too large Коло завелике Classic Defaults Класичні значення за промовчанням Clean Up… Очистити… Clear Очистити @@ -878,6 +884,7 @@ font-technology Variable Варіативні Direct Selection Tool Інструмент «Пряме виділення» Direction Handles Маркери напряму Disable Auto Add/Delete Вимкнути авто-додавання/видалення + Interpolate Control Points When Moving Anchors Інтерполювати маркери напряму під час переміщення опорних точок Disable Opacity Mask Вимкнути маску непрозорості Discard Відкинути Preserve Зберігати @@ -1287,6 +1294,8 @@ font-technology Variable Варіативні Files Файли Files of a PDF standard can't be password-protected. Файли стандарту PDF не можуть бути захищені паролем. Files of this standard tag their colours with ICC profiles. Файли цього стандарту позначають свої кольори профілями ICC. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Файли цього стандарту позначають свої кольори профілями ICC, крім кольорів CMYK у профілі призначення виведення, які записуються як DeviceCMYK. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. З «Не включати профілі» та призначенням виведення CMYK кожен колір CMYK записується як DeviceCMYK, якщо його не перетворено в призначення CMYK з іншим профілем. Fill Заливка Fill & Stroke Заливка та обведення Fill (X), double-click for the Color Picker Заливка (X), двічі клацніть на палітрі кольорів @@ -2092,6 +2101,7 @@ file-filter Templates Шаблони Load SVG into Clipboard Завантажити SVG у буфер обміну Load Text into Clipboard Завантажити текст у буфер обміну Local Libraries Локальні бібліотеки + Locate Layer Знайти шар Locate Object Знайти об’єкт Locate Selected Objects Знаходити виділені об’єкти Location Розташування @@ -2286,6 +2296,7 @@ file-filter Templates Шаблони Scatter: Розсіювання: Rotation: Поворот: Rotation relative to: Поворот відносно: + Hue Jitter: Розкид відтінку: Brush Scale Options Параметри масштабування пензля Scale Proportionately Масштабувати пропорційно Stretch to Fit Stroke Length Розтягнути за довжиною обведення @@ -2322,6 +2333,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 Натиск @@ -2761,6 +2773,10 @@ diagnostics ui інтерфейс Polar Grid Tool Інструмент «Полярна сітка» Polygon Багатокутник Polygon Properties: Властивості багатокутника: + Line Properties: Властивості лінії: + Line Length: Довжина лінії: + Line Angle: Кут лінії: + Constrain Pie Angle Зберігати кут сектора Polygon Tool Інструмент «Багатокутник» Portrait Книжкова Power Saving (integrated) Енергозбереження (вбудована) @@ -2922,6 +2938,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. Система узгоджує кольори вікна з дисплеєм. @@ -3184,6 +3203,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. «Створити мітки підрізування» малює мітки в японському стилі замість західних. @@ -3495,6 +3515,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 Нещодавні команди @@ -3575,6 +3600,7 @@ digits Malayalam Малаялам Set Slice Rectangle Вказати прямокутник фрагмента Set Tab Stops Задати табуляції Set Text Задати текст + Set the current fill or stroke to the selected color Призначити вибраний колір поточній заливці або обведенню Set the selected color to the current color Призначити поточний колір вибраному кольору Set Zoom Задати масштаб Settings… Параметри… @@ -3698,7 +3724,7 @@ digits Malayalam Малаялам Show Vivid/Muted Показати яскраві/приглушені Show Warm/Cool Показати теплі/холодні Show {kind} Brushes Показати пензлі {kind} - Show/hide plate (Alt-click: only this plate) Показати/приховати пластину (Alt+клацання: тільки цю пластину) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Показати/приховати пластину (Alt+клацання: тільки цю пластину; повторне Alt+клацання: усі пластини) Show: Показати: Shown with the optimised preview. Показано оптимізованим переглядом. Side 1: Сторона 1: @@ -4307,6 +4333,8 @@ effect Points Точки V Spacing: Інтервал по вертикалі: V: В: Variable Width Profile Профіль змінної ширини + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Пензель обведення зберігає власний розмір, тому профіль ширини його не змінює. Щоб використати профіль, заберіть пензель. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Пензель обведення зберігає власний розмір, тому профіль ширини його не змінює. Щоб використати профіль, заберіть пензель. Variables Змінні New Variable Нова змінна Delete Variable Видалити змінну @@ -4586,6 +4614,7 @@ imageTrace Outline Контур Bevel Скіс Offset Зміщення Axis Вісь + Axis Angle Кут осі axis Horizontal Горизонтальна axis Vertical Вертикальна axis Both Обидві @@ -5141,9 +5170,15 @@ 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 three [x, y] pairs of numbers `points` має містити три пари чисел [x, y] -@msg direct-select three anchor points, or give `points` виділіть три опорні точки прямим виділенням або задайте `points` +@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` @msg no circle passes through these points: two are the same or all three lie on one line через ці точки не проходить жодне коло: дві точки збігаються або всі три лежать на одній прямій @msg no app to open files here тут немає програми для відкриття файлів @msg no artboard немає монтажної області @@ -5245,6 +5280,9 @@ liquify-list-end {0}, {1} {0} і {1} @msg no such user library такої користувацької бібліотеки немає @msg no such view такого виду немає @msg no such width point такої точки ширини немає +@msg `single` must be `incoming` or `outgoing` `single` має бути `incoming` або `outgoing` +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` і `outIndex` мають бути двома половинами однієї розривної точки ширини +@msg a discontinuous width point keeps its place розривна точка ширини зберігає своє місце @msg no swatch `{name}` немає зразка `{name}` @msg no swatch library `{l}` (see swatch.library.list) немає бібліотеки зразків `{l}` (див. swatch.library.list) @msg no symbol instances selected екземпляри символів не виділені @@ -5610,6 +5648,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 @@ -5726,6 +5766,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 шлях автоматизації відхилено: шлях порожній @@ -6006,6 +6047,7 @@ lighting Light Світло Cove Викружка Depth Глибина Front Спереду + Side Збоку Isometric Bottom Ізометрія знизу Isometric Left Ізометрія ліворуч Isometric Right Ізометрія праворуч @@ -6100,7 +6142,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 and Revolve object types Графіка наноситься на об’єкти типів «Площина», «Видавлювання» та «Обертання» @@ -7347,6 +7389,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 Спільні дотичні @@ -7893,6 +7943,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] @@ -8429,6 +8487,7 @@ breakText Glyphs Гліфи @msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes складені фігури приймають контури, складені контури, групи, складені фігури, текст, переходи й оболонки @msg compound {_1} must contain exactly one open path to join складений об’єкт {_1} має містити рівно один відкритий контур для з’єднання @msg connect needs a path other than the one extended для connect потрібен контур, відмінний від того, що продовжується +@msg connect needs extend для connect потрібен extend @msg connect needs id для connect потрібен id @msg connect path has no open end контур для connect не має відкритого кінця @msg continuation must be an array of path chunks continuation має бути масивом частин контуру diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 5cedb1cc53..0244441df1 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -157,7 +157,11 @@ 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 + Single Width Only Chỉ một chiều rộng Adjust Color Balance… Điều chỉnh cân bằng màu… Adjust Colors Điều chỉnh màu sắc Adjust Options: Tùy chọn điều chỉnh: @@ -314,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 @@ -571,6 +576,8 @@ font-technology Variable Biến thiên Choose the file to relink each linked file to. Files with the size and contents saved with the link come first. Chọn tệp để liên kết lại từng tệp liên kết. Các tệp có kích thước và nội dung đã lưu cùng liên kết được hiển thị trước. Choose… Chọn… Circle Hình tròn + Circle Tool Công cụ Hình tròn + Circle too large Hình tròn quá lớn Classic Cổ điển Classic Defaults Mặc định cổ điển Clean Up… Dọn dẹp… @@ -1024,6 +1031,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 @@ -1476,6 +1484,8 @@ digits Malayalam Malayalam Files Tệp Files of a PDF standard can't be password-protected. Tệp theo tiêu chuẩn PDF không thể bảo vệ bằng mật khẩu. Files of this standard tag their colours with ICC profiles. Tệp theo tiêu chuẩn này gắn thẻ màu bằng hồ sơ ICC. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Tệp theo tiêu chuẩn này gắn thẻ màu bằng hồ sơ ICC, trừ các màu CMYK trong hồ sơ mục đích đầu ra, được ghi dưới dạng DeviceCMYK. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. Với “Không bao gồm hồ sơ” và mục đích đầu ra CMYK, mọi màu CMYK được ghi dưới dạng DeviceCMYK, trừ khi được chuyển đổi sang đích CMYK của hồ sơ khác. Fill Tô Fill & Stroke Tô & Nét Fill (X), double-click for the Color Picker Tô (X), bấm đúp để mở Bộ chọn màu @@ -1657,6 +1667,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 @@ -2396,6 +2407,7 @@ digits Hindi Hindi Load Texture… Tải kết cấu… Loaded Texture Kết cấu đã tải Local Libraries Thư viện cục bộ + Locate Layer Xác định vị trí lớp Locate Object Xác định vị trí đối tượng Locate Selected Objects Xác định vị trí đối tượng đã chọn Location Vị trí @@ -3079,6 +3091,10 @@ diagnostics ui giao diện Polar Grid Tool Công cụ Lưới cực Polygon Đa giác Polygon Properties: Thuộc tính đa giác: + 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 @@ -3246,6 +3262,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. @@ -3500,6 +3519,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ã. @@ -3632,6 +3652,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 @@ -3650,6 +3671,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 @@ -3839,6 +3861,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 @@ -3930,6 +3957,7 @@ mark-style Japanese Kiểu Nhật Set Slice Rectangle Đặt hình chữ nhật lát cắt Set Tab Stops Đặt vị trí tab Set Text Đặt văn bản + Set the current fill or stroke to the selected color Đặt tô hoặc nét hiện tại thành màu đã chọn Set the selected color to the current color Đặt màu đã chọn thành màu hiện tại Set Zoom Đặt thu phóng Settings Cài đặt @@ -4065,7 +4093,7 @@ mark-style Japanese Kiểu Nhật Show Vivid/Muted Hiện màu sống động/tối Show Warm/Cool Hiện màu nóng/lạnh Show {kind} Brushes Hiện cọ {kind} - Show/hide plate (Alt-click: only this plate) Hiện/ẩn bản in (Alt-bấm: chỉ bản in này) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Hiện/ẩn bản in (Alt-bấm: chỉ bản in này; Alt-bấm lần nữa: tất cả bản in) Show: Hiện: Shown with the optimised preview. Hiển thị với bản xem trước được tối ưu hóa. Side 1: Mặt 1: @@ -4720,6 +4748,8 @@ mark-style Japanese Kiểu Nhật Variable Options Tùy chọn biến Variable Options… Tùy chọn biến số… Variable Width Profile Hồ sơ chiều rộng biến đổi + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Cọ của nét giữ kích thước riêng, nên hồ sơ chiều rộng không thay đổi nét. Gỡ cọ để dùng hồ sơ. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Cọ của nét giữ kích thước riêng, nên hồ sơ chiều rộng không thay đổi nét. Gỡ cọ để dùng hồ sơ. Variables Biến số Variation: Biến thể: Vector Effects Hiệu ứng vector @@ -5040,6 +5070,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} @@ -5284,6 +5315,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} @@ -5478,9 +5517,15 @@ 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 three [x, y] pairs of numbers `points` phải là ba cặp số [x, y] -@msg direct-select three anchor points, or give `points` hãy chọn trực tiếp ba điểm neo hoặc cung cấp `points` +@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` @msg no circle passes through these points: two are the same or all three lie on one line không có đường tròn nào đi qua các điểm này: hai điểm trùng nhau hoặc cả ba điểm thẳng hàng @msg no app to open files here không có ứng dụng để mở tệp ở đây @msg no artboard không có bảng vẽ @@ -5594,6 +5639,9 @@ liquify-list-end {0}, {1} {0} và {1} @msg no such user library không có thư viện người dùng như vậy @msg no such view không có chế độ xem như vậy @msg no such width point không có điểm chiều rộng như vậy +@msg `single` must be `incoming` or `outgoing` `single` phải là `incoming` hoặc `outgoing` +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` và `outIndex` phải là hai nửa của cùng một điểm chiều rộng gián đoạn +@msg a discontinuous width point keeps its place điểm chiều rộng gián đoạn giữ nguyên vị trí @msg no swatch `{name}` không có mẫu màu `{name}` @msg no swatch library `{l}` (see swatch.library.list) không có thư viện mẫu màu `{l}` (xem swatch.library.list) @msg no symbol instances selected chưa chọn đối tượng ký hiệu @@ -5907,7 +5955,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 and Revolve object types Đồ họa được đặt lên các loại đối tượng Mặt phẳng, Kéo dài và Xoay tròn @@ -6179,6 +6227,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 @@ -7383,6 +7433,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 221a3838b6..d56912e957 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -90,8 +90,12 @@ Add to Swatches 添加到色板 Add Used Colors 添加已用颜色 Additional Plug-ins Folder 附加增效工具文件夹 + Plug-in Instruction Budget 增效工具指令预算 Additional Fonts Folder 附加字体文件夹 Adjust Adjoining Width Points 调整相邻宽度点 + Incoming 入侧 + Outgoing 出侧 + Single Width Only 仅保留一个宽度 Adjust Color Balance… 调整色彩平衡… Adjust Colors 调整颜色 Adjust Options: 调整选项: @@ -442,6 +446,8 @@ antiAlias Sharp 锐利 Choose a folder 选择文件夹 Choose… 选择… Circle 圆形 + Circle Tool 圆形工具 + Circle too large 圆形过大 Classic Defaults 经典默认 Clean Up… 清理… Clear 清除 @@ -825,6 +831,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 丢弃空文字 @@ -1223,6 +1230,8 @@ antiAlias Sharp 锐利 Files 文件 Files of a PDF standard can't be password-protected. PDF 标准的文件无法设置密码保护。 Files of this standard tag their colours with ICC profiles. 此标准的文件会以 ICC 配置文件标记颜色。 + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. 此标准的文件会以 ICC 配置文件标记颜色,但输出意图配置文件中的 CMYK 颜色会写为 DeviceCMYK。 + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. 选择“不包含配置文件”且输出意图为 CMYK 时,除非转换为其他配置文件的 CMYK 目标,否则每种 CMYK 颜色都会写为 DeviceCMYK。 Fill 填色 Fill & Stroke 填色和描边 Fill (X), double-click for the Color Picker 填色 (X),双击打开拾色器 @@ -1969,6 +1978,7 @@ file-filter Templates 模板 Load SVG into Clipboard 将 SVG 载入剪贴板 Load Text into Clipboard 将文本载入剪贴板 Local Libraries 本地库 + Locate Layer 查找图层 Locate Object 查找对象 Locate Selected Objects 查找所选对象 Location 位置 @@ -2159,6 +2169,7 @@ file-filter Templates 模板 Scatter: 散布: Rotation: 旋转: Rotation relative to: 旋转相对于: + Hue Jitter: 色相抖动: Brush Scale Options 画笔缩放选项 Scale Proportionately 等比缩放 Stretch to Fit Stroke Length 伸展以适合描边长度 @@ -2185,6 +2196,7 @@ file-filter Templates 模板 Approximate path 近似路径 Colorization 着色 Key Color: 主色: + Roundness 圆度 Roundness: 圆度: Fixed 固定 Pressure 压力 @@ -2620,6 +2632,10 @@ diagnostics ui 界面 Polar Grid Tool 极坐标网格工具 Polygon 多边形 Polygon Properties: 多边形属性: + Line Properties: 直线属性: + Line Length: 直线长度: + Line Angle: 直线角度: + Constrain Pie Angle 约束扇形角度 Polygon Tool 多边形工具 Portrait 纵向 Portuguese 葡萄牙语 @@ -2782,6 +2798,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. 系统会使窗口匹配显示器的颜色。 @@ -3041,6 +3060,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. 创建裁切标记绘制日式标记,而不是西式标记。 @@ -3320,6 +3340,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 最近使用的命令 @@ -3397,6 +3420,7 @@ digits Malayalam 马拉雅拉姆数字 Set Slice Rectangle 设置切片矩形 Set Tab Stops 设置制表位 Set Text 设置文本 + Set the current fill or stroke to the selected color 将当前填色或描边设为选择的颜色 Set the selected color to the current color 将选择的颜色设为当前颜色 Set Zoom 设置缩放 Settings… 设置… @@ -3518,7 +3542,7 @@ digits Malayalam 马拉雅拉姆数字 Show Vivid/Muted 显示鲜艳/柔和 Show Warm/Cool 显示暖色/冷色 Show {kind} Brushes 显示{kind}画笔 - Show/hide plate (Alt-click: only this plate) 显示/隐藏色版 (Alt-单击:仅此色版) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) 显示/隐藏色版 (Alt-单击:仅此色版;再次 Alt-单击:所有色版) Show: 显示: Shown with the optimised preview. 与优化预览一起显示。 Side 1: 侧边 1: @@ -4134,6 +4158,8 @@ digits Malayalam 马拉雅拉姆数字 V Spacing: 垂直间距: V: V: Variable Width Profile 变量宽度配置文件 + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. 描边的画笔保持其自身大小,因此宽度配置文件不会改变它。移除画笔即可使用配置文件。 +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. 描边的画笔保持其自身大小,因此宽度配置文件不会改变它。移除画笔即可使用配置文件。 Variables 变量 New Variable 新建变量 Delete Variable 删除变量 @@ -4623,8 +4649,8 @@ imageTrace Outline 轮廓 @msg image would be too large; lower the resolution 图像将过大;请降低分辨率 @msg clipboard is empty 剪贴板为空 @msg no anchor points selected 未选择锚点 -@msg `points` must be three [x, y] pairs of numbers `points` 必须是三对数字 [x, y] -@msg direct-select three anchor points, or give `points` 请直接选择三个锚点,或提供 `points` +@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` @msg no circle passes through these points: two are the same or all three lie on one line 没有圆经过这些点:有两点相同,或三点共线 @msg select at least two objects 请至少选择两个对象 @msg exit isolation mode first 请先退出隔离模式 @@ -4981,6 +5007,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} @@ -5031,6 +5063,9 @@ imageTrace Outline 轮廓 @msg `{color}` is not a colour (#rrggbb or a preset name) `{color}` 不是颜色 (#rrggbb 或预设名称) @msg give the path `id` and the width point `index` 请给出路径的 `id` 和宽度点的 `index` @msg no such width point 没有此宽度点 +@msg `single` must be `incoming` or `outgoing` `single` 必须是 `incoming` 或 `outgoing` +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` 和 `outIndex` 必须是同一个不连续宽度点的两半 +@msg a discontinuous width point keeps its place 不连续宽度点保持原位 @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 只能给出一个 @@ -5407,6 +5442,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}` 是内置工作区;请选择其他名称 @@ -5456,6 +5493,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 已拒绝自动化路径:路径为空 @@ -5965,6 +6003,7 @@ font-technology Variable 可变 Bevel 斜角 Offset 偏移 Axis 轴 + Axis Angle 轴角度 axis Horizontal 水平 axis Vertical 垂直 axis Both 两者 @@ -6278,6 +6317,7 @@ lighting Light 光源 Cove 凹圆 Depth 深度 Front 正面 + Side 侧面 Isometric Bottom 等角底部 Isometric Left 等角左侧 Isometric Right 等角右侧 @@ -6372,7 +6412,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 and Revolve object types 图形映射到平面、突出和回转对象类型上 @@ -7577,6 +7617,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 公切线 @@ -7949,6 +7997,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] @@ -8784,6 +8840,7 @@ breakText Glyphs 字形 @msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes 复合形状接受路径、复合路径、编组、复合形状、文字、混合和封套 @msg compound {_1} must contain exactly one open path to join 复合对象 {_1} 必须恰好包含一条要连接的开放路径 @msg connect needs a path other than the one extended connect 需要一条不同于被延伸路径的路径 +@msg connect needs extend connect 需要 extend @msg connect needs id connect 需要 id @msg connect path has no open end connect 的路径没有开放的端点 @msg copy needs path: the file to copy into the document's folder copy 需要 path:即要复制到文档所在文件夹的文件 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 94f30010dd..7f7dcfe5e2 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -99,8 +99,12 @@ Add to Swatches 新增至色票 Add Used Colors 新增使用中的顏色 Additional Plug-ins Folder 額外的增效模組資料夾 + Plug-in Instruction Budget 增效模組指令預算 Additional Fonts Folder 額外的字體資料夾 Adjust Adjoining Width Points 調整相鄰寬度點 + Incoming 入側 + Outgoing 出側 + Single Width Only 僅保留一個寬度 Adjust Color Balance… 調整色彩平衡… Adjust Colors 調整顏色 Adjust Options: 調整選項: @@ -457,6 +461,8 @@ font-technology Variable 可變 Choose a folder 選擇資料夾 Choose… 選擇… Circle 圓形 + Circle Tool 圓形工具 + Circle too large 圓形過大 Classic Defaults 經典預設值 Clean Up… 清除… Clear 清除 @@ -846,6 +852,7 @@ font-technology Variable 可變 Direct Selection Tool 直接選取工具 Direction Handles 控制把手 Disable Auto Add/Delete 停用自動增加/刪除 + Interpolate Control Points When Moving Anchors 移動錨點時內插控制把手 Disable Opacity Mask 停用不透明度遮色片 Discard 捨棄 Preserve 保留 @@ -1257,6 +1264,8 @@ font-technology Variable 可變 Files 檔案 Files of a PDF standard can't be password-protected. PDF 標準的檔案無法設定密碼保護。 Files of this standard tag their colours with ICC profiles. 此標準的檔案會以 ICC 描述檔標記顏色。 + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. 此標準的檔案會以 ICC 描述檔標記顏色,但輸出目的描述檔中的 CMYK 顏色會寫為 DeviceCMYK。 + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. 選擇「不包含描述檔」且輸出目的為 CMYK 時,除非轉換為其他描述檔的 CMYK 目的地,否則每種 CMYK 顏色都會寫為 DeviceCMYK。 Fill 填色 Fill & Stroke 填色與筆畫 Fill (X), double-click for the Color Picker 填色 (X),按兩下開啟檢色器 @@ -2106,8 +2115,8 @@ file-filter Templates 範本 @msg image would be too large; lower the resolution 影像會過大;請降低解析度 @msg clipboard is empty 剪貼簿是空的 @msg no anchor points selected 未選取錨點 -@msg `points` must be three [x, y] pairs of numbers `points` 必須是三組數字 [x, y] -@msg direct-select three anchor points, or give `points` 請以直接選取方式選取三個錨點,或提供 `points` +@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` @msg no circle passes through these points: two are the same or all three lie on one line 沒有圓通過這些點:有兩點相同,或三點共線 @msg select at least two objects 請選取至少兩個物件 @msg exit isolation mode first 請先結束隔離模式 @@ -2467,6 +2476,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} @@ -2517,6 +2532,9 @@ file-filter Templates 範本 @msg `{color}` is not a colour (#rrggbb or a preset name) `{color}` 不是顏色 (#rrggbb 或預設集名稱) @msg give the path `id` and the width point `index` 請提供路徑的 `id` 和寬度點的 `index` @msg no such width point 沒有這個寬度點 +@msg `single` must be `incoming` or `outgoing` `single` 必須是 `incoming` 或 `outgoing` +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` 和 `outIndex` 必須是同一個不連續寬度點的兩半 +@msg a discontinuous width point keeps its place 不連續寬度點保持原位 @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 只能提供其中一個 @@ -2778,6 +2796,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} @@ -2894,6 +2920,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}` 是內建工作區;請選擇其他名稱 @@ -2935,6 +2963,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 已拒絕自動化路徑:路徑是空的 @@ -3257,6 +3286,7 @@ liquify-list-end {0}, {1} {0}和{1} Load SVG into Clipboard 將 SVG 載入剪貼簿 Load Text into Clipboard 將文字載入剪貼簿 Local Libraries 本機資料庫 + Locate Layer 尋找圖層 Locate Object 尋找物件 Locate Selected Objects 尋找選取的物件 Location 位置 @@ -3467,6 +3497,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 延伸以符合筆畫長度 @@ -3503,6 +3534,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 壓力 @@ -3944,6 +3976,10 @@ diagnostics ui 介面 Polar Grid Tool 極座標格點工具 Polygon 多邊形 Polygon Properties: 多邊形內容: + Line Properties: 直線內容: + Line Length: 直線長度: + Line Angle: 直線角度: + Constrain Pie Angle 強制扇形角度 Polygon Tool 多邊形工具 Portrait 直向 Power Saving (integrated) 節能 (內建顯示晶片) @@ -4108,6 +4144,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. 系統會讓視窗符合顯示器的色彩。 @@ -4370,6 +4409,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. 建立剪裁標記繪製日式標記,而不是西式標記。 @@ -4679,6 +4719,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 最近使用的指令 @@ -4759,6 +4804,7 @@ digits Malayalam 馬來亞拉姆數字 Set Slice Rectangle 設定切片矩形 Set Tab Stops 設定定位點 Set Text 設定文字 + Set the current fill or stroke to the selected color 將目前填色或筆畫設為選取的顏色 Set the selected color to the current color 將選取的顏色設為目前顏色 Set Zoom 設定縮放 Settings… 設定… @@ -4882,7 +4928,7 @@ digits Malayalam 馬來亞拉姆數字 Show Vivid/Muted 顯示鮮豔/柔和 Show Warm/Cool 顯示暖色/冷色 Show {kind} Brushes 顯示{kind}筆刷 - Show/hide plate (Alt-click: only this plate) 顯示/隱藏色版 (Alt-按一下:僅此色版) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) 顯示/隱藏色版 (Alt-按一下:僅此色版;再次 Alt-按一下:所有色版) Show: 顯示: Shown with the optimised preview. 於最佳化預覽時顯示。 Side 1: 側面 1: @@ -5503,6 +5549,8 @@ digits Malayalam 馬來亞拉姆數字 V Spacing: 垂直間距: V: V: Variable Width Profile 可變寬度描述檔 + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. 筆畫的筆刷會保持自身大小,因此寬度描述檔不會改變它。移除筆刷即可使用描述檔。 +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. 筆畫的筆刷會保持自身大小,因此寬度描述檔不會改變它。移除筆刷即可使用描述檔。 Variables 變數 New Variable 新增變數 Delete Variable 刪除變數 @@ -5795,6 +5843,7 @@ imageTrace Outline 輪廓 Bevel 斜角 Offset 位移 Axis 軸 + Axis Angle 軸角度 axis Horizontal 水平 axis Vertical 垂直 axis Both 兩者 @@ -6116,6 +6165,7 @@ lighting Light 光源 Cove 凹圓 Depth 深度 Front 正面 + Side 側面 Isometric Bottom 等角底部 Isometric Left 等角左側 Isometric Right 等角右側 @@ -6210,7 +6260,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 and Revolve object types 圖形會對應到「平面」、「突出」與「迴轉」物件類型 @@ -7388,6 +7438,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 公切線 @@ -8715,6 +8773,7 @@ breakText Glyphs 字符 @msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes 複合形狀接受路徑、複合路徑、群組、複合形狀、文字、漸變物件和封套 @msg compound {_1} must contain exactly one open path to join 複合路徑 {_1} 必須剛好包含一條可連接的開放路徑 @msg connect needs a path other than the one extended connect 需要延伸路徑以外的另一條路徑 +@msg connect needs extend connect 需要 extend @msg connect needs id connect 需要 id @msg connect path has no open end connect 的路徑沒有開放的端點 @msg copy needs path: the file to copy into the document's folder copy 需要 path:要複製到文件資料夾的檔案 diff --git a/crates/ui-egui/src/icon_data.rs b/crates/ui-egui/src/icon_data.rs index f521e45c22..bc0cfe3510 100644 --- a/crates/ui-egui/src/icon_data.rs +++ b/crates/ui-egui/src/icon_data.rs @@ -58,6 +58,7 @@ pub static ICONS: &[(&str, &[u8])] = &[ ("dc-cap-square", include_bytes!("../../../assets/icons/dc-cap-square.svg")), ("dc-center-hide", include_bytes!("../../../assets/icons/dc-center-hide.svg")), ("dc-center-show", include_bytes!("../../../assets/icons/dc-center-show.svg")), + ("dc-circle-points", include_bytes!("../../../assets/icons/dc-circle-points.svg")), ("dc-clear", include_bytes!("../../../assets/icons/dc-clear.svg")), ("dc-color-guide", include_bytes!("../../../assets/icons/dc-color-guide.svg")), ("dc-contour", include_bytes!("../../../assets/icons/dc-contour.svg")), diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs index e352653279..c4a67fdef6 100644 --- a/crates/ui-egui/src/icons.rs +++ b/crates/ui-egui/src/icons.rs @@ -44,6 +44,7 @@ pub fn tool_icon(name: &str) -> &'static str { "tool-rect" => "square", "tool-rounded-rect" => "dc-rounded-rect", "tool-ellipse" => "dc-ellipse", + "tool-circle" => "dc-circle-points", "tool-polygon" => "dc-polygon", "tool-star" => "star", "tool-flare" => "dc-flare", 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 cb9917ba39..87091ef8a9 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -144,7 +144,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} opens SVG Options; with params = document.export {path?, svg?: {…SVG options}, range?…} (a .svgz path writes it gzipped)", ), - ("file.export.png", "Export As PNG…", "", "{path?, …document.export options}; no path: pick the file, then PNG Options"), + ( + "file.export.png", + "Export As PNG…", + "", + "{path?, …document.export options}; no path: pick the file, then PNG Options with supplied options retained and defaults for omitted options", + ), ( "file.exportForScreens", "Export for Screens…", @@ -162,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", @@ -847,7 +858,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "tool.setOption", "Tool Option", "", - "{key, value} | {values: {key: value…}}, tool?: id (default: the active tool) → the tool's options (`{}` reads them). The options a tool keeps (Liquify brush and tool options, Mirror & Cut, Puppet Warp, drawing tools…) last across tool switches and are saved with the preferences; another tool's are stored for when it is chosen", + "{key, value} | {values: {key: value…}}, tool?: id (default: the active tool) → the tool's options (`{}` or no params reads them; params that are not an object are an error). The options a tool keeps (Liquify brush and tool options, Mirror & Cut, Puppet Warp, drawing tools…) last across tool switches and are saved with the preferences; another tool's are stored for when it is chosen. Every option is checked before any is set: an option the tool doesn't have, a value of the wrong type, a number out of the tool's range or an unknown choice is an error naming the tool and the option, and nothing changes. The Live Paint tools' width and the Shape Builder's gapLength are set to the nearest end of their range instead", ), ( crate::touch::TOGGLE_MODE, @@ -890,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…", @@ -943,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", @@ -997,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 224d7d975a..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; @@ -564,8 +709,9 @@ pub(crate) fn recent_list_open(ctx: &egui::Context) -> bool { pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { // The widget that had the keyboard focus when the palette opened takes it back when the palette - // closes, unless a pick opened a dialog, which focuses its own first field, or the press that - // closed it focused another widget, such as a field in a window above the backdrop. + // closes, unless a modal window is up (a pick opened a dialog, which focuses its own first + // field, or a window that opened closed the palette), or the press that closed it focused + // another widget, such as a field in a window above the backdrop. let focus_id = egui::Id::unique("palette-focus-before"); let field_id = egui::Id::unique("palette-field"); if !app.ui.palette_open { @@ -576,7 +722,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { }); let now = ctx.memory(|m| m.focused()); if let Some(Some(before)) = ctx.data_mut(|d| d.remove_temp::>(focus_id)) - && app.ui.dialog.is_none() + && !crate::panel_docking::modal_window_up(app, ctx) && (now.is_none() || now == field) { ctx.memory_mut(|m| m.request_focus(before)); @@ -739,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 { @@ -764,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()); @@ -1933,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); @@ -2041,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(); @@ -2117,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 @@ -2210,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())); } @@ -2232,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] @@ -2282,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(); @@ -2294,15 +2660,47 @@ 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)); } + /// When a modal window that is not a dialog, such as the About window, closes the palette, the + /// widget under the window's backdrop does not get the keyboard focus back. + #[test] + fn a_modal_window_that_closes_the_palette_keeps_the_focus_from_the_widget_under_it() { + let ctx = egui::Context::default(); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + let mut text = String::new(); + let field = egui::Id::unique("other field"); + let mut frame = |app: &mut VectorcraftApp, focus: bool| { + ctx.run_ui(egui::RawInput::default(), |ui| { + let r = ui.add(egui::TextEdit::singleline(&mut text).id(field)); + if focus { + r.request_focus(); + } + show(app, ui.ctx()); + }) + .textures_delta + .clear(); + }; + frame(&mut app, true); + frame(&mut app, false); + app.ui.palette_open = true; + frame(&mut app, false); + frame(&mut app, false); + // As `panel_docking::close_overlays_for_modal` does when the About window opens. + app.ui.about = true; + app.ui.palette_open = false; + frame(&mut app, false); + frame(&mut app, false); + assert_ne!(ctx.memory(|m| m.focused()), Some(field), "the field under the About window does not take the focus"); + } + /// The widget that had the keyboard focus when the palette opened has it again once the /// palette closes. #[test] @@ -2398,6 +2796,9 @@ mod tests { /// app, as a progress window is drawn, and count its clicks. above: Option, above_clicks: usize, + /// Draw a modal window over the backdrop before the app's windows, as a progress window + /// of a plug-in, trace or open run is drawn. + progress: bool, } impl Window { @@ -2409,7 +2810,7 @@ mod tests { assert!(!app.session.doc().unwrap().selection.is_empty()); let ctx = egui::Context::default(); ctx.enable_accesskit(); - let mut window = Window { app, ctx, time: 0.0, above: None, above_clicks: 0 }; + let mut window = Window { app, ctx, time: 0.0, above: None, above_clicks: 0, progress: false }; window.frame(vec![]); window.frame(vec![]); window @@ -2421,9 +2822,13 @@ mod tests { let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, WINDOW); let input = egui::RawInput { time: Some(self.time), screen_rect: Some(screen), events, ..Default::default() }; let app = &mut self.app; - let (above, clicks) = (self.above, &mut self.above_clicks); + let (above, clicks, progress) = (self.above, &mut self.above_clicks, self.progress); let mut out = self.ctx.run_ui(input, |ui| { app.logic(ui.ctx()); + if progress { + let id = egui::Id::unique("test-progress"); + crate::dialogs::modal::show_at(ui.ctx(), "Progress", id, egui::Vec2::ZERO, 12, |ui| ui.label("Working")); + } app.ui(ui); if let Some(at) = above { let area = egui::Area::new(egui::Id::unique("test-above")).order(egui::Order::Foreground).fixed_pos(at); @@ -2495,6 +2900,150 @@ mod tests { assert_eq!(window.selection(), before, "the click does not reach the canvas"); } + /// #7906: a pick in the macOS menu bar that opens a dialog closes the palette, and the search + /// field does not keep the keyboard from the dialog. + #[test] + fn a_dialog_opened_from_the_system_menu_closes_the_palette() { + let mut window = Window::new(); + window.app.ui.palette_open = true; + window.frame(vec![]); + window.frame(vec![]); + let field = window.ctx.data(|d| d.get_temp::(egui::Id::unique("palette-field"))).expect("the search field is drawn"); + assert_eq!(window.ctx.memory(|m| m.focused()), Some(field), "the search field has the keyboard"); + menus::invoke_from_system_menu(&mut window.app, &window.ctx, "object.move", json!({})); + assert!(window.app.ui.dialog.is_some(), "Move… opens its dialog: {}", window.app.ui.status); + window.frame(vec![]); + assert!(!window.app.ui.palette_open, "the dialog closes the palette"); + window.frame(vec![]); + assert!(window.app.ui.dialog.is_some(), "the dialog stays open"); + assert_ne!(window.ctx.memory(|m| m.focused()), Some(field), "the search field does not keep the keyboard"); + } + + /// #7906: with the palette open, the About window that opens without a press closes the palette. + #[test] + fn the_about_window_closes_the_palette() { + let mut window = Window::new(); + window.app.ui.palette_open = true; + window.frame(vec![]); + menus::invoke_from_system_menu(&mut window.app, &window.ctx, "help.about", json!({})); + assert!(window.app.ui.about, "About opens"); + window.frame(vec![]); + assert!(!window.app.ui.palette_open, "the About window closes the palette"); + } + + /// #7906: a window drawn over the modal backdrop, as a plug-in, trace or open run's progress + /// window is, closes the palette in the pass it first draws. + #[test] + fn a_progress_window_closes_the_palette() { + let mut window = Window::new(); + window.app.ui.palette_open = true; + window.frame(vec![]); + assert!(window.app.ui.palette_open, "the palette is open"); + window.progress = true; + window.frame(vec![]); + assert!(!window.app.ui.palette_open, "the progress window closes the palette"); + } + + /// #7906: the palette opened from the macOS menu bar while a dialog is open closes again, and its + /// search field does not take the keyboard from the dialog. + #[test] + fn the_palette_opened_over_a_dialog_closes() { + let mut window = Window::new(); + menus::invoke(&mut window.app, "object.move", json!({})); + assert!(window.app.ui.dialog.is_some(), "Move… opens its dialog: {}", window.app.ui.status); + window.frame(vec![]); + window.frame(vec![]); + let before = window.ctx.memory(|m| m.focused()); + menus::invoke_from_system_menu(&mut window.app, &window.ctx, "help.commandPalette", json!({})); + assert!(window.app.ui.palette_open, "the command opens the palette"); + window.frame(vec![]); + window.frame(vec![]); + assert!(!window.app.ui.palette_open, "the dialog keeps the palette closed"); + assert!(window.app.ui.dialog.is_some(), "the dialog stays open"); + let field = window.ctx.data(|d| d.get_temp::(egui::Id::unique("palette-field"))); + let now = window.ctx.memory(|m| m.focused()); + assert!(field.is_none() || now != field, "the search field does not take the keyboard"); + assert_eq!(now, before, "the dialog keeps its focus"); + } + + /// #7906 as reported: with the palette open, a click on the Effect menu in the window's menu bar + /// closes the palette, and a dialog opened afterwards is not under it. + #[test] + fn a_click_on_the_menu_bar_closes_the_palette_before_a_dialog_opens() { + let mut window = Window::new(); + window.app.ui.palette_open = true; + let nodes = window.frame(vec![]); + window.click(button_at(&nodes, "Effect")); + assert!(!window.app.ui.palette_open, "the click on the menu bar closes the palette"); + menus::invoke(&mut window.app, "object.move", json!({})); + assert!(window.app.ui.dialog.is_some(), "Move… opens its dialog: {}", window.app.ui.status); + window.frame(vec![]); + window.frame(vec![]); + assert!(!window.app.ui.palette_open, "the palette stays closed over the dialog"); + } + + /// Opens `overlay` ("flyout", "drawer" or "menu") in a new window, then opens Move… without a + /// press, as the macOS menu bar or an automation command does: whether the overlay is still open. + fn overlay_open_after_a_dialog_opens(overlay: &str) -> bool { + let mut window = Window::new(); + match overlay { + "flyout" => { + window.app.ui.flyout = Some(0); + let tools = vec!["rectangle".to_string(), "ellipse".to_string()]; + window.ctx.data_mut(|d| d.insert_temp(egui::Id::unique("flyout-tools"), tools)); + } + "drawer" => window.app.ui.tools_drawer = true, + _ => { + let nodes = window.frame(vec![]); + window.click(button_at(&nodes, "Object")); + } + } + window.frame(vec![]); + let open = |w: &Window| w.app.ui.flyout.is_some() || w.app.ui.tools_drawer || egui::Popup::is_any_open(&w.ctx); + assert!(open(&window), "the {overlay} is open"); + menus::invoke(&mut window.app, "object.move", json!({})); + assert!(window.app.ui.dialog.is_some(), "Move… opens its dialog: {}", window.app.ui.status); + window.frame(vec![]); + open(&window) + } + + /// #7906: a dialog that opens without a press closes a tool group's flyout. + #[test] + fn a_dialog_opened_without_a_press_closes_a_flyout() { + assert!(!overlay_open_after_a_dialog_opens("flyout"), "the dialog closes the flyout"); + } + + /// #7906: a dialog that opens without a press closes the All Tools drawer. + #[test] + fn a_dialog_opened_without_a_press_closes_the_tools_drawer() { + assert!(!overlay_open_after_a_dialog_opens("drawer"), "the dialog closes the drawer"); + } + + /// #7906: a dialog that opens without a press closes an open menu. + #[test] + fn a_dialog_opened_without_a_press_closes_a_menu() { + assert!(!overlay_open_after_a_dialog_opens("menu"), "the dialog closes the menu"); + } + + /// The palette opened in the pass after a dialog closes stays open, and the next dialog to open, + /// one pass later, closes it. + #[test] + fn the_palette_opened_as_a_dialog_closes_stays_open_until_the_next_dialog() { + let mut window = Window::new(); + menus::invoke(&mut window.app, "object.move", json!({})); + assert!(window.app.ui.dialog.is_some(), "Move… opens its dialog: {}", window.app.ui.status); + window.frame(vec![]); + window.frame(vec![]); + crate::dialogs::cancel(&mut window.app); + window.app.ui.palette_open = true; + window.frame(vec![]); + assert!(window.app.ui.palette_open, "the palette stays open"); + menus::invoke(&mut window.app, "object.move", json!({})); + assert!(window.app.ui.dialog.is_some(), "Move… opens its dialog again: {}", window.app.ui.status); + window.frame(vec![]); + assert!(!window.app.ui.palette_open, "the next dialog closes the palette"); + } + /// A click on another control outside the popup closes the popup and does not press the /// control. #[test] @@ -2596,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)); @@ -2684,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/panel_docking.rs b/crates/ui-egui/src/panel_docking.rs index bfc6c5ecf0..02c448755a 100644 --- a/crates/ui-egui/src/panel_docking.rs +++ b/crates/ui-egui/src/panel_docking.rs @@ -1306,6 +1306,40 @@ pub(crate) fn modal_open(app: &VectorcraftApp, ctx: &egui::Context) -> bool { || ctx.memory(|m| m.areas().is_visible(&crate::dialogs::modal::backdrop())) } +/// Is a modal window open in this pass: a dialog, the About window, a file dialog, the update +/// prompt, or a window such as a progress window drawn over the modal backdrop in this pass? +pub(crate) fn modal_window_up(app: &VectorcraftApp, ctx: &egui::Context) -> bool { + app.ui.dialog.is_some() + || app.ui.about + || app.file_dialog_open() + || crate::updates_ui::blocks_input(app) + || crate::dialogs::modal::drawn_this_pass(ctx) +} + +/// The key of whether a modal window was up in the last pass ([`close_overlays_for_modal`]). +fn modal_window_up_id() -> egui::Id { + egui::Id::unique("modal-window-up") +} + +/// While a modal window is up ([`modal_window_up`]), keeps the command palette closed, so a palette +/// opened over it from the macOS menu bar or by an automation command does not take the keyboard +/// from the window. In the pass the window opens, also closes a tool group's flyout, the All Tools +/// drawer and any open popup, whatever opened the window: a press in the window, a pick in the +/// macOS menu bar, an automation command or a run that ends in a dialog. Popups the window itself +/// opens later stay open. Called after every window of the pass has drawn. +pub(crate) fn close_overlays_for_modal(app: &mut VectorcraftApp, ctx: &egui::Context) { + let up = modal_window_up(app, ctx); + let was = ctx.data_mut(|d| std::mem::replace(d.get_temp_mut_or_default::(modal_window_up_id()), up)); + if up { + app.ui.palette_open = false; + } + if up && !was { + app.ui.flyout = None; + app.ui.tools_drawer = false; + egui::Popup::close_all(ctx); + } +} + /// Keys, text and clipboard events that a floating panel's own OS window left over run the main /// window's shortcuts, tool keys and clipboard on its next frame ([`VectorcraftApp::raw_input_hook`]). /// craft-ui forwards nothing while a field in that window has the keyboard. A field of the main 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/artboards.rs b/crates/ui-egui/src/panels/artboards.rs index b7f9e25df5..94560b9f76 100644 --- a/crates/ui-egui/src/panels/artboards.rs +++ b/crates/ui-egui/src/panels/artboards.rs @@ -149,11 +149,14 @@ pub(crate) fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui, options: bool, // The W/H link sits between W and H, but is made after H so Tab goes from W straight to H and // finds the link after it, as in the object Control bar. let mut link_room = None; + let mut labels = Vec::with_capacity(4); for (k, lbl, v) in [("x", "X:", rp.x - origin.x), ("y", "Y:", rp.y - origin.y), ("width", "W:", r.width()), ("height", "H:", r.height())] { if k == "height" { link_room = Some(super::transform::constrain_link_room(ui)); } - widgets::field_label(ui, egui::RichText::new(tl!(lbl)).size(12.0).color(t.text_dim)); + // A click on the label opens the Transform panel, as the Transform link does; a drag scrubs. + let text = egui::RichText::new(tl!(lbl)).size(12.0).color(t.text).underline(); + labels.push(widgets::field_panel_label(ui, text).on_hover_text(tl!("Transform options"))); let set = if matches!(k, "width" | "height") { widgets::size_field(ui, ("cb-ab", k), Some(v), units, 80.0) } else { @@ -173,6 +176,10 @@ pub(crate) fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui, options: bool, let id = ui.scope_id().with("cb-ab-constrain-link"); super::transform::constrain_link_at(app, ui, ui.interact(room, id, egui::Sense::click())); } + // After the fields, which each take the label before them as their own. + for label in &labels { + super::transform::popover(app, label); + } true } diff --git a/crates/ui-egui/src/panels/artboards/tests.rs b/crates/ui-egui/src/panels/artboards/tests.rs index b53faf87c0..b52d1da682 100644 --- a/crates/ui-egui/src/panels/artboards/tests.rs +++ b/crates/ui-egui/src/panels/artboards/tests.rs @@ -957,6 +957,32 @@ fn the_control_bar_resizes_the_active_artboard_about_the_reference_point() { assert_eq!(boards(&app).0, want, "Artboard 2 widens from its left edge"); } +/// With the Artboard tool, a click on the Control bar's X:, Y:, W: or H: label opens the Transform +/// panel's artboard fields in a popover under it, as the Transform link does, and a second click +/// closes it; the artboards stay as they were and no field takes the keyboard. +#[test] +fn the_artboard_control_bars_x_y_w_and_h_labels_open_the_transform_panel() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 100, "units": "Points"})).unwrap(); + app.select_tool("artboard"); + let ctx = bar_context(); + let before = boards(&app); + // The bar draws one W:, and the popover's artboard fields another. + let ws = |texts: &[(String, egui::Rect)]| texts.iter().filter(|(t, _)| t == "W:").count(); + for label in ["X:", "Y:", "W:", "H:"] { + let texts = bar_texts(&mut app, &ctx); + assert_eq!(ws(&texts), 1, "{label}: the bar alone: {texts:?}"); + let at = text_rect(&texts, label).center(); + bar_click(&mut app, &ctx, at); + let texts = bar_texts(&mut app, &ctx); + assert_eq!(ws(&texts), 2, "{label}: the Transform panel opens: {texts:?}"); + assert_eq!(ctx.memory(|m| m.focused()), None, "{label}: no field took the keyboard"); + bar_click(&mut app, &ctx, at); + assert_eq!(ws(&bar_texts(&mut app, &ctx)), 1, "{label}: a second click closes it"); + } + assert_eq!(boards(&app), before, "the artboards stay"); +} + /// The Control bar's Portrait and Landscape buttons swap the active artboard's width and height, /// its top-left corner staying put, in one undo step each. #[test] 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/color.rs b/crates/ui-egui/src/panels/color.rs index 28fb618dc9..c6a96b62d1 100644 --- a/crates/ui-egui/src/panels/color.rs +++ b/crates/ui-egui/src/panels/color.rs @@ -231,19 +231,23 @@ pub(crate) const WEB_WARNING: (&str, &str) = ("dc-cube", "Out of Web Color Warni /// The out-of-gamut warning: its icon and tooltip. pub(crate) const GAMUT_WARNING: (&str, &str) = ("dc-gamut", "Out of Gamut Warning"); -/// A warning icon with the corrected colour beside it. Returns true when the colour is clicked. +/// A warning icon with the corrected colour beside it. Returns true when the icon or the colour is +/// clicked. pub(crate) fn warning_chip(ui: &mut Ui, (icon, warning): (&str, &str), fix: &Color) -> bool { let t = Tokens::get(ui.ctx()); + let tip = crate::i18n::fmt( + tl!("{warning}: click to correct to the closest color ({hex})"), + &[("warning", tl!(warning)), ("hex", &format!("#{}", hex_digits(fix).to_ascii_lowercase()))], + ); ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = 3.0; - icons::icon(ui, icon, 16.0, t.icon).on_hover_text(tl!(warning)); + let icon = icons::icon(ui, icon, 16.0, t.icon).interact(Sense::click()); + icon.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!(warning))); let (r, resp) = ui.allocate_exact_size(vec2(16.0, 16.0), Sense::click()); - widgets::swatch_tile(ui, r, &Paint::solid(*fix), false, resp.hovered()); - resp.on_hover_text(crate::i18n::fmt( - tl!("{warning}: click to correct to the closest color ({hex})"), - &[("warning", tl!(warning)), ("hex", &format!("#{}", hex_digits(fix).to_ascii_lowercase()))], - )) - .clicked() + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &tip)); + widgets::swatch_tile(ui, r, &Paint::solid(*fix), false, resp.hovered() || icon.hovered()); + let icon = icon.on_hover_text(&tip).clicked(); + resp.on_hover_text(&tip).clicked() || icon }) .inner } diff --git a/crates/ui-egui/src/panels/color_themes.rs b/crates/ui-egui/src/panels/color_themes.rs index d736fa415b..3590d70812 100644 --- a/crates/ui-egui/src/panels/color_themes.rs +++ b/crates/ui-egui/src/panels/color_themes.rs @@ -1,6 +1,8 @@ //! Color Themes panel (local only): the Create tab makes a five-colour theme on a harmony wheel (a //! harmony rule from the selected colour, or Custom: each colour moves on its own; with a rule the -//! colours move together), the My Themes tab lists the themes saved in the preferences. Themes are +//! colours move together; the selected color is also edited in its hex field or with CMYK, RGB, Lab +//! or HSB sliders), the My Themes tab lists the themes saved in the preferences (the panel +//! menu's Show Find Field adds a field that lists only the themes whose names hold its text). Themes are //! saved, edited, deleted and added to Swatches as colour groups through `colorTheme.*`; the theme //! being made is panel state. @@ -10,8 +12,10 @@ use vectorcraft_color::Color; use vectorcraft_color::harmony::{Harmony, THEME_SIZE, move_on_wheel}; use vectorcraft_engine::cmd::colortheme::ColorTheme; -use super::{active_paint, c32, color_json, empty_state, pstate, set_pstate}; +use super::color::{Mode, components, from_components, track_color}; +use super::{active_paint, c32, color_json, empty_state, proxy_cmd, pstate, set_pstate}; use crate::VectorcraftApp; +use crate::dialogs::recolor::slider_cell; use crate::theme::{self, Tokens}; use crate::widgets::{self, menu_item}; @@ -21,6 +25,11 @@ const DEFAULT_RULE: Harmony = Harmony::Analogous2; const DEFAULT_BASE: Color = Color::Rgb { r: 0.1, g: 0.55, b: 0.6 }; /// Diameter of the harmony wheel. const WHEEL: f32 = 150.0; +/// The color modes of the selected color's sliders, in the order the Color Mode menu lists them. +const SLIDER_MODES: [Mode; 4] = [Mode::Cmyk, Mode::Rgb, Mode::Lab, Mode::Hsb]; +/// Widths of a slider's label and of its number field (the field's width is the Recolor dialog's). +const SLIDER_LABEL_W: f32 = 12.0; +const SLIDER_FIELD_W: f32 = 48.0; /// The theme being made on the Create tab. #[derive(Clone, Debug, Default, PartialEq)] @@ -90,9 +99,35 @@ fn set_draft(ctx: &egui::Context, d: Draft) { set_pstate(ctx, "ct-draft", Some(d)); } -/// The saved theme picked on the My Themes tab. +/// The saved theme picked on the My Themes tab, while the list shows it: a theme that the find +/// field hides stays picked, but nothing acts on it until the list shows it again. fn picked(app: &VectorcraftApp, ctx: &egui::Context) -> Option { - pstate::>(ctx, "ct-picked").filter(|n| app.session.prefs.color_themes.iter().any(|t| t.name == *n)) + let q = query(ctx); + pstate::>(ctx, "ct-picked").filter(|n| app.session.prefs.color_themes.iter().any(|t| t.name == *n && matches(&t.name, &q))) +} + +/// The My Themes find field's text, kept while the panel menu hides the field. +fn find_id() -> egui::Id { + egui::Id::unique("ct-find") +} + +/// Whether the panel menu's Show Find Field shows the find field (off in a new session). +fn show_find(ctx: &egui::Context) -> bool { + pstate(ctx, "ct-show-find") +} + +/// The find field's text, trimmed and lowercased; empty while the field is hidden. +fn query(ctx: &egui::Context) -> String { + if !show_find(ctx) { + return String::new(); + } + ctx.data(|d| d.get_temp::(find_id())).unwrap_or_default().trim().to_lowercase() +} + +/// Whether the find field lists theme `name` for `query` (trimmed and lowercased): its name holds +/// the text anywhere, in any letter case. An empty query lists every theme. +fn matches(name: &str, query: &str) -> bool { + query.is_empty() || name.to_lowercase().contains(query) } /// The tab shown: 0 Create, 1 My Themes. @@ -100,6 +135,78 @@ fn tab(ctx: &egui::Context) -> usize { pstate(ctx, "ct-tab") } +/// The color mode of the sliders: the one last picked from their Color Mode menu while the app +/// runs, or else the selected color's own model (HSB for a gray). Picking a mode changes no color. +fn slider_mode(ctx: &egui::Context, c: Option<&Color>) -> Mode { + pstate::>(ctx, "ct-mode").unwrap_or_else(|| match c.map(Mode::of) { + Some(m @ (Mode::Cmyk | Mode::Rgb | Mode::Lab)) => m, + _ => Mode::Hsb, + }) +} + +/// The slider values a slider edit last set: the selected place and the color they made in +/// `mode`. While those still hold, the sliders show `v` as it was set, so an edit of one slider +/// leaves the others' numbers as they were instead of converting them back from the color. +#[derive(Clone, Debug, PartialEq)] +struct Held { + sel: usize, + color: Color, + mode: Mode, + v: Vec, +} + +/// The numbers the sliders show for the selected color of `d` in `mode`. +fn slider_values(ctx: &egui::Context, d: &Draft, mode: Mode) -> Option> { + let c = d.colors.get(d.sel)?; + let held = + pstate::>(ctx, "ct-held").filter(|h| h.sel == d.sel && h.color == *c && h.mode == mode && h.v.len() == mode.labels().len()); + Some(held.map_or_else(|| components(mode, c), |h| h.v)) +} + +/// The Color Mode menu (CMYK, RGB, Lab and HSB) and its sliders, each a rail and a number field, for +/// the selected color of `d`. An edit sets the selected color in the menu's mode (an RGB or HSB +/// edit makes it RGB, a CMYK edit CMYK and a Lab edit Lab) as the hex field does: with a rule the +/// theme follows from it as the new base. +fn sliders(ui: &mut Ui, d: &mut Draft) { + let t = Tokens::get(ui.ctx()); + let ctx = ui.ctx().clone(); + let current = slider_mode(&ctx, d.colors.get(d.sel)); + ui.horizontal(|ui| { + ui.label(egui::RichText::new(tl!("Color Mode:")).color(t.text_dim)); + let labels: Vec<&str> = SLIDER_MODES.iter().map(|m| m.label()).collect(); + if let Some(&m) = + widgets::dropdown_named(ui, "ct-mode", Some(tl!("Color Mode:")), current.label(), &labels, 90.0).and_then(|i| SLIDER_MODES.get(i)) + { + set_pstate(&ctx, "ct-mode", Some(m)); + } + }); + ui.add_space(2.0); + let mode = slider_mode(&ctx, d.colors.get(d.sel)); + let Some(comps) = slider_values(&ctx, d, mode) else { return }; + let spacing = 6.0; + let rail = (ui.available_width() - SLIDER_LABEL_W - SLIDER_FIELD_W - 2.0 * spacing - 4.0).max(40.0); + let mut set: Option> = None; + egui::Grid::new("ct-sliders").num_columns(3).spacing([spacing, 4.0]).show(ui, |ui| { + for (n, lbl) in mode.labels().iter().enumerate() { + let v = comps.get(n).copied().unwrap_or(0.0); + let shown = widgets::SliderValue::field(f64::from(v), f64::from(mode.min(n))..=f64::from(mode.max(n)), mode.suffix(n), 0); + let track = |x: f32| c32(&track_color(mode, &comps, n, x)); + if let Some(nv) = slider_cell(ui, ("ct", mode.label(), n), lbl, shown, mode.suffix(n), &track, SLIDER_LABEL_W, rail) { + let mut c2 = comps.clone(); + c2[n] = nv as f32; + set = Some(c2); + } + ui.end_row(); + } + }); + if let Some(v) = set { + d.set_selected(from_components(mode, &v)); + if let Some(&color) = d.colors.get(d.sel) { + set_pstate(&ctx, "ct-held", Some(Held { sel: d.sel, color, mode, v })); + } + } +} + /// Save the theme being made (overwriting the theme it edits); it then edits the saved theme. fn save(app: &mut VectorcraftApp, ctx: &egui::Context) { let mut d = draft(app, ctx); @@ -126,6 +233,17 @@ fn add_draft_to_swatches(app: &mut VectorcraftApp, ctx: &egui::Context) { app.run("swatch.newGroup", json!({ "name": name, "colors": colors_json(&d.colors), "keepModel": true })).ok(); } +/// Paint the active proxy (Fill or Stroke) with the selected colour of the theme being made, in its +/// own model: the selection and the new-art default take it in one paint command, so one undo +/// step, and no step when the art already has it. With characters selected with the Type tool, +/// only those characters take it and the new-art default stays as it was, as with a swatch click. +/// The theme stays as it is. +fn set_active_color(app: &mut VectorcraftApp, d: &Draft) { + if let Some(c) = d.colors.get(d.sel) { + app.run(proxy_cmd(app, false), json!({ "color": color_json(c), "keepModel": true })).ok(); + } +} + pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let ctx = ui.ctx().clone(); ui.horizontal(|ui| { @@ -187,11 +305,18 @@ fn create(app: &mut VectorcraftApp, ui: &mut Ui) { } } ui.add_space(6.0); + sliders(ui, &mut d); + ui.add_space(4.0); ui.horizontal(|ui| { let hex = d.colors.get(d.sel).map(|c| c.to_hex().trim_start_matches('#').to_string()).unwrap_or_default(); if let Some(c) = widgets::hex_field_named(ui, "ct-hex", Some(tl!("Color")), &hex).and_then(|h| Color::from_hex(&h)) { d.set_selected(c); } + let can_set = app.session.active().is_some() && d.colors.get(d.sel).is_some(); + let tip = tl!("Set the current fill or stroke to the selected color"); + if widgets::icon_button_enabled(ui, "paint-bucket", tip, false, can_set, 24.0).clicked() { + set_active_color(app, &d); + } let current = active_paint(app).color(); if widgets::icon_button_enabled(ui, "pipette", tl!("Set the selected color to the current color"), false, current.is_some(), 24.0).clicked() && let Some(c) = current @@ -241,6 +366,12 @@ enum Action { fn my_themes(app: &mut VectorcraftApp, ui: &mut Ui) { let t = Tokens::get(ui.ctx()); let ctx = ui.ctx().clone(); + // The find field lists the saved themes whose names hold its text, in their saved order. + if show_find(&ctx) { + widgets::search_field(ui, find_id(), tl!("Find")); + ui.add_space(4.0); + } + let q = query(&ctx); let pick = picked(app, &ctx); let mut action = None; if app.session.prefs.color_themes.is_empty() { @@ -248,7 +379,11 @@ fn my_themes(app: &mut VectorcraftApp, ui: &mut Ui) { } else { widgets::list_box(ui, |ui| { egui::ScrollArea::vertical().id_salt("ct-list").max_height(300.0).auto_shrink([false, true]).show(ui, |ui| { - for th in &app.session.prefs.color_themes { + let mut shown = app.session.prefs.color_themes.iter().filter(|th| matches(&th.name, &q)).peekable(); + if shown.peek().is_none() { + widgets::dim_label(ui, tl!("No matches.")); + } + for th in shown { let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), 44.0), Sense::hover()); let resp = ui.interact(r, ui.scope_id().with(("ct-theme", &th.name)), Sense::click()); let selected = pick.as_deref() == Some(th.name.as_str()); @@ -340,6 +475,11 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { { delete(app, &ctx, n); } + ui.separator(); + let find = show_find(&ctx); + if menu_item(ui, tl!("Show Find Field"), true, find) { + set_pstate(&ctx, "ct-show-find", !find); + } } else { if menu_item(ui, tl!("Save Theme"), true, false) { save(app, &ctx); @@ -454,6 +594,341 @@ mod tests { frame(&mut app, &ctx); } + /// The texts one frame draws: the panel, or with `menu_only` its panel menu, with `events`. + fn drawn(app: &mut VectorcraftApp, ctx: &egui::Context, menu_only: bool, events: Vec) -> Vec<(String, Rect)> { + crate::i18n::set_current(crate::i18n::Lang::EN); + let screen = Rect::from_min_size(egui::Pos2::ZERO, vec2(320.0, 700.0)); + let input = egui::RawInput { events, screen_rect: Some(screen), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| if menu_only { menu(app, ui) } else { show(app, ui) }); + out.textures_delta.clear(); + fn texts(s: &egui::Shape, out: &mut Vec<(String, 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| texts(s, out)), + _ => {} + } + } + let mut found = vec![]; + out.shapes.iter().for_each(|s| texts(&s.shape, &mut found)); + found + } + + /// The saved themes the My Themes list draws, in order. + fn listed(app: &mut VectorcraftApp, ctx: &egui::Context) -> Vec { + drawn(app, ctx, false, vec![]); + let names: Vec = themes(app).iter().map(|t| t.name.clone()).collect(); + drawn(app, ctx, false, vec![]).into_iter().map(|(t, _)| t).filter(|t| names.contains(t)).collect() + } + + /// Click panel menu item `label` (with its check mark, or three spaces when unchecked). + fn click_menu(app: &mut VectorcraftApp, ctx: &egui::Context, label: &str) { + let texts = drawn(app, ctx, true, vec![]); + let at = texts.iter().find(|(t, _)| t == label).unwrap_or_else(|| panic!("no {label:?} in {texts:?}")).1.center(); + let button = + |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + drawn(app, ctx, true, vec![egui::Event::PointerMoved(at), button(true), button(false)]); + } + + /// My Themes with three saved themes and the find field holding `text`. + fn three_themes(text: &str) -> (VectorcraftApp, egui::Context) { + let mut app = app(); + for (name, color) in [("Harbor", "#2266aa"), ("Harvest", "#cc8822"), ("Forest", "#227744")] { + app.run("colorTheme.save", json!({"color": color, "rule": "complementary", "name": name})).unwrap(); + } + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + set_pstate(&ctx, "ct-tab", 1usize); + set_pstate(&ctx, "ct-show-find", true); + ctx.data_mut(|d| d.insert_temp(find_id(), text.to_string())); + (app, ctx) + } + + /// Show Find Field is a checked item of the My Themes menu only, off in a new session; each + /// choice turns the field on or off. + #[test] + fn show_find_field_toggles_the_find_field_on_my_themes() { + let mut app = app(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let has = |texts: &[(String, Rect)], label: &str| texts.iter().any(|(t, _)| t == label); + let texts = drawn(&mut app, &ctx, true, vec![]); + assert!(!has(&texts, " Show Find Field") && !has(&texts, "✓ Show Find Field"), "the Create tab has no find field"); + set_pstate(&ctx, "ct-tab", 1usize); + assert!(has(&drawn(&mut app, &ctx, true, vec![]), " Show Find Field"), "off in a new session"); + assert!(!has(&drawn(&mut app, &ctx, false, vec![]), "Find"), "no field while it is off"); + click_menu(&mut app, &ctx, " Show Find Field"); + assert!(show_find(&ctx)); + assert!(has(&drawn(&mut app, &ctx, true, vec![]), "✓ Show Find Field")); + assert!(has(&drawn(&mut app, &ctx, false, vec![]), "Find"), "the field shows its hint"); + click_menu(&mut app, &ctx, "✓ Show Find Field"); + assert!(!show_find(&ctx)); + } + + /// The find field lists the themes whose names hold its text, in any letter case, anywhere in + /// the name, in their saved order; it reads names only, and its text is plain text. + #[test] + fn the_find_field_lists_themes_whose_names_hold_its_text() { + let (mut app, ctx) = three_themes(" HAR "); + assert_eq!(listed(&mut app, &ctx), ["Harbor", "Harvest"]); + ctx.data_mut(|d| d.insert_temp(find_id(), "vest".to_string())); + assert_eq!(listed(&mut app, &ctx), ["Harvest"], "a match in the middle of a name"); + // Colours are not searched: no name holds "2266aa". + ctx.data_mut(|d| d.insert_temp(find_id(), "2266aa".to_string())); + assert!(listed(&mut app, &ctx).is_empty()); + assert!(drawn(&mut app, &ctx, false, vec![]).iter().any(|(t, _)| t == "No matches.")); + assert_eq!(themes(&app).len(), 3, "the saved themes stay"); + // Pattern characters are plain text, and letters outside ASCII match in either case. + app.run("colorTheme.save", json!({"color": "#aa2266", "rule": "complementary", "name": "Été a.b*"})).unwrap(); + ctx.data_mut(|d| d.insert_temp(find_id(), "ÉTÉ A.B*".to_string())); + assert_eq!(listed(&mut app, &ctx), ["Été a.b*"]); + ctx.data_mut(|d| d.insert_temp(find_id(), ".*".to_string())); + assert!(listed(&mut app, &ctx).is_empty()); + // Blank text, or the field turned off, lists every theme; turned on again the text applies. + ctx.data_mut(|d| d.insert_temp(find_id(), " ".to_string())); + assert_eq!(listed(&mut app, &ctx).len(), 4); + ctx.data_mut(|d| d.insert_temp(find_id(), "har".to_string())); + set_pstate(&ctx, "ct-show-find", false); + assert_eq!(listed(&mut app, &ctx).len(), 4); + set_pstate(&ctx, "ct-show-find", true); + assert_eq!(listed(&mut app, &ctx), ["Harbor", "Harvest"]); + } + + /// With no saved themes the panel says so, whatever the find field holds. + #[test] + fn no_saved_themes_is_not_no_matches() { + let mut app = app(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + set_pstate(&ctx, "ct-tab", 1usize); + set_pstate(&ctx, "ct-show-find", true); + ctx.data_mut(|d| d.insert_temp(find_id(), "har".to_string())); + drawn(&mut app, &ctx, false, vec![]); + let texts: Vec = drawn(&mut app, &ctx, false, vec![]).into_iter().map(|(t, _)| t).collect(); + assert!(texts.iter().any(|t| t == "No saved themes"), "{texts:?}"); + assert!(!texts.iter().any(|t| t == "No matches.")); + } + + /// A picked theme that the find field hides stays picked, but neither the menu nor the footer + /// acts on it until the list shows it again. + #[test] + fn a_theme_the_find_field_hides_is_not_acted_on() { + let (mut app, ctx) = three_themes("har"); + set_pstate(&ctx, "ct-picked", Some("Forest".to_string())); + assert_eq!(picked(&app, &ctx), None); + drawn(&mut app, &ctx, true, vec![]); + click_menu(&mut app, &ctx, " Delete Theme"); + assert_eq!(themes(&app).len(), 3, "Delete Theme is off"); + click_menu(&mut app, &ctx, " Edit Theme"); + assert_eq!(tab(&ctx), 1, "Edit Theme is off"); + let undo = undo_len(&app); + click_menu(&mut app, &ctx, " Add to Swatches"); + assert_eq!(undo_len(&app), undo, "Add to Swatches is off"); + // Cleared, the field lists Forest again and it is picked as before. + ctx.data_mut(|d| d.insert_temp(find_id(), String::new())); + assert_eq!(picked(&app, &ctx).as_deref(), Some("Forest")); + ctx.data_mut(|d| d.insert_temp(find_id(), "har".to_string())); + set_pstate(&ctx, "ct-show-find", false); + assert_eq!(picked(&app, &ctx).as_deref(), Some("Forest"), "the field turned off lists it too"); + set_pstate(&ctx, "ct-show-find", true); + // A theme the field shows is acted on. + set_pstate(&ctx, "ct-picked", Some("Harvest".to_string())); + click_menu(&mut app, &ctx, " Delete Theme"); + assert_eq!(themes(&app).iter().map(|t| t.name.as_str()).collect::>(), ["Harbor", "Forest"]); + } + + /// The footer buttons are off for a picked theme that the find field hides. + #[test] + fn footer_buttons_are_off_for_a_hidden_pick() { + use crate::widgets::accessibility_tests::{named, tree}; + let mut app = app(); + app.run("colorTheme.save", json!({"color": "#227744", "rule": "complementary", "name": "Forest"})).unwrap(); + for (text, off) in [("har", true), ("for", false)] { + let shown = tree(|ui| { + let ctx = ui.ctx().clone(); + set_pstate(&ctx, "ct-tab", 1usize); + set_pstate(&ctx, "ct-show-find", true); + set_pstate(&ctx, "ct-picked", Some("Forest".to_string())); + ctx.data_mut(|d| d.insert_temp(find_id(), text.to_string())); + show(&mut app, ui); + }); + for label in ["Edit theme", "Add to Swatches", "Delete theme"] { + assert_eq!(named(&shown, label).is_disabled(), off, "{label} with {text:?}"); + } + } + } + + const SET_ACTIVE: &str = "Set the current fill or stroke to the selected color"; + + /// A click on the panel button that screen readers name `label`. egui finds what the pointer is + /// over from the frame before, so the move gets a frame of its own. + fn click(app: &mut VectorcraftApp, ctx: &egui::Context, label: &str) { + crate::i18n::set_current(crate::i18n::Lang::EN); + ctx.enable_accesskit(); + let mut time = ctx.input(|i| i.time); + let mut run = |app: &mut VectorcraftApp, events: Vec| { + time += 0.1; + let screen = Rect::from_min_size(egui::Pos2::ZERO, vec2(320.0, 520.0)); + let input = egui::RawInput { events, time: Some(time), screen_rect: Some(screen), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| show(app, ui)); + out.textures_delta.clear(); + out + }; + run(app, vec![]); + let out = run(app, vec![]); + let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes; + let node = nodes.iter().find(|(_, n)| n.label() == Some(label)); + let b = node.unwrap_or_else(|| panic!("nothing named {label:?}")).1.bounds().expect("bounds"); + let at = egui::pos2((b.x0 + b.x1) as f32 * 0.5, (b.y0 + b.y1) as f32 * 0.5); + let button = + |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + run(app, vec![egui::Event::PointerMoved(at)]); + run(app, vec![button(true)]); + run(app, vec![button(false)]); + } + + /// A Custom theme of five different colours with the third selected. + fn five_colors(ctx: &egui::Context) -> Draft { + let colors = ["#cc2200", "#22aa44", "#3355dd", "#ddbb11", "#884499"].map(|h| Color::from_hex(h).unwrap()).to_vec(); + let d = Draft { colors, rule: None, sel: 2, name: "Mine".into(), editing: None }; + set_draft(ctx, d.clone()); + d + } + + /// The fill and stroke paints of object `id`. + fn paints(app: &VectorcraftApp, id: vectorcraft_doc::NodeId) -> (vectorcraft_color::Paint, vectorcraft_color::Paint) { + let n = app.session.doc().unwrap().doc.node(id).unwrap(); + (n.appearance.fill().unwrap().paint.clone(), n.appearance.stroke().unwrap().paint.clone()) + } + + fn undo_len(app: &VectorcraftApp) -> usize { + app.session.doc().unwrap().history.undo.len() + } + + /// Screen readers name the Set Active Color button by its tool tip; it is off without a document. + #[test] + fn set_active_color_is_named_and_needs_a_document() { + use crate::widgets::accessibility_tests::{named, tree}; + let mut app = app(); + let shown = tree(|ui| show(&mut app, ui)); + assert_eq!(named(&shown, SET_ACTIVE).role(), egui::accesskit::Role::Button); + assert!(!named(&shown, SET_ACTIVE).is_disabled()); + let mut none = VectorcraftApp::new(Session::new(), Default::default()); + let shown = tree(|ui| show(&mut none, ui)); + assert!(named(&shown, SET_ACTIVE).is_disabled(), "no document: nothing to paint"); + } + + /// Set Active Color paints the active proxy of the selection with the selected theme colour, + /// one undo step a click, none when the art already has it, and leaves the theme as it is. + #[test] + fn set_active_color_paints_the_active_proxy_with_the_selected_color() { + let mut app = app(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap(); + let id = app.session.doc().unwrap().selection.objects[0]; + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let d = five_colors(&ctx); + let (_, stroke) = paints(&app, id); + let undo = undo_len(&app); + click(&mut app, &ctx, SET_ACTIVE); + assert_eq!(paints(&app, id), (vectorcraft_color::Paint::solid(d.colors[2]), stroke.clone()), "the selected colour, not the first"); + assert_eq!(undo_len(&app), undo + 1, "one undo step"); + click(&mut app, &ctx, SET_ACTIVE); + assert_eq!(undo_len(&app), undo + 1, "no step when the fill already has the colour"); + // With the Stroke proxy in front, the stroke takes the colour and the fill stays. + app.run("paint.toggleActive", json!({"fill": false})).unwrap(); + set_draft(&ctx, Draft { sel: 3, ..d.clone() }); + click(&mut app, &ctx, SET_ACTIVE); + let solid = |i: usize| vectorcraft_color::Paint::solid(d.colors[i]); + assert_eq!(paints(&app, id), (solid(2), solid(3))); + assert_eq!(undo_len(&app), undo + 2); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(paints(&app, id), (solid(2), stroke.clone()), "one undo takes the stroke back"); + app.run("edit.redo", json!({})).unwrap(); + assert_eq!(paints(&app, id), (solid(2), solid(3))); + // The theme being made and the saved themes stay as they were. + assert_eq!(draft(&app, &ctx), Draft { sel: 3, ..d.clone() }); + assert!(themes(&app).is_empty()); + // The reverse pipette paints nothing. + let undo = undo_len(&app); + click(&mut app, &ctx, "Set the selected color to the current color"); + assert_eq!((paints(&app, id), undo_len(&app)), ((solid(2), solid(3)), undo)); + } + + /// With nothing selected, Set Active Color sets the new-art default alone, without an undo step, + /// and new art takes it. + #[test] + fn set_active_color_with_nothing_selected_sets_the_default_for_new_art() { + let mut app = app(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let d = five_colors(&ctx); + let undo = undo_len(&app); + click(&mut app, &ctx, SET_ACTIVE); + assert_eq!(app.session.paint.fill, vectorcraft_color::Paint::solid(d.colors[2])); + assert_eq!(undo_len(&app), undo, "no art changed"); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap(); + let id = app.session.doc().unwrap().selection.objects[0]; + assert_eq!(paints(&app, id).0, vectorcraft_color::Paint::solid(d.colors[2])); + } + + /// In a CMYK document Set Active Color keeps an RGB theme colour in RGB. + #[test] + fn set_active_color_keeps_the_model_in_a_cmyk_document() { + let mut app = app(); + app.run("file.documentColorMode", json!({"mode": "cmyk"})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap(); + let id = app.session.doc().unwrap().selection.objects[0]; + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let d = five_colors(&ctx); + click(&mut app, &ctx, SET_ACTIVE); + assert_eq!(paints(&app, id).0.color(), Some(d.colors[2])); + assert!(matches!(d.colors[2], Color::Rgb { .. })); + } + + /// With characters selected with the Type tool, Set Active Color paints those characters as a + /// swatch click does: the type and the undo history come out as they do from `paint.setFill` with + /// the same color, and the new-art default stays as it was. + #[test] + fn set_active_color_paints_selected_characters_as_a_swatch_click_does() { + use vectorcraft_doc::{NodeId, NodeKind}; + // The editing handshake of text_styles::tests::select_type_range. + let typed = || { + let mut app = app(); + let id = NodeId(app.run("text.create", json!({"x": 10, "y": 50, "text": "ABcdef", "size": 18})).unwrap()["id"].as_u64().unwrap()); + app.session.select_tool("type", Default::default()).unwrap(); + app.session.apply_actions(vec![vectorcraft_tools::Action::Notify("text.editNew".into())]).unwrap(); + app.session.set_tool_option("select", &json!({"start": 2, "end": 4})); + super::super::character::end_typing(&mut app); + assert_eq!(super::super::character::text_editing(&app), Some((id, 2, 4))); + (app, id) + }; + let runs = |app: &VectorcraftApp, id: NodeId| match &app.session.doc().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => t.runs.clone(), + _ => panic!("not type"), + }; + let (mut by_button, id) = typed(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let d = five_colors(&ctx); + let undo = undo_len(&by_button); + let default = (by_button.session.paint.fill.clone(), by_button.session.paint.stroke.clone()); + assert_ne!(default.0, vectorcraft_color::Paint::solid(d.colors[2])); + click(&mut by_button, &ctx, SET_ACTIVE); + let (mut by_command, _) = typed(); + by_command.run("paint.setFill", json!({"color": color_json(&d.colors[2]), "keepModel": true})).unwrap(); + let painted = runs(&by_button, id); + assert!(painted.iter().any(|r| r.style.fill == vectorcraft_color::Paint::solid(d.colors[2])), "the characters take the color"); + assert!(painted.iter().any(|r| r.style.fill != vectorcraft_color::Paint::solid(d.colors[2])), "the other characters keep theirs"); + assert_eq!(painted, runs(&by_command, id)); + assert_eq!((&by_button.session.paint.fill, &by_button.session.paint.stroke), (&default.0, &default.1), "the default stays"); + assert_eq!( + (&by_button.session.paint.fill, &by_button.session.paint.stroke), + (&by_command.session.paint.fill, &by_command.session.paint.stroke) + ); + assert_eq!((undo_len(&by_button), undo_len(&by_command)), (undo + 1, undo + 1)); + } + /// In a CMYK document the theme being made goes to Swatches with its colors in their own model. #[test] fn the_theme_being_made_keeps_its_model_in_a_cmyk_document() { @@ -471,4 +946,234 @@ mod tests { let g = app.session.doc().unwrap().doc.swatch_groups.last().expect("the group"); assert_eq!(g.swatches.iter().filter_map(|w| w.paint.color()).collect::>(), colors); } + + /// One frame of the panel in a 260 × 700 window with `events`, in English, with screen readers on. + fn step(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) -> egui::FullOutput { + crate::i18n::set_current(crate::i18n::Lang::EN); + ctx.enable_accesskit(); + let time = ctx.input(|i| i.time) + 0.1; + let screen = Rect::from_min_size(egui::Pos2::ZERO, vec2(260.0, 700.0)); + let input = egui::RawInput { events, time: Some(time), screen_rect: Some(screen), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| show(app, ui)); + out.textures_delta.clear(); + out + } + + /// The screen-reader nodes of the frame after a settling one. + fn nodes(app: &mut VectorcraftApp, ctx: &egui::Context) -> Vec<(egui::accesskit::NodeId, egui::accesskit::Node)> { + step(app, ctx, vec![]); + step(app, ctx, vec![]).platform_output.accesskit_update.expect("an accessibility tree").nodes + } + + /// The labels of the color sliders the Create tab shows (named by one letter, unlike the wheel's + /// Brightness slider), with each one's range, in order. + fn slider_ranges(app: &mut VectorcraftApp, ctx: &egui::Context) -> Vec<(String, f64, f64)> { + let mut found: Vec<(f64, String, f64, f64)> = nodes(app, ctx) + .into_iter() + .filter(|(_, n)| n.role() == egui::accesskit::Role::Slider && n.label().is_some_and(|l| l.chars().count() == 1)) + .filter_map(|(_, n)| { + let top = n.bounds()?.y0; + Some((top, n.label()?.to_string(), n.min_numeric_value()?, n.max_numeric_value()?)) + }) + .collect(); + found.sort_by(|a, b| a.0.total_cmp(&b.0)); + found.into_iter().map(|(_, l, lo, hi)| (l, lo, hi)).collect() + } + + /// The node id and bounds of the screen-reader node named `label` whose role is (with `rail`) or + /// is not a slider. + fn node(app: &mut VectorcraftApp, ctx: &egui::Context, label: &str, rail: bool) -> (egui::accesskit::NodeId, egui::Pos2) { + let all = nodes(app, ctx); + let (id, n) = all + .iter() + .find(|(_, n)| n.label() == Some(label) && (n.role() == egui::accesskit::Role::Slider) == rail) + .unwrap_or_else(|| panic!("nothing named {label:?}")); + let b = n.bounds().expect("bounds"); + (*id, egui::pos2((b.x0 + b.x1) as f32 * 0.5, (b.y0 + b.y1) as f32 * 0.5)) + } + + /// A screen reader's set-value action on the slider named `label`. + fn set_slider(app: &mut VectorcraftApp, ctx: &egui::Context, label: &str, value: f64) { + use egui::accesskit::{Action, ActionData, ActionRequest, TreeId}; + let (target_node, _) = node(app, ctx, label, true); + let data = Some(ActionData::NumericValue(value)); + step( + app, + ctx, + vec![egui::Event::AccessKitActionRequest(ActionRequest { action: Action::SetValue, target_node, target_tree: TreeId::ROOT, data })], + ); + step(app, ctx, vec![]); + } + + /// A click at `at`, each event in a frame of its own. + fn press_at(app: &mut VectorcraftApp, ctx: &egui::Context, at: egui::Pos2) { + let button = + |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + step(app, ctx, vec![egui::Event::PointerMoved(at)]); + step(app, ctx, vec![button(true)]); + step(app, ctx, vec![button(false)]); + } + + fn key(app: &mut VectorcraftApp, ctx: &egui::Context, key: egui::Key, modifiers: egui::Modifiers) { + step(app, ctx, vec![egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }]); + step(app, ctx, vec![egui::Event::Key { key, physical_key: None, pressed: false, repeat: false, modifiers }]); + } + + /// Type `text` into the number field named `label` in place of its number, and press Enter. + fn type_into(app: &mut VectorcraftApp, ctx: &egui::Context, label: &str, text: &str) { + let (_, at) = node(app, ctx, label, false); + press_at(app, ctx, at); + key(app, ctx, egui::Key::A, egui::Modifiers::COMMAND); + step(app, ctx, vec![egui::Event::Text(text.into())]); + key(app, ctx, egui::Key::Enter, egui::Modifiers::NONE); + step(app, ctx, vec![]); + } + + /// The Create tab offers a Color Mode menu of CMYK, RGB, Lab and HSB with a rail and a number + /// field for each component over its range, beside the hex field. It starts in the selected + /// color's own model (HSB for a gray), keeps the mode picked while the app runs, and picking a + /// mode changes no color. + #[test] + fn the_create_tab_offers_cmyk_rgb_lab_and_hsb_sliders() { + let mut app = app(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut d = five_colors(&ctx); + let named = |app: &mut VectorcraftApp, ctx: &egui::Context, label: &str| nodes(app, ctx).iter().any(|(_, n)| n.label() == Some(label)); + assert!(named(&mut app, &ctx, "Color Mode:"), "the menu is named"); + assert!(named(&mut app, &ctx, "Color"), "the hex field stays"); + let rgb = vec![("R".to_string(), 0.0, 255.0), ("G".into(), 0.0, 255.0), ("B".into(), 0.0, 255.0)]; + assert_eq!(slider_ranges(&mut app, &ctx), rgb, "an RGB color starts in RGB"); + for (c, first) in [(Color::cmyk(0.1, 0.2, 0.3, 0.4), "C"), (Color::lab(50.0, -20.0, 30.0), "L"), (Color::gray(0.5), "H")] { + d.colors[2] = c; + set_draft(&ctx, d.clone()); + assert_eq!(slider_ranges(&mut app, &ctx)[0].0, first, "{c:?}"); + } + let expect = [ + vec![("C", 0.0, 100.0), ("M", 0.0, 100.0), ("Y", 0.0, 100.0), ("K", 0.0, 100.0)], + vec![("R", 0.0, 255.0), ("G", 0.0, 255.0), ("B", 0.0, 255.0)], + vec![("L", 0.0, 100.0), ("a", -128.0, 127.0), ("b", -128.0, 127.0)], + vec![("H", 0.0, 360.0), ("S", 0.0, 100.0), ("B", 0.0, 100.0)], + ]; + for (m, rows) in SLIDER_MODES.into_iter().zip(expect) { + set_pstate(&ctx, "ct-mode", Some(m)); + let rows: Vec<(String, f64, f64)> = rows.into_iter().map(|(l, lo, hi)| (l.to_string(), lo, hi)).collect(); + assert_eq!(slider_ranges(&mut app, &ctx), rows, "{m:?}"); + assert_eq!(draft(&app, &ctx), d, "picking a mode changes no color"); + } + // The picked mode stays when another color is selected. + set_draft(&ctx, Draft { sel: 0, ..d.clone() }); + assert_eq!(slider_ranges(&mut app, &ctx)[0].0, "H"); + } + + /// In Custom, a rail, the arrow keys and the number field change the selected color alone, in + /// the menu's mode, and the selection stays; the other numbers stay as they were set. + #[test] + fn a_slider_edit_changes_only_the_selected_custom_color() { + let mut app = app(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let d = five_colors(&ctx); + let start = components(Mode::Rgb, &d.colors[2]); + set_slider(&mut app, &ctx, "R", 10.0); + let now = draft(&app, &ctx); + assert_eq!(now.colors[2], from_components(Mode::Rgb, &[10.0, start[1], start[2]])); + assert_eq!(now.sel, 2); + for i in [0, 1, 3, 4] { + assert_eq!(now.colors[i], d.colors[i], "color {i} stays"); + } + // The arrow keys step the focused rail by one. + let (_, at) = node(&mut app, &ctx, "G", true); + press_at(&mut app, &ctx, at); + let held = pstate::>(&ctx, "ct-held").expect("held").v; + key(&mut app, &ctx, egui::Key::ArrowRight, egui::Modifiers::NONE); + let after = pstate::>(&ctx, "ct-held").expect("held").v; + assert_eq!(after, vec![10.0, held[1] + 1.0, start[2]]); + // The number field. + type_into(&mut app, &ctx, "B", "40"); + let now = draft(&app, &ctx); + assert_eq!(now.colors[2], from_components(Mode::Rgb, &[10.0, held[1] + 1.0, 40.0])); + assert_eq!((now.sel, now.rule), (2, None)); + assert_eq!(now.colors[0], d.colors[0]); + } + + /// The sliders keep the numbers they set: an HSB color taken to no saturation keeps its hue on + /// the H slider, and S back up brings that hue back. Another color shows its own numbers. + #[test] + fn the_sliders_keep_the_numbers_they_set() { + let mut app = app(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + five_colors(&ctx); + set_pstate(&ctx, "ct-mode", Some(Mode::Hsb)); + let hue = |app: &mut VectorcraftApp, ctx: &egui::Context| { + let (id, _) = node(app, ctx, "H", true); + nodes(app, ctx).into_iter().find(|(n, _)| *n == id).and_then(|(_, n)| n.numeric_value()) + }; + set_slider(&mut app, &ctx, "H", 200.0); + set_slider(&mut app, &ctx, "S", 0.0); + assert_eq!(hue(&mut app, &ctx), Some(200.0), "a gray keeps the hue it was set to"); + set_slider(&mut app, &ctx, "S", 80.0); + let [h, s, _] = draft(&app, &ctx).colors[2].to_hsb(); + assert!((h - 200.0).abs() < 0.5 && (s - 0.8).abs() < 1e-3, "{h} {s}"); + set_draft(&ctx, Draft { sel: 0, ..draft(&app, &ctx) }); + let own = components(Mode::Hsb, &draft(&app, &ctx).colors[0])[0].round(); + assert_eq!(hue(&mut app, &ctx), Some(f64::from(own)), "another color shows its own numbers"); + } + + /// With a rule, a slider edit makes the edited color the theme's new base, as a hex edit does, + /// and selects it. + #[test] + fn with_a_rule_a_slider_edit_rebuilds_the_theme_from_the_edited_color() { + let mut app = app(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let d = Draft { rule: Some(Harmony::Triad), ..five_colors(&ctx) }; + set_draft(&ctx, d.clone()); + set_pstate(&ctx, "ct-mode", Some(Mode::Hsb)); + let start = components(Mode::Hsb, &d.colors[2]); + set_slider(&mut app, &ctx, "H", 200.0); + let base = from_components(Mode::Hsb, &[200.0, start[1], start[2]]); + let now = draft(&app, &ctx); + assert_eq!((now.colors, now.sel), (Harmony::Triad.theme(base), 0)); + } + + /// A CMYK edit keeps the color CMYK and a Lab edit keeps it Lab, with the numbers set, through + /// Save and Add to Swatches in a CMYK document; a number that is not one, or not finite, changes + /// nothing, and one past the range sets its end. + #[test] + fn cmyk_and_lab_slider_edits_keep_their_models() { + let mut app = app(); + app.run("file.documentColorMode", json!({"mode": "cmyk"})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let d = five_colors(&ctx); + set_pstate(&ctx, "ct-mode", Some(Mode::Cmyk)); + let start = components(Mode::Cmyk, &d.colors[2]); + set_slider(&mut app, &ctx, "C", 20.0); + set_slider(&mut app, &ctx, "K", 40.0); + let cmyk = from_components(Mode::Cmyk, &[20.0, start[1], start[2], 40.0]); + assert_eq!(draft(&app, &ctx).colors[2], cmyk); + assert!(matches!(cmyk, Color::Cmyk { k, .. } if (k - 0.4).abs() < 1e-6)); + // Lab on another color. + set_draft(&ctx, Draft { sel: 3, ..draft(&app, &ctx) }); + set_pstate(&ctx, "ct-mode", Some(Mode::Lab)); + let start = components(Mode::Lab, &d.colors[3]); + set_slider(&mut app, &ctx, "b", -60.0); + let lab = Color::lab(start[0], start[1], -60.0); + assert_eq!(draft(&app, &ctx).colors[3], lab); + // Not numbers, not finite, past the range. + let before = draft(&app, &ctx); + type_into(&mut app, &ctx, "L", "abc"); + set_slider(&mut app, &ctx, "a", f64::NAN); + assert_eq!(draft(&app, &ctx), before); + set_slider(&mut app, &ctx, "a", 500.0); + assert_eq!(draft(&app, &ctx).colors[3], Color::lab(start[0], 127.0, -60.0)); + let colors = draft(&app, &ctx).colors; + save(&mut app, &ctx); + assert_eq!(themes(&app)[0].colors, colors, "saved in their models"); + add_draft_to_swatches(&mut app, &ctx); + let g = app.session.doc().unwrap().doc.swatch_groups.last().expect("the group"); + assert_eq!(g.swatches.iter().filter_map(|w| w.paint.color()).collect::>(), colors); + } } 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 59d518cb1b..2696c78c08 100644 --- a/crates/ui-egui/src/panels/graphic_styles.rs +++ b/crates/ui-egui/src/panels/graphic_styles.rs @@ -3,10 +3,13 @@ //! 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. Holding the right button on a style +//! canvas or the Appearance panel's thumbnail dropped on the panel becomes a new style, and +//! dropped on a style with Alt held replaces that style with its look (`graphicStyle.redefine`). +//! Holding the right button on a style //! shows it large, on the selected object when there is one. The Control bar's Style picker lists //! the same tiles ([`picker`]). Graphic style libraries open in library panels //! ([`GraphicStyleLibraries`]). @@ -364,6 +367,10 @@ struct Events { moved: Option<(String, usize)>, /// Art or an appearance dropped on the panel: a new style from this object. 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. @@ -383,10 +390,27 @@ 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. +/// 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) { let name = &d.graphic_styles[i].name; widgets::drag_source(ui, resp, || PanelDrag::GraphicStyle(name.clone())); + let source = resp.dnd_hover_payload::().and_then(|drag| match &*drag { + PanelDrag::Art(ids) => ids.first().copied(), + PanelDrag::Appearance(id) => Some(*id), + _ => None, + }); + if let Some(id) = source + && alt_held(ui) + { + ev.over = true; + widgets::drop_target_outline(ui, resp.rect); + if resp.dnd_release_payload::().is_some() { + ev.replaced = Some((name.clone(), id)); + } + } if let Some(drag) = resp.dnd_hover_payload::() && let PanelDrag::GraphicStyle(moving) = &*drag { @@ -394,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()); @@ -432,7 +461,7 @@ fn zone_input(ui: &Ui, zone: &Response, d: &Document, ev: &mut Events) { PanelDrag::Art(ids) => (None, ids.first().copied()), PanelDrag::Appearance(id) => (None, Some(*id)), PanelDrag::Paint { .. } - | PanelDrag::Symbol(_) + | PanelDrag::Symbol { .. } | PanelDrag::LibrarySymbol { .. } | PanelDrag::Brush { .. } | PanelDrag::LibraryBrush { .. } @@ -505,6 +534,15 @@ fn act(app: &mut VectorcraftApp, ui: &Ui, s: &Shown, ev: Events, picker: bool) { if let Some(id) = ev.new_from { run(app, "graphicStyle.new", json!({ "id": id.0 })); } + // An object that is linked to the style and still has its look leaves the style as it is. + if let Some((name, id)) = ev.replaced + && !app.session.graphic_style_of(id).is_some_and(|(g, linked)| linked && g.name == name) + { + 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(); @@ -1432,6 +1470,190 @@ mod tests { } } + /// Art or the Appearance panel's thumbnail dropped on a style with Alt held replaces that style + /// with the object's look, in one undo step: the style keeps its name, its place and its id, the + /// objects still linked to it take the new look, and the object becomes linked. The style is + /// outlined while one is held over it with Alt. Without Alt the drop makes a new style; a style + /// dragged with Alt still only moves; an object linked to the style with its look, an empty art + /// drag and an object that is gone change nothing and record no undo step. + #[test] + fn art_or_an_appearance_dropped_on_a_style_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(); + 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 = doc(&app).graphic_style("Red").unwrap().clone(); + let green = doc(&app).node(oval).unwrap().appearance.fill_paint(); + assert_ne!(red.appearance.fill_paint(), green); + // 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); + for payload in [PanelDrag::Art(vec![oval]), PanelDrag::Appearance(oval)] { + let n = names(&app); + let before = steps(&app); + // Held over the style with Alt it is outlined; without Alt it is not. + egui::DragAndDrop::set_payload(&ctx, payload.clone()); + assert!(!frame_at(&mut app, at, vec![egui::Event::PointerMoved(at)], none), "{view:?} {payload:?}: no outline without Alt"); + assert!(frame_at(&mut app, at, vec![egui::Event::PointerMoved(at)], alt), "{view:?} {payload:?}: outlined with Alt"); + assert_eq!(names(&app), n, "{view:?} {payload:?}: holding it there changes nothing"); + // Released there with Alt: Red takes the oval'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:?} {payload:?}"); + let g = d.graphic_style("Red").unwrap(); + assert_eq!((g.id, g.appearance.fill_paint()), (red.id, green.clone()), "{view:?} {payload:?}"); + assert_eq!(d.node(rect).unwrap().appearance.fill_paint(), green, "{view:?} {payload:?}: the linked rectangle follows"); + assert_eq!(d.node(rect).unwrap().extras().graphic_style, Some(red.id)); + assert_eq!(d.node(oval).unwrap().extras().graphic_style, Some(red.id), "{view:?} {payload:?}: the oval is linked"); + assert_eq!(steps(&app), before + 1, "{view:?} {payload:?}: one undo step"); + app.run("edit.undo", json!({})).unwrap(); + let d = doc(&app); + assert_eq!(d.graphic_style("Red").unwrap().appearance, red.appearance, "{view:?} {payload:?}: undo restores the style"); + assert_eq!(d.node(oval).unwrap().extras().graphic_style, None); + assert_eq!(d.node(rect).unwrap().appearance.fill_paint(), red.appearance.fill_paint()); + } + + // Without Alt the oval becomes a new style at the end, and Red stays as it was. + let n = names(&app); + egui::DragAndDrop::set_payload(&ctx, PanelDrag::Art(vec![oval])); + frame_at(&mut app, at, release(at, none), none); + assert_eq!(names(&app).len(), n.len() + 1, "{view:?}"); + assert_eq!(doc(&app).graphic_style("Red").unwrap().appearance, red.appearance, "{view:?}"); + app.run("edit.undo", json!({})).unwrap(); + + // 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, 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(); + assert_eq!(names(&app), n, "{view:?}"); + + // The rectangle that is linked to Red with its look, an empty drag of art and an object + // that is gone change nothing and record nothing. + let before = steps(&app); + for payload in [PanelDrag::Art(vec![rect]), PanelDrag::Appearance(rect), PanelDrag::Art(vec![]), PanelDrag::Art(vec![NodeId(9999)])] { + egui::DragAndDrop::set_payload(&ctx, payload.clone()); + frame_at(&mut app, at, release(at, alt), alt); + assert_eq!(names(&app), n, "{view:?} {payload:?}"); + assert_eq!(doc(&app).graphic_style("Red").unwrap().appearance, red.appearance, "{view:?} {payload:?}"); + assert_eq!(steps(&app), before, "{view:?} {payload:?}"); + } + } + } + + /// 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/layers.rs b/crates/ui-egui/src/panels/layers.rs index 6e8c2648fa..5871db03b3 100644 --- a/crates/ui-egui/src/panels/layers.rs +++ b/crates/ui-egui/src/panels/layers.rs @@ -221,6 +221,14 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { reveal = rows.first().copied(); ui.data_mut(|d| d.insert_temp(key("seen"), rows.clone())); } + // Locate Object or Locate Layer (`layer.locate`): the located row is revealed each time, also + // when it was already highlighted and a layer around it was closed since or the list scrolled + // away. A request for a row no longer highlighted is dropped. + let locate = app.session.active_mut().and_then(|st| st.locate_reveal.take()).filter(|id| rows.contains(id)); + if let Some(id) = locate { + open_around(app, &doc, &[id]); + reveal = Some(id); + } let highlighted = reveal.is_some(); // A new active layer (a canvas selection highlights no row): reveal it too, unless a row // highlighted in the panel holds the view. @@ -330,15 +338,17 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { // The column drag: live while it lasts, one undo step when the button is released. let released = ui.input(|i| i.pointer.any_released()); // Layers dragged into the empty space under the last row go below the bottom layer (there is - // no row there to take the drop). + // no row there to take the drop). The bottom layer itself goes there only as an Alt copy, + // which lands below it; moved, it would stay where it is (#8237). let below = list_rect.top() - scrolled.inner.state.clamped_offset().y + list.len() as f32 * view.h; + let alt = ui.input(|i| i.modifiers.alt); if query.is_empty() && !app.ui.layers_filter.is_on() && let Some(drag) = egui::DragAndDrop::payload::(ui.ctx()) && let LayersDrag::Rows(ids) = &*drag && let Some(bottom) = doc.layers.first() && !ids.is_empty() - && !ids.contains(&bottom.id) + && (alt || !ids.contains(&bottom.id)) && ids.iter().all(|i| doc.node(*i).is_some_and(Node::is_layer)) && let Some(p) = ui.input(|i| i.pointer.hover_pos()) && list_rect.contains(p) diff --git a/crates/ui-egui/src/panels/layers/controls.rs b/crates/ui-egui/src/panels/layers/controls.rs index c030cd85c8..573c18adb9 100644 --- a/crates/ui-egui/src/panels/layers/controls.rs +++ b/crates/ui-egui/src/panels/layers/controls.rs @@ -116,8 +116,11 @@ pub(super) fn bottom_bar(app: &mut VectorcraftApp, ui: &mut Ui, view: &View, doc if widgets::icon_button(&mut child, "frame", tl!("Make/Release Clipping Mask"), false, 24.0).clicked() { actions.push(("layer.clippingMask.toggle".into(), json!({}))); } - if widgets::icon_button(&mut child, "search", tl!("Locate Object"), false, 24.0).clicked() { - actions.push(("layer.locate".into(), json!({}))); + // With Show Layers Only on, Locate Object becomes Locate Layer: it highlights the layer row. + let layers_only = view.opts.layers_only; + let locate = if layers_only { tl!("Locate Layer") } else { tl!("Locate Object") }; + if widgets::icon_button(&mut child, "search", locate, false, 24.0).clicked() { + actions.push(("layer.locate".into(), json!({ "layersOnly": layers_only }))); } } @@ -132,6 +135,7 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { let current = st.current_layer(); let has_sel = !st.selection.is_empty(); let isolated = st.isolation.is_some(); + let layers_only = app.ui.layers_panel.layers_only; let targets: Vec = if rows.is_empty() { current.into_iter().collect() } else { rows.clone() }; let one_container = match targets.as_slice() { [id] => doc.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. })), @@ -166,7 +170,11 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { }); items.extend([ None, - Some(("Locate Object", "layer.locate", json!({}), has_sel, false)), + Some(if layers_only { + ("Locate Layer", "layer.locate", json!({"layersOnly": true}), has_sel, false) + } else { + ("Locate Object", "layer.locate", json!({}), has_sel, false) + }), // Sentinel: rendered as the Save Selection submenu (the Select menu's saved-selection items). Some(("Save Selection", "", json!({}), true, false)), None, diff --git a/crates/ui-egui/src/panels/layers/rows.rs b/crates/ui-egui/src/panels/layers/rows.rs index 62e32f1097..447133e7d6 100644 --- a/crates/ui-egui/src/panels/layers/rows.rs +++ b/crates/ui-egui/src/panels/layers/rows.rs @@ -510,9 +510,10 @@ fn row_context_menu(ui: &mut Ui, view: &View, n: &Node, collect_ids: &[u64], out } } ui.separator(); - // Locate Object - if widgets::menu_item(ui, "Locate Object", true, false) { - out.actions.push(("layer.locate".into(), json!({ "id": n.id.0 }))); + // Locate Object, or Locate Layer with Show Layers Only on + let layers_only = view.opts.layers_only; + if widgets::menu_item(ui, if layers_only { "Locate Layer" } else { "Locate Object" }, true, false) { + out.actions.push(("layer.locate".into(), json!({ "id": n.id.0, "layersOnly": layers_only }))); ui.close(); } ui.separator(); @@ -674,15 +675,20 @@ fn drop_target(ui: &Ui, view: &View, n: &Node, r: egui::Rect, indent: f32, open: return; } }; - // Never into itself or a row inside it. + // Never into itself or a row inside it. With Alt, rows held over one of their own rows copy + // beside it, above or below, as `layer.move` places a copy there (#8237). + let alt = ui.input(|i| i.modifiers.alt); + let beside_itself = alt && matches!(&*drag, LayersDrag::Rows(_)) && moving.contains(&n.id); let around = doc.ancestry(n.id).unwrap_or_default(); - if moving.is_empty() || moving.iter().any(|m| around.contains(m)) { + if moving.is_empty() || moving.iter().any(|m| around.contains(m) && !(beside_itself && *m == n.id)) { return; } let Some(p) = ui.input(|i| i.pointer.hover_pos()) else { return }; let rel = (p.y - r.top()) / r.height().max(1.0); let inside = takes(n, &drag, &moving, doc); let place = match &*drag { + LayersDrag::Rows(_) if beside_itself && rel < 0.5 => Place::Above, + LayersDrag::Rows(_) if beside_itself => Place::Below, LayersDrag::Art if inside => Place::Inside, LayersDrag::Art => Place::Above, LayersDrag::Rows(_) if inside && rel >= 0.25 && (rel <= 0.75 || open) => Place::Inside, diff --git a/crates/ui-egui/src/panels/layers/tests.rs b/crates/ui-egui/src/panels/layers/tests.rs index 2570e77df7..1f03ee5d86 100644 --- a/crates/ui-egui/src/panels/layers/tests.rs +++ b/crates/ui-egui/src/panels/layers/tests.rs @@ -1462,6 +1462,57 @@ fn dragging_a_layer_into_the_empty_space_under_the_rows_moves_it_to_the_bottom() assert_eq!(ids(&app), vec![top, bottom], "the top layer is now the bottom one"); } +/// #8237: with Alt, the top layer dropped on the top edge of its own row copies above itself, and +/// the bottom layer dropped in the empty space under the list copies below itself. Without Alt, +/// neither drop changes anything. +#[test] +fn alt_dragging_the_top_layer_up_or_the_bottom_layer_down_copies_it() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + app.session.execute("layer.new", &json!({"top": true})).unwrap(); + let ids = |app: &VectorcraftApp| app.session.active().unwrap().doc.layers.iter().map(|l| l.id).collect::>(); + let [bottom, top] = ids(&app)[..] else { panic!("two layers") }; + let ctx = egui::Context::default(); + // Rows: the top layer, the bottom layer, then empty space. + let (circles, _) = frame(&mut app, &ctx, vec![], false); + assert_eq!(circles.len(), 2); + let row = |y: f32| egui::pos2(150.0, y); + let top_edge = |y: f32| egui::pos2(150.0, y - ROW_MEDIUM * 0.4); + let under = |y: f32| egui::pos2(150.0, y + 3.0 * ROW_MEDIUM); + drag(&mut app, &ctx, row(circles[0].y), top_edge(circles[0].y), false); + drag(&mut app, &ctx, row(circles[1].y), under(circles[1].y), false); + assert_eq!(ids(&app), vec![bottom, top], "moved onto their own places, nothing changes"); + drag(&mut app, &ctx, row(circles[0].y), top_edge(circles[0].y), true); + let after = ids(&app); + assert_eq!((after.len(), &after[..2]), (3, &[bottom, top][..]), "a copy above the top layer"); + // Rows: the copy, the top layer, the bottom layer, then empty space. + let (circles, _) = frame(&mut app, &ctx, vec![], false); + assert_eq!(circles.len(), 3); + drag(&mut app, &ctx, row(circles[2].y), under(circles[2].y), true); + let after = ids(&app); + assert_eq!((after.len(), after[1]), (4, bottom), "a copy below the bottom layer"); +} + +/// #8237: a document's only layer, Alt-dragged up onto its own row or down into the empty space, +/// is copied above or below itself. +#[test] +fn a_lone_layer_alt_dragged_up_or_down_is_copied() { + for (up, at) in [(true, 0), (false, 1)] { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let ids = |app: &VectorcraftApp| app.session.active().unwrap().doc.layers.iter().map(|l| l.id).collect::>(); + let [only] = ids(&app)[..] else { panic!("one layer") }; + let ctx = egui::Context::default(); + let (circles, _) = frame(&mut app, &ctx, vec![], false); + assert_eq!(circles.len(), 1); + let y = circles[0].y; + let to = if up { y - ROW_MEDIUM * 0.4 } else { y + 3.0 * ROW_MEDIUM }; + drag(&mut app, &ctx, egui::pos2(150.0, y), egui::pos2(150.0, to), true); + let after = ids(&app); + assert_eq!((after.len(), after[at]), (2, only), "up: {up}"); + } +} + #[test] fn dragging_rows_moves_them_into_other_layers_and_alt_copies() { let (mut app, [layer, sub, g, _, a, c]) = nested(); @@ -2133,6 +2184,97 @@ fn the_panel_menu_lists_every_operation() { } } +/// With Show Layers Only on, Locate Object becomes Locate Layer in the panel menu and a row's +/// menu, and the bottom bar's Locate button highlights the sublayer holding the selected art, +/// opening the layer around it. Off, the button highlights the art's own row. +#[test] +fn with_show_layers_only_locate_object_becomes_locate_layer() { + let (mut app, [layer, sub, _, b, _, _]) = nested(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let shown = |app: &mut VectorcraftApp, events: Vec, f: fn(&mut VectorcraftApp, &mut egui::Ui)| { + super::super::tests_appearance::frame_events(&ctx, app, events, f).into_iter().map(|(t, _)| t.trim().to_string()).collect::>() + }; + let has = |texts: &[String], s: &str| texts.iter().any(|t| t == s); + app.session.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + let off = shown(&mut app, vec![], menu); + assert!(has(&off, "Locate Object") && !has(&off, "Locate Layer"), "{off:?}"); + let locate = |app: &mut VectorcraftApp| { + let at = bar_buttons(app, &ctx)[4]; + click_with(app, &ctx, at, egui::Modifiers::NONE); + }; + locate(&mut app); + assert_eq!(rows_of(&app), vec![b], "off: the art's own row"); + + app.ui.layers_panel.layers_only = true; + let on = shown(&mut app, vec![], menu); + assert!(has(&on, "Locate Layer") && !has(&on, "Locate Object"), "{on:?}"); + app.session.active_mut().unwrap().layers_open.set(layer, false); + shown(&mut app, vec![], show); + locate(&mut app); + assert_eq!(rows_of(&app), vec![sub], "on: the sublayer holding the art"); + shown(&mut app, vec![], show); + assert!(app.session.active().unwrap().layers_open.contains(layer), "the layer around the sublayer opens"); + assert!(has(&shown(&mut app, vec![], show), "Sub"), "the sublayer's row shows"); + + // A row's menu says Locate Layer too. + let c = frame(&mut app, &ctx, vec![], false).0; + let at = egui::pos2(150.0, c[0].y); + let right = egui::PointerButton::Secondary; + for e in [egui::Event::PointerMoved(at), button_by(at, true, right), button_by(at, false, right)] { + frame(&mut app, &ctx, vec![e], false); + } + let row_menu = shown(&mut app, vec![], show); + assert!(has(&row_menu, "Locate Layer") && !has(&row_menu, "Locate Object"), "{row_menu:?}"); +} + +/// Locate Layer or Locate Object run again on the row it already highlighted reveals that row +/// again: the layers around it that were closed since open, once per Locate. +#[test] +fn a_repeated_locate_reveals_the_row_it_already_highlighted() { + let (mut app, [layer, sub, g, b, _, _]) = nested(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let draw = |app: &mut VectorcraftApp| { + super::super::tests_appearance::frame_events(&ctx, app, vec![], show).into_iter().map(|(t, _)| t.trim().to_string()).collect::>() + }; + let open = |app: &VectorcraftApp, id: NodeId| app.session.active().unwrap().layers_open.contains(id); + let close = |app: &mut VectorcraftApp, ids: &[NodeId]| { + for id in ids { + app.session.active_mut().unwrap().layers_open.set(*id, false); + } + }; + app.session.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + + // Locate Layer: the sublayer stays highlighted while its layer is closed, and Locate Layer again opens it. + app.ui.layers_panel.layers_only = true; + app.session.execute("layer.locate", &json!({"layersOnly": true})).unwrap(); + draw(&mut app); + assert_eq!(rows_of(&app), vec![sub]); + close(&mut app, &[layer]); + assert!(!draw(&mut app).iter().any(|t| t == "Sub"), "the closed layer hides the sublayer"); + app.session.execute("layer.locate", &json!({"layersOnly": true})).unwrap(); + assert!(draw(&mut app).iter().any(|t| t == "Sub"), "the sublayer's row shows again"); + assert!(open(&app, layer), "the layer around the sublayer opens again"); + assert_eq!(rows_of(&app), vec![sub]); + // Once per Locate: a later frame leaves a layer closed after that alone. + close(&mut app, &[layer]); + draw(&mut app); + assert!(!open(&app, layer), "a frame without a Locate opens nothing"); + + // Locate Object: the same for the object's row inside a closed sublayer and group. + app.ui.layers_panel.layers_only = false; + app.session.execute("layer.locate", &json!({})).unwrap(); + draw(&mut app); + assert_eq!(rows_of(&app), vec![b]); + close(&mut app, &[sub, g]); + draw(&mut app); + app.session.execute("layer.locate", &json!({})).unwrap(); + draw(&mut app); + assert!(open(&app, layer) && open(&app, sub) && open(&app, g), "the layers and group around the object open again"); + assert_eq!(rows_of(&app), vec![b]); +} + /// ≡ › Save Selection lists the saved selections: choosing one recalls it, Update Selection /// makes it hold the selected objects, and Save Selection… opens the name dialog. #[test] diff --git a/crates/ui-egui/src/panels/links.rs b/crates/ui-egui/src/panels/links.rs index 3b45e450d4..cf68e1d5bd 100644 --- a/crates/ui-egui/src/panels/links.rs +++ b/crates/ui-egui/src/panels/links.rs @@ -54,7 +54,7 @@ impl Default for Options { /// `links.list` and the first selected image's `links.info`, with what they were fetched for. #[derive(Clone, Default)] -struct Cache { +pub(super) struct Cache { /// (document uid, revision, show, sort, Show DCS Transparency Interactions). key: Option<(u64, u64, &'static str, Option<&'static str>, bool)>, at: f64, @@ -83,23 +83,23 @@ fn set_options(ctx: &egui::Context, f: impl FnOnce(&mut Options)) { } /// The rows to show (cached per document revision, the files looked at again every [`RECHECK`] -/// seconds) and the Link Info of the first selected image when the section is open. -fn cached(app: &mut VectorcraftApp, ctx: &egui::Context, o: &Options) -> Option { +/// seconds) and the Link Info of the first selected image when the section is open. A frame that +/// fetches nothing returns the stored cache without copying it and stores nothing. +fn cached(app: &mut VectorcraftApp, ctx: &egui::Context, o: &Options) -> Option> { let st = app.session.active()?; let key = Some((st.uid, st.revision, o.show, o.sort, o.dcs)); let first = selected_links(app, ctx).first().copied(); let now = ctx.input(|i| i.time); - let mut c: Cache = pstate(ctx, "links-cache"); + let mut c: std::sync::Arc = pstate(ctx, "links-cache"); let stale = c.key != key || now - c.at > RECHECK; if stale { let same_doc = c.key == key; - c.list = app.session.execute("links.list", &json!({ "show": o.show, "sort": o.sort, "dcsTransparency": o.dcs })).ok()?; - (c.key, c.at) = (key, now); + let list = app.session.execute("links.list", &json!({ "show": o.show, "sort": o.sort, "dcsTransparency": o.dcs })).ok()?; // One pass over the stored art for the rows outside the layer tree and the objects whose // opacity masks hold them, not one per frame. An object in the layer tree is looked up by // its index when drawn. let doc = app.session.active().map(|st| &st.doc); - let want: std::collections::HashSet = c.list["links"] + let want: std::collections::HashSet = list["links"] .as_array() .into_iter() .flatten() @@ -110,18 +110,22 @@ fn cached(app: &mut VectorcraftApp, ctx: &egui::Context, o: &Options) -> Option< .collect(); // The same revision keeps the objects collected for it, so their thumbnails are not drawn // again each time the files are looked at. - if !(same_doc && want.iter().all(|id| c.nested_node(*id).is_some())) { - c.nested = match doc { + let nested = if same_doc && want.iter().all(|id| c.nested_node(*id).is_some()) { + c.nested.clone() + } else { + match doc { Some(d) if !want.is_empty() => stored_objects(d, want), _ => vec![], - }; - } + } + }; + c = std::sync::Arc::new(Cache { key, at: now, list, info: None, nested }); } let want = first.filter(|_| o.info); if stale || c.info.as_ref().map(|(id, _)| *id) != want { - c.info = want.and_then(|id| Some((id, app.session.execute("links.info", &json!({ "id": id })).ok()?))); + let info = want.and_then(|id| Some((id, app.session.execute("links.info", &json!({ "id": id })).ok()?))); + std::sync::Arc::make_mut(&mut c).info = info; + set_pstate(ctx, "links-cache", c.clone()); } - set_pstate(ctx, "links-cache", c.clone()); // Files change on disk without a frame of ours: look again later. ctx.request_repaint_after(std::time::Duration::from_secs_f64(RECHECK)); Some(c) @@ -819,9 +823,10 @@ fn link_info(ui: &mut Ui, info: Option<&Value>, units: vectorcraft_doc::Unit) { pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { let o = options(ui.ctx()); // The rows the panel shows (the menu opens from it). - let list = pstate::(ui.ctx(), "links-cache").list; + let cache = pstate::>(ui.ctx(), "links-cache"); + let list = &cache.list; let selected = selected_links(app, ui.ctx()); - let sel = selected_rows(&list, &selected); + let sel = selected_rows(list, &selected); let linked = ids(&sel, |r| r["linked"] == true); let embedded: Vec<&Value> = sel.iter().copied().filter(|r| status_is(r, "embedded")).collect(); let any = !sel.is_empty(); diff --git a/crates/ui-egui/src/panels/opentype.rs b/crates/ui-egui/src/panels/opentype.rs index fe144edbf9..4cfcb27e89 100644 --- a/crates/ui-egui/src/panels/opentype.rs +++ b/crates/ui-egui/src/panels/opentype.rs @@ -1,7 +1,7 @@ //! OpenType panel: per-character OpenType features (ligatures, alternates, swashes, small caps, -//! ordinals, fractions, figure style, position, and with the East Asian options the menu's H or V -//! Style and Roman Italics) for the selected text (every frame of each selected threaded story) or -//! the Type tool's selected characters. +//! ordinals, fractions, figure style, position, stylistic sets from the panel or its menu, and with +//! the East Asian options the menu's H or V Style and Roman Italics) for the selected text (every +//! frame of each selected threaded story) or the Type tool's selected characters. use egui::Ui; use serde_json::json; @@ -257,18 +257,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { change = Some(Change::Toggle(flag, shown != Some(true))); } } - // The font, not the text, decides which numbered sets can be offered. Each set is an - // independent feature, so the menu permits several at once. A font's own label wins over - // the numbered fallback. See the public Stylistic Sets help page. A set is checked when every - // character has it. - let sets: Vec<(StylisticSet, Flag, bool)> = offered_sets(&st) - .into_iter() - .map(|set| { - let flag = Flag::Extra(EXTRA_FEATURES[usize::from(set.number - 1)]); - let on = shown_flag(app, flag) == Some(true); - (set, flag, on) - }) - .collect(); + let sets = set_entries(app, &st); ui.add_enabled_ui(!sets.is_empty(), |ui| { ui.menu_button(tl!("Stylistic Sets"), |ui| { widgets::menu_scroll(ui, |ui| { @@ -300,6 +289,22 @@ fn tracking_drops_ligatures(app: &VectorcraftApp) -> bool { }) } +/// The Stylistic Sets entries of the panel's button and of the panel menu's submenu: each set the +/// font `st` names offers, the feature it turns on and off, and whether it is checked. The font, +/// not the text, decides which numbered sets can be offered. Each set is an independent feature, +/// so the menu permits several at once. A font's own label wins over the numbered fallback. See +/// the public Stylistic Sets help page. A set is checked when every character has it. +fn set_entries(app: &VectorcraftApp, st: &CharStyle) -> Vec<(StylisticSet, Flag, bool)> { + offered_sets(st) + .into_iter() + .map(|set| { + let flag = Flag::Extra(EXTRA_FEATURES[usize::from(set.number - 1)]); + let on = shown_flag(app, flag) == Some(true); + (set, flag, on) + }) + .collect() +} + /// The stylistic sets of the font `st` names. A font that is not available offers none, rather than /// the sets of the face drawn in its place. fn offered_sets(st: &vectorcraft_doc::CharStyle) -> Vec { @@ -345,10 +350,31 @@ fn east_asian_items() -> [Toggle; 2] { } pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { - let has = text_style(app).is_some(); + let style = text_style(app); + let has = style.is_some(); if menu_item(ui, tl!("Reset OpenType Features"), has, false) { set(app, OtFeatures::default()); } + // Stylistic Sets: the sets, labels and checks of the panel's Stylistic Sets button. A set chosen + // while only some characters have it turns it on for all of them. Disabled with no text or when + // the font offers no sets. + let sets = style.map(|(st, _)| set_entries(app, &st)).unwrap_or_default(); + let mut toggle = None; + ui.add_enabled_ui(!sets.is_empty(), |ui| { + // Indented like the items beside it (their check column). + ui.menu_button(format!(" {}", tl!("Stylistic Sets")), |ui| { + widgets::menu_scroll(ui, |ui| { + for (set, flag, on) in &sets { + if widgets::menu_item_name(ui, &set_label(set), true, *on) { + toggle = Some(Change::Toggle(*flag, !on)); + } + } + }); + }); + }); + if let Some(c) = toggle { + edit(app, c); + } if app.session.prefs.show_east_asian_options { ui.separator(); // Checked when every character it changes has it; chosen then, it turns it off. @@ -767,6 +793,48 @@ mod tests { assert_eq!(undo_steps(&app), undo + 1); } + /// The panel menu's Stylistic Sets submenu lists the font's sets with the labels of the panel's + /// Stylistic Sets button. Chosen, a set turns on for the selected type in one undo step and + /// shows checked, keeping the other features; chosen again, it turns off. With no text + /// selected the submenu is disabled and does not open. + #[test] + fn the_panel_menu_stylistic_sets_submenu_turns_sets_on_and_off() { + let mut app = selected_text(); + let Some((st, _)) = text_style(&app) else { panic!("no text style") }; + let sets = set_entries(&app, &st); + // Builds without the bundled fonts have no face that offers sets. + let Some((first, _, _)) = sets.first() else { return }; + let (label, tag) = (set_label(first), EXTRA_FEATURES[usize::from(first.number - 1)]); + set(&mut app, OtFeatures { small_caps: true, ..Default::default() }); + let entry = |t: &str| t.trim_start_matches(['✓', ' ']).to_string(); + // Opens the submenu in a fresh context and returns the drawn text of `label`'s entry and + // its rect, if the submenu shows it. + let open = |app: &mut VectorcraftApp, ctx: &egui::Context| { + crate::theme::install_fonts(ctx); + let texts = super::super::tests_appearance::frame_events(ctx, app, vec![], menu); + let sub = super::super::tests_appearance::text_rect(&texts, " Stylistic Sets"); + super::super::tests_appearance::click(ctx, app, sub.center(), menu); + let texts = super::super::tests_appearance::frame_events(ctx, app, vec![], menu); + texts.into_iter().find(|(t, _)| entry(t) == label && t != " Stylistic Sets") + }; + let ctx = egui::Context::default(); + let Some((text, at)) = open(&mut app, &ctx) else { panic!("{label} missing from the submenu") }; + assert!(!text.starts_with('✓'), "{text:?}"); + let undo = undo_steps(&app); + super::super::tests_appearance::click(&ctx, &mut app, at.center(), menu); + assert_eq!(undo_steps(&app), undo + 1); + let on = text_style(&app).unwrap().0.features; + assert!(on.iter().any(|f| f == tag) && on.iter().any(|f| f == "smcp"), "{on:?}"); + let ctx = egui::Context::default(); + let Some((text, at)) = open(&mut app, &ctx) else { panic!("{label} missing from the reopened submenu") }; + assert!(text.starts_with('✓'), "{text:?}"); + super::super::tests_appearance::click(&ctx, &mut app, at.center(), menu); + assert_eq!(text_style(&app).unwrap().0.features, ["smcp"]); + app.session.execute("select.set", &json!({"ids": []})).unwrap(); + let ctx = egui::Context::default(); + assert!(open(&mut app, &ctx).is_none(), "the submenu opened with no text selected"); + } + /// H or V Style and Roman Italics are in the panel menu with the East Asian options only. #[test] fn kana_style_and_roman_italics_show_with_the_east_asian_options() { diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index a98ad34aa7..02870c371f 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -985,7 +985,7 @@ fn width_profile_row(app: &mut VectorcraftApp, ui: &mut Ui) { } ui.horizontal(|ui| { dim_label(ui, tl!("Profile:")); - if let Some(id) = super::stroke::profile_dropdown(app, ui, profile) { + if let Some(id) = super::stroke::profile_dropdown(app, ui, stroke.as_ref()) { app.run("stroke.set", json!({"profile": id})).ok(); } }); diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index c91d01a2bf..613eb73793 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -1515,6 +1515,26 @@ fn the_width_profile_shows_for_a_variable_width_or_the_width_tool() { assert_eq!(WidthProfile::id_of(profile.as_ref()), "taperStart"); } +/// A brushed stroke with a variable width: the Width Profile list lists only Uniform, which removes +/// the profile. +#[test] +fn the_width_profile_of_a_brushed_stroke_offers_only_uniform() { + let mut app = new_app(); + let line = app.run("shape.line", json!({"x1": 20, "y1": 100, "x2": 300, "y2": 100})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [line]})).unwrap(); + app.run("stroke.set", json!({"profile": "lens"})).unwrap(); + app.run("brush.apply", json!({"ids": [line], "name": "3 pt. Round"})).unwrap(); + let ctx = egui::Context::default(); + let texts = tall(&mut app, &ctx, vec![]); + let spacing = ctx.global_style().spacing.item_spacing.x; + let texts = press(&mut app, &ctx, text_at(&texts, "Profile:").right_center() + vec2(spacing + 50.0, 0.0)); + assert!(!shows(&texts, "Taper Start"), "{texts:?}"); + press(&mut app, &ctx, text_at(&texts, "Uniform").center()); + let profile = + app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(line.as_u64().unwrap())).unwrap().appearance.stroke().unwrap().profile.clone(); + assert_eq!(profile, None); +} + /// With Direct Selection, a path whose corner is selected shows that corner's kind and radius; /// each edit sets that corner alone in one undo step. Not with the Selection tool, nor with the /// whole path selected; a live rectangle keeps its own Corner Radius row instead. diff --git a/crates/ui-egui/src/panels/separations.rs b/crates/ui-egui/src/panels/separations.rs index bdb4210920..2b3e112c5f 100644 --- a/crates/ui-egui/src/panels/separations.rs +++ b/crates/ui-egui/src/panels/separations.rs @@ -1,5 +1,6 @@ //! Separations Preview panel: process plates C/M/Y/K plus spot plates with eye toggles (one visible -//! plate renders as greyscale ink coverage; Alt-click an eye to show only that plate), and the +//! plate renders as grayscale ink coverage; Alt-click an eye to show only that plate, and Alt-click +//! the eye of the plate shown alone to show every plate), and the //! colour-management controls behind Edit → Color Settings… / Assign Profile… and View → Proof //! Setup (working spaces, color management policies, intent, black-point compensation, proof //! target, gamut check). @@ -59,11 +60,11 @@ fn plates_section(app: &mut VectorcraftApp, ui: &mut Ui) { let vis = visible(&p.name); let mut clicked = false; ui.add_enabled_ui(on, |ui| { - clicked = widgets::toggle_icon(ui, "eye", vis, 18.0, tl!("Show/hide plate (Alt-click: only this plate)")); + clicked = + widgets::toggle_icon(ui, "eye", vis, 18.0, tl!("Show/hide plate (Alt-click: only this plate; Alt-click again: all plates)")); }); if clicked && on { - let key = if alt { "only" } else { "toggle" }; - run(app, "view.separationsPreview", json!({ key: p.name })); + run(app, "view.separationsPreview", eye_click(&p.name, alt)); } let (r, _) = ui.allocate_exact_size(vec2(14.0, 14.0), Sense::hover()); let q = |x: f32| (x.clamp(0.0, 1.0) * 255.0).round() as u8; @@ -75,6 +76,12 @@ fn plates_section(app: &mut VectorcraftApp, ui: &mut Ui) { }); } +/// The `view.separationsPreview` params for a click on plate `name`'s eye: with Alt, that plate +/// alone, or every plate when it already shows alone; without, the plate shown or hidden. +fn eye_click(name: &str, alt: bool) -> Value { + if alt { json!({"soloToggle": name}) } else { json!({"toggle": name}) } +} + /// A dropdown of the `kind` profiles after `extra` (a built-in entry, shown in the UI language); /// profile names are shown as they are. Returns the chosen name. pub(crate) fn profile_dropdown(ui: &mut Ui, id: &str, current: &str, kind: ProfileKind, extra: Option<&str>) -> Option { @@ -345,6 +352,16 @@ mod tests { assert!(panel.iter().all(|(id, _)| cms::ProofTarget::parse(id).is_some_and(|t| t.id() == *id))); } + /// An Alt-click on a plate's eye sends `soloToggle`, which `view.separationsPreview` takes, and + /// a plain click sends `toggle`. + #[test] + fn an_alt_click_on_a_plates_eye_sends_solo_toggle() { + assert_eq!(eye_click("Cyan", true), json!({"soloToggle": "Cyan"})); + assert_eq!(eye_click("Brand Orange", false), json!({"toggle": "Brand Orange"})); + let spec = vectorcraft_engine::cmd::command_specs().iter().find(|c| c.id == "view.separationsPreview"); + assert!(spec.is_some_and(|c| c.params.contains("soloToggle?:"))); + } + /// Assign Profile's three choices: no profile, the working space assigned as the profile, or /// another profile; a choice the document already has runs nothing. #[test] diff --git a/crates/ui-egui/src/panels/stroke.rs b/crates/ui-egui/src/panels/stroke.rs index 3b48f45e91..33faeec41e 100644 --- a/crates/ui-egui/src/panels/stroke.rs +++ b/crates/ui-egui/src/panels/stroke.rs @@ -355,10 +355,10 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { // Profile. ui.horizontal(|ui| { row_label(ui, tl!("Profile:")); - if let Some(id) = profile_dropdown(app, ui, st.as_ref().and_then(|s| s.profile.as_ref())) { + if let Some(id) = profile_dropdown(app, ui, st.as_ref()) { set(app, json!({"profile": id})); } - let can_flip = st.as_ref().is_some_and(|s| s.profile.is_some()); + let can_flip = st.as_ref().is_some_and(|s| s.profile.is_some()) && brush_keeps_size(app, ui.ctx(), st.as_ref()).is_none(); // Lucide names these icons for their mirror line: the vertical-line icon flips the // profile along the path, while the horizontal-line icon flips it across the path. if widgets::icon_button_enabled(ui, "flip-vertical-2", tl!("Flip Along"), false, can_flip, 22.0).clicked() { @@ -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); } @@ -498,24 +498,66 @@ pub fn paint_profile(ui: &Ui, r: Rect, points: Option<&[(f64, f64, f64)]>, color /// The width of the [`profile_dropdown`] button. pub(crate) const PROFILE_DROPDOWN_WIDTH: f32 = 100.0; -/// The Profile dropdown (Stroke panel, Control bar): the stroke's own silhouette on the button -/// (a custom profile too), the built-in profiles and then the saved ones in the list. Returns the -/// id or name picked. -pub(crate) fn profile_dropdown(app: &VectorcraftApp, ui: &mut Ui, cur: Option<&WidthProfile>) -> Option { +/// While a width profile changes none of the strokes the Profile list edits, because each draws +/// with a brush: whether any of them has a profile. None while a profile changes one of them. +/// With nothing selected the list sets up the next object drawn, whose stroke is `shown` (the +/// stroke the panels show). Otherwise it edits the strokes `stroke.set` targets +/// ([`vectorcraft_engine::Session::brushed_strokes_profiled`], cached per document revision and +/// active Appearance row), such as a selected group's own stroke while `shown` is its first +/// member's. +pub(crate) fn brush_keeps_size(app: &VectorcraftApp, ctx: &egui::Context, shown: Option<&StrokeLayer>) -> Option { + let st = app.session.active()?; + if st.selection.objects.is_empty() && st.selection.subjects().is_empty() { + let s = shown?; + let name = s.brush.as_deref()?; + return super::brushes::document_brushes(st).iter().any(|b| b.name == name).then_some(s.profile.is_some()); + } + let key = (st.uid, st.revision, app.session.appearance_item()); + match pstate::), Option)>>(ctx, "stroke-brushed") { + Some((k, v)) if k == key => v, + _ => { + let v = app.session.brushed_strokes_profiled(); + set_pstate(ctx, "stroke-brushed", Some((key, v))); + v + } + } +} + +/// The Profile dropdown (Stroke panel, Properties panel, Control bar): the stroke's own silhouette +/// on the button (a custom profile too), the built-in profiles and then the saved ones in the list. +/// Returns the id or name picked. While the strokes draw with a brush ([`brush_keeps_size`]), the +/// button is dimmed and says why when hovered; it opens no list while every one is uniform, and +/// only the Uniform row, which removes the profiles, while one has a profile. +pub(crate) fn profile_dropdown(app: &VectorcraftApp, ui: &mut Ui, shown: Option<&StrokeLayer>) -> Option { let t = Tokens::get(ui.ctx()); - let (r, resp) = ui.allocate_exact_size(vec2(PROFILE_DROPDOWN_WIDTH, 24.0), Sense::click()); + let cur = shown.and_then(|s| s.profile.as_ref()); + let brushed = brush_keeps_size(app, ui.ctx(), shown); + let keeps_size = brushed.is_some(); + let uniform = brushed == Some(false); + let sense = if uniform { Sense::hover() } else { Sense::click() }; + let (r, resp) = ui.allocate_exact_size(vec2(PROFILE_DROPDOWN_WIDTH, 24.0), sense); ui.painter().rect_filled(r, 2, t.input); - ui.painter().rect_stroke(r, 2, Stroke::new(1.0, if resp.hovered() { t.text } else { t.input_border }), StrokeKind::Inside); + let border = if resp.hovered() && !uniform { t.text } else { t.input_border }; + ui.painter().rect_stroke(r, 2, Stroke::new(1.0, border), StrokeKind::Inside); let body = Rect::from_min_max(r.min + vec2(6.0, 5.0), pos2(r.right() - 20.0, r.bottom() - 5.0)); - paint_profile(ui, body, cur.and_then(|p| silhouette(&p.points)), t.text_strong); - icons::paint(ui, "chevron-down", Rect::from_center_size(pos2(r.right() - 9.0, r.center().y), vec2(10.0, 10.0)), t.icon); - let resp = resp.on_hover_text(tl!("Variable Width Profile")); + let (shape, icon) = if keeps_size { (t.text_disabled, t.text_disabled) } else { (t.text_strong, t.icon) }; + paint_profile(ui, body, cur.and_then(|p| silhouette(&p.points)), shape); + icons::paint(ui, "chevron-down", Rect::from_center_size(pos2(r.right() - 9.0, r.center().y), vec2(10.0, 10.0)), icon); + let tip = if keeps_size { + tl!("The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile.") + } else { + tl!("Variable Width Profile") + }; + let resp = resp.on_hover_text(tip); + if uniform { + return None; + } let mut out = None; egui::Popup::menu(&resp).show(|ui| { egui::ScrollArea::vertical().max_height(360.0).show(ui, |ui| { // A divider between the built-in profiles and the saved ones. let mut divide = true; - for e in app.session.profile_entries() { + for e in app.session.profile_entries().filter(|e| !keeps_size || e.matches(None)) { if !e.built_in && std::mem::take(&mut divide) { ui.separator(); } diff --git a/crates/ui-egui/src/panels/swatches/actions.rs b/crates/ui-egui/src/panels/swatches/actions.rs index 1779f9dfa6..8850b2ed6c 100644 --- a/crates/ui-egui/src/panels/swatches/actions.rs +++ b/crates/ui-egui/src/panels/swatches/actions.rs @@ -5,16 +5,19 @@ use super::{ widgets, }; -/// The selected swatches and groups that can be deleted (all but None and Registration). -pub(super) fn deletable(sel: &[String]) -> Vec { - sel.iter().filter(|n| !n.starts_with('[')).cloned().collect() +/// The selected swatches and groups that can be deleted: every color group in the document and +/// every swatch that `Swatch::is_reserved` does not reserve (None and Registration). Names the +/// document does not hold are left out. +pub(super) fn deletable(app: &VectorcraftApp, sel: &[String]) -> Vec { + let Some(d) = app.session.active().map(|st| &st.doc) else { return vec![] }; + sel.iter().filter(|n| d.swatch(n).map_or_else(|| d.swatch_groups.iter().any(|g| g.name == **n), |w| !w.is_reserved())).cloned().collect() } /// The selected swatch when exactly one swatch with an editor is selected (not None, Registration /// or a group). -fn editable(app: &VectorcraftApp, sel: &[String]) -> Option { +pub(super) fn editable(app: &VectorcraftApp, sel: &[String]) -> Option { match sel { - [n] if !n.starts_with('[') && app.session.active().is_some_and(|st| st.doc.swatch(n).is_some()) => Some(n.clone()), + [n] if app.session.active().and_then(|st| st.doc.swatch(n)).is_some_and(|w| !w.is_reserved()) => Some(n.clone()), _ => None, } } @@ -80,7 +83,7 @@ pub(super) fn bottom(app: &mut VectorcraftApp, ui: &mut Ui, sel: &[String]) { } ui.add_space((ui.available_width() - 3.0 * 28.0).max(0.0)); if widgets::icon_button(ui, "dc-folder", tl!("New Color Group"), false, 24.0).clicked() { - app.run("ui.newColorGroup", json!({"swatches": deletable(sel)})).ok(); + app.run("ui.newColorGroup", json!({"swatches": deletable(app, sel)})).ok(); } // Alt-click skips the dialog; Ctrl/Cmd-click makes a spot color, and Ctrl/Cmd+Shift-click // makes a global process color. @@ -89,7 +92,7 @@ pub(super) fn bottom(app: &mut VectorcraftApp, ui: &mut Ui, sel: &[String]) { } // Alt-click deletes without asking. Swatches or color groups dragged from the list can be // dropped on it, also with nothing selected: the button is enabled while they are held. - let del = deletable(sel); + let del = deletable(app, sel); let dragged = dragged_deletable(app, ui.ctx()); let trash = widgets::icon_button_enabled(ui, "trash-2", tl!("Delete Swatch"), false, !del.is_empty() || !dragged.is_empty(), 24.0); if trash.clicked() && !del.is_empty() { @@ -111,7 +114,7 @@ fn dragged_deletable(app: &VectorcraftApp, ctx: &egui::Context) -> Vec { return vec![]; } match egui::DragAndDrop::payload::(ctx).as_deref() { - Some(PanelDrag::Paint { rows: Some(r), .. }) => deletable(&r.names).into_iter().filter(|n| st.doc.swatch_name_taken(n)).collect(), + Some(PanelDrag::Paint { rows: Some(r), .. }) => deletable(app, &r.names).into_iter().filter(|n| st.doc.swatch_name_taken(n)).collect(), _ => vec![], } } @@ -164,7 +167,7 @@ pub(super) fn new_swatch(app: &mut VectorcraftApp, sel: &[String], m: egui::Modi pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { let view = app.ui.swatches_view; let selected = selection(app, ui); - let del = deletable(&selected); + let del = deletable(app, &selected); let opts = editable(app, &selected); if menu_item(ui, tl!("New Swatch…"), true, false) { new_swatch(app, &selected, egui::Modifiers::NONE); @@ -239,6 +242,6 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { ui.separator(); ui.menu_button(tl!("Open Swatch Library"), |ui| library_panel::library_menu::(app, ui)); if menu_item(ui, tl!("Save Swatch Library…"), true, false) { - app.run("ui.saveSwatchLibrary", json!({ "names": deletable(&selected) })).ok(); + app.run("ui.saveSwatchLibrary", json!({ "names": deletable(app, &selected) })).ok(); } } diff --git a/crates/ui-egui/src/panels/swatches/dnd.rs b/crates/ui-egui/src/panels/swatches/dnd.rs index ea3282db68..d8cd2534ab 100644 --- a/crates/ui-egui/src/panels/swatches/dnd.rs +++ b/crates/ui-egui/src/panels/swatches/dnd.rs @@ -308,7 +308,8 @@ pub(crate) fn drag_preview(app: &VectorcraftApp, ctx: &egui::Context) { None => return, }, PanelDrag::GraphicStyle(name) => return pointer_chip(ctx, |ui, r| crate::panels::graphic_styles::paint_style(app, ui, r, name)), - PanelDrag::Symbol(name) => match app.session.active() { + // Drawn from the document it was dragged from, whichever document is active now. + PanelDrag::Symbol { document, name } => match app.session.documents().iter().find(|st| st.uid == *document) { Some(st) => { return pointer_chip(ctx, |ui, r| crate::panels::symbols::chip(ui, &st.doc, &crate::panels::symbols::document_symbols(st), r, name)); } diff --git a/crates/ui-egui/src/panels/swatches/libraries.rs b/crates/ui-egui/src/panels/swatches/libraries.rs index d5722e6354..183231971c 100644 --- a/crates/ui-egui/src/panels/swatches/libraries.rs +++ b/crates/ui-egui/src/panels/swatches/libraries.rs @@ -142,7 +142,7 @@ impl LibraryKind for SwatchLibraries { app.status(e); } if menu_item(ui, tl!("Save Swatch Library…"), app.session.active().is_some(), false) { - let names = deletable(&selection(app, ui)); + let names = deletable(app, &selection(app, ui)); app.run("ui.saveSwatchLibrary", json!({ "names": names })).ok(); } } diff --git a/crates/ui-egui/src/panels/swatches/tests.rs b/crates/ui-egui/src/panels/swatches/tests.rs index a67e604f2b..20c57ac769 100644 --- a/crates/ui-egui/src/panels/swatches/tests.rs +++ b/crates/ui-egui/src/panels/swatches/tests.rs @@ -281,7 +281,27 @@ fn delete_asks_then_removes_the_selection_and_unlinks_art() { assert!(app.session.doc().unwrap().doc.swatch("Orange").is_some()); delete(&mut app, vec!["Orange".into()], true); assert!(app.ui.dialog.is_none() && app.session.doc().unwrap().doc.swatch("Orange").is_none()); - assert_eq!(deletable(&["[None]".into(), REGISTRATION.into(), "Grays".into()]), ["Grays"]); + assert_eq!(deletable(&app, &["[None]".into(), REGISTRATION.into(), "Grays".into()]), ["Grays"]); +} + +/// Only None and Registration are reserved: a user swatch or color group whose name starts with +/// `[` can be deleted, the swatch can be edited, and names the document does not hold are left out. +#[test] +fn bracketed_user_swatches_and_groups_can_be_deleted_and_edited() { + let mut app = app(); + app.run("swatch.new", json!({"name": "[Mine]", "color": "#336699"})).unwrap(); + app.run("swatch.newGroup", json!({"name": "[Team]", "colors": ["#ff0000"]})).unwrap(); + let names = |v: &[&str]| v.iter().map(|n| n.to_string()).collect::>(); + assert_eq!(deletable(&app, &names(&["[None]", REGISTRATION, "[Mine]", "[Team]", "Gone"])), ["[Mine]", "[Team]"]); + assert_eq!(actions::editable(&app, &names(&["[Mine]"])).as_deref(), Some("[Mine]")); + for name in ["[None]", REGISTRATION, "[Team]", "Gone"] { + assert_eq!(actions::editable(&app, &names(&[name])), None, "{name}"); + } + let doomed = deletable(&app, &names(&["[Mine]"])); + delete(&mut app, doomed, false); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.str("message")).as_deref(), Some("Delete “[Mine]”?")); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.session.doc().unwrap().doc.swatch("[Mine]").is_none()); } /// The prompt for several swatches and groups gives the form the language's plural rule picks for the count. diff --git a/crates/ui-egui/src/panels/symbols.rs b/crates/ui-egui/src/panels/symbols.rs index 0be9e7111c..b50b7876cc 100644 --- a/crates/ui-egui/src/panels/symbols.rs +++ b/crates/ui-egui/src/panels/symbols.rs @@ -19,6 +19,7 @@ use super::library_panel::{self, LibraryKind, LibraryRef, Row}; use super::memo::Memo; use super::{pstate, set_pstate}; use crate::VectorcraftApp; +use crate::caches::SymbolInstances; use crate::menus::Item; use crate::theme::Tokens; use crate::widgets::{self, PanelDrag, menu_item}; @@ -139,21 +140,37 @@ fn current(app: &VectorcraftApp) -> Option { app.session.active().and_then(|st| vectorcraft_engine::cmd::current_symbol(&st.doc)) } -/// Does the selection hold (in it or in its groups) a symbol instance that `wanted` takes? -fn instance_selected(app: &VectorcraftApp, wanted: impl Fn(&Node) -> bool) -> bool { - app.session.active().is_some_and(|st| { - st.selection.objects.iter().any(|id| { - let mut any = false; - if let Some(n) = st.doc.node(*id) { - n.walk(&mut |c| any |= matches!(c.kind, NodeKind::SymbolInstance { .. }) && wanted(c)); - } - any - }) - }) +#[cfg(test)] +thread_local! { + /// How many times [`selected_instances`] walked the selection on this thread. + static INSTANCE_SCANS: std::cell::Cell = const { std::cell::Cell::new(0) }; } -fn has_instances_selected(app: &VectorcraftApp) -> bool { - instance_selected(app, |_| true) +/// The symbol instances in the selection and in its groups, found in one walk of the selected +/// subtrees per (document uid, revision) ([`crate::caches::CanvasCache::symbol_instances`]); +/// `None` without a document. +fn selected_instances(app: &mut VectorcraftApp) -> Option<&mut SymbolInstances> { + let st = app.session.active()?; + let key = (st.uid, st.revision); + if app.canvas.symbol_instances.as_ref().is_none_or(|(k, _)| *k != key) { + #[cfg(test)] + INSTANCE_SCANS.with(|n| n.set(n.get() + 1)); + let mut found = SymbolInstances::default(); + for n in st.selection.objects.iter().filter_map(|id| st.doc.node(*id)) { + n.walk(&mut |c| { + if matches!(c.kind, NodeKind::SymbolInstance { .. }) { + found.changed |= !c.extras().symbol_overrides.is_empty(); + found.ids.push(c.id); + } + }); + } + app.canvas.symbol_instances = Some((key, found)); + } + app.canvas.symbol_instances.as_mut().map(|(_, found)| found) +} + +fn has_instances_selected(app: &mut VectorcraftApp) -> bool { + selected_instances(app).is_some_and(|found| !found.ids.is_empty()) } /// Collect the IDs of selected instances of symbol `name` (including inside groups). @@ -221,15 +238,19 @@ fn item_context_menu(app: &mut VectorcraftApp, ui: &mut Ui, name: &str) { /// Does the selection hold a symbol instance with appearance changes of its own (a dynamic /// symbol's), which Reset drops? -pub(crate) fn changed_instances_selected(app: &VectorcraftApp) -> bool { - instance_selected(app, |c| !c.extras().symbol_overrides.is_empty()) +pub(crate) fn changed_instances_selected(app: &mut VectorcraftApp) -> bool { + selected_instances(app).is_some_and(|found| found.changed) } /// Does the selection hold a symbol instance whose scale, rotation or shear differs from its /// symbol's, which Reset Transformation restores? -fn transformed_instances_selected(app: &VectorcraftApp) -> bool { +fn transformed_instances_selected(app: &mut VectorcraftApp) -> bool { let Some(doc) = app.session.active().map(|st| st.doc.clone()) else { return false }; - instance_selected(app, |c| vectorcraft_engine::cmd::reset_transformation_changes(&doc, c)) + let Some(found) = selected_instances(app) else { return false }; + let ids = &found.ids; + *found + .transformed + .get_or_insert_with(|| ids.iter().filter_map(|id| doc.node(*id)).any(|n| vectorcraft_engine::cmd::reset_transformation_changes(&doc, n))) } /// The symbols of the selected objects when every one is a symbol instance; `None` otherwise. @@ -296,7 +317,7 @@ pub(crate) fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui, reserve: f32) { pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let t = Tokens::get(ui.ctx()); - let Some((doc, keys)) = app.session.active().map(|d| (d.doc.clone(), document_symbols(d))) else { return }; + let Some((doc, keys, document)) = app.session.active().map(|d| (d.doc.clone(), document_symbols(d), d.uid)) else { return }; let names: Vec = doc.symbols.iter().map(|s| s.name.clone()).collect(); let view = app.ui.symbols_view; let sel = current(app); @@ -305,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()); @@ -316,7 +341,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { for n in &names { let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), h), Sense::click_and_drag()); // Dragged onto the canvas, the symbol is placed there. - drag_symbol(ui, &resp, n, uid); + widgets::drag_source(ui, &resp, || PanelDrag::Symbol { document, name: n.clone() }); if on(n) { ui.painter().rect_filled(r, 0.0, t.row_selected); } else if resp.hovered() { @@ -324,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)); @@ -342,7 +370,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { ui.horizontal_wrapped(|ui| { for n in &names { let (r, resp) = ui.allocate_exact_size(vec2(44.0, 44.0), Sense::click_and_drag()); - drag_symbol(ui, &resp, n, uid); + widgets::drag_source(ui, &resp, || PanelDrag::Symbol { document, name: n.clone() }); chip(ui, &doc, &keys, r.shrink(2.0), n); let on = on(n); ui.painter().rect_stroke( @@ -351,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)); @@ -370,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); } @@ -399,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 @@ -409,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. @@ -434,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 { @@ -499,26 +554,14 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { } } -/// The panel state key of the document (`uid`) the symbol being dragged from the panel belongs to. -const DRAG_DOC: &str = "sym-drag-doc"; - -/// Make `resp` a drag source of the symbol `name` of the document `uid`, and keep `uid` while it -/// is dragged. -fn drag_symbol(ui: &Ui, resp: &egui::Response, name: &str, uid: Option) { - if resp.drag_started_by(egui::PointerButton::Primary) { - set_pstate(ui.ctx(), DRAG_DOC, uid); - } - widgets::drag_source(ui, resp, || PanelDrag::Symbol(name.to_string())); -} - /// The symbol of the active document (`uid`, whose symbols are `names`) dragged from the panel and /// released on `button` this frame, if any; `button` is outlined while one is held over it, also /// when it is disabled for clicks. A symbol dragged from another document is ignored. Only the /// release of the primary button drops the symbol; the release of another button ends the drag. fn symbol_dropped(ui: &Ui, button: &egui::Response, names: &[String], uid: Option) -> Option { let held = button.dnd_hover_payload::()?; - let PanelDrag::Symbol(name) = &*held else { return None }; - if !names.contains(name) || pstate::>(ui.ctx(), DRAG_DOC) != uid { + let PanelDrag::Symbol { document, name } = &*held else { return None }; + if !names.contains(name) || Some(*document) != uid { return None; } widgets::drop_target_outline(ui, button.rect); @@ -528,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"; @@ -760,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() @@ -813,13 +904,14 @@ mod tests { let doc = &app.session.active().unwrap().doc; let first = doc.layers[0].children().unwrap().first().unwrap(); assert!(matches!(first.kind, NodeKind::SymbolInstance { .. }), "the art became an instance"); - // Dragging the symbol's tile out of the panel carries the symbol. + // Dragging the symbol's tile out of the panel carries the symbol and its document. frame(&ctx, &mut app, vec![]); let tile = pos2(26.0, 26.0); frame(&ctx, &mut app, vec![egui::Event::PointerMoved(tile), button(tile, true)]); frame(&ctx, &mut app, vec![egui::Event::PointerMoved(tile + vec2(40.0, 40.0))]); frame(&ctx, &mut app, vec![egui::Event::PointerMoved(tile + vec2(80.0, 80.0))]); - assert_eq!(egui::DragAndDrop::payload::(&ctx).as_deref(), Some(&PanelDrag::Symbol(names[0].clone()))); + let document = app.session.active().unwrap().uid; + assert_eq!(egui::DragAndDrop::payload::(&ctx).as_deref(), Some(&PanelDrag::Symbol { document, name: names[0].clone() })); } /// One headless frame of the panel menu; returns its painted labels. @@ -838,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] @@ -1008,6 +1287,134 @@ mod tests { assert_eq!(app.run("symbol.list", json!({})).unwrap()["symbols"][0]["alignToPixelGrid"], false); } + /// Does the selection hold a symbol instance that `wanted` takes, found by walking every + /// selected subtree on each call: what the cached flags must match. + fn walked(app: &VectorcraftApp, wanted: impl Fn(&Node) -> bool) -> bool { + app.session.active().is_some_and(|st| { + st.selection.objects.iter().any(|id| { + let mut any = false; + if let Some(n) = st.doc.node(*id) { + n.walk(&mut |c| any |= matches!(c.kind, NodeKind::SymbolInstance { .. }) && wanted(c)); + } + any + }) + }) + } + + /// Any instance, one with appearance changes, one Reset Transformation changes: walked again. + fn walked_flags(app: &VectorcraftApp) -> [bool; 3] { + let Some(doc) = app.session.active().map(|st| st.doc.clone()) else { return [false; 3] }; + [ + walked(app, |_| true), + walked(app, |c| !c.extras().symbol_overrides.is_empty()), + walked(app, |c| vectorcraft_engine::cmd::reset_transformation_changes(&doc, c)), + ] + } + + fn cached_flags(app: &mut VectorcraftApp) -> [bool; 3] { + [has_instances_selected(app), changed_instances_selected(app), transformed_instances_selected(app)] + } + + fn scans() -> usize { + INSTANCE_SCANS.with(std::cell::Cell::get) + } + + /// The Symbols and Properties panels' instance flags (Break Link, Reset Symbol Instance and the + /// Properties panel's Reset, Reset Transformation) are those a walk of the selection gives, for + /// plain, changed, scaled and grouped instances, several selected objects, nothing selected, + /// Undo and another document; the selection is walked once per document revision, however + /// often they are read. + #[test] + fn instance_flags_are_found_once_per_revision_and_match_a_walk_of_the_selection() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); + let id = |v: Value| v["id"].as_u64().unwrap(); + let rect = id(app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap()); + let second = id(app.run("shape.rectangle", json!({"x": 60, "y": 10, "width": 40, "height": 40})).unwrap()); + let other = id(app.run("shape.rectangle", json!({"x": 300, "y": 10, "width": 40, "height": 40})).unwrap()); + // Reads every flag several times; the walk runs only when the revision changed. + let check = |app: &mut VectorcraftApp, want: [bool; 3], what: &str| { + let before = scans(); + for _ in 0..3 { + assert_eq!(cached_flags(app), want, "{what}"); + } + assert_eq!(walked_flags(app), want, "{what}: a walk of the selection agrees"); + assert!(scans() - before <= 1, "{what}: walked {} times", scans() - before); + }; + app.run("select.set", json!({"ids": [rect]})).unwrap(); + check(&mut app, [false; 3], "no instance"); + // Two objects, so the instance's art is a group whose first object can be painted. + let inst = id(app.run("symbol.new", json!({"name": "S", "ids": [rect, second], "type": "dynamic"})).unwrap()); + app.run("select.set", json!({"ids": [inst]})).unwrap(); + check(&mut app, [true, false, false], "a plain instance"); + app.run("symbol.instance.setAppearance", json!({"id": inst, "path": [0], "fill": "#ff0000"})).unwrap(); + app.run("select.set", json!({"ids": [inst]})).unwrap(); + check(&mut app, [true, true, false], "an instance with appearance changes"); + let scaled = id(app.run("symbol.place", json!({"name": "S", "x": 200, "y": 100})).unwrap()); + app.run("select.set", json!({"ids": [scaled]})).unwrap(); + app.run("object.scale", json!({"sx": 150, "sy": 50})).unwrap(); + check(&mut app, [true, false, true], "a scaled instance"); + app.run("select.set", json!({"ids": [scaled, other]})).unwrap(); + let group = id(app.run("object.group", json!({})).unwrap()); + app.run("select.set", json!({"ids": [group]})).unwrap(); + check(&mut app, [true, false, true], "an instance in a selected group"); + app.run("select.set", json!({"ids": [inst, group]})).unwrap(); + check(&mut app, [true, true, true], "several selected objects"); + app.run("select.set", json!({"ids": [other]})).unwrap(); + check(&mut app, [false; 3], "select.set to a path"); + app.run("select.none", json!({})).unwrap(); + check(&mut app, [false; 3], "nothing selected"); + // Undo takes the group apart again. + app.run("edit.undo", json!({})).unwrap(); + let undone = walked_flags(&app); + check(&mut app, undone, "after Undo"); + // At one revision the walk runs once; a new revision walks again. + app.run("select.set", json!({"ids": [inst, scaled]})).unwrap(); + let before = scans(); + cached_flags(&mut app); + cached_flags(&mut app); + assert_eq!(scans(), before + 1); + app.run("select.set", json!({"ids": [inst]})).unwrap(); + cached_flags(&mut app); + assert_eq!(scans(), before + 2); + // Another document has its own uid, so its flags are found again. + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + let plain = id(app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap()); + app.run("select.set", json!({"ids": [plain]})).unwrap(); + check(&mut app, [false; 3], "another document"); + } + + /// The Properties panel (its Reset quick action) and the Symbols panel (Break Link) share one + /// walk of the selection while the document does not change. + #[test] + fn properties_and_symbols_panels_walk_the_selection_once_per_revision() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let rect = |app: &mut VectorcraftApp, x: f64| { + app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap() + }; + let ids = [rect(&mut app, 10.0), rect(&mut app, 60.0)]; + let inst = app.run("symbol.new", json!({"name": "S", "ids": ids, "type": "dynamic"})).unwrap()["id"].as_u64().unwrap(); + app.run("symbol.instance.setAppearance", json!({"id": inst, "path": [0], "fill": "#ff0000"})).unwrap(); + app.run("select.set", json!({"ids": [inst]})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let before = scans(); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| super::super::properties::show(&mut app, ui)); + out.textures_delta.clear(); + assert_eq!(scans(), before + 1, "the Properties panel reads the flags"); + for _ in 0..3 { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + super::super::properties::show(&mut app, ui); + show(&mut app, ui); + }); + out.textures_delta.clear(); + } + assert_eq!(scans(), before + 1, "one walk for both panels over four frames"); + assert_eq!(cached_flags(&mut app), [true, true, false]); + assert_eq!(scans(), before + 1); + } + /// F8 is Symbol Options… (`ui.symbolOptions`) by default, on every platform. Shift+F8 and Cmd+F8 /// are still the Transform and Info panels' keys, and Cmd+Shift+F8 is still Edit Pattern's. No /// other command, tool or panel has F8 by default. @@ -1979,7 +2386,12 @@ mod tests { frame(&ctx, &mut app, vec![egui::Event::PointerMoved(from), button(from, true)]); frame(&ctx, &mut app, vec![egui::Event::PointerMoved(from + vec2(40.0, 40.0))]); frame(&ctx, &mut app, vec![egui::Event::PointerMoved(from + vec2(80.0, 80.0))]); - assert_eq!(egui::DragAndDrop::payload::(&ctx).as_deref(), Some(&PanelDrag::Symbol("Leaf".into())), "{view}"); + let document = uid(&app).expect("an active document"); + assert_eq!( + egui::DragAndDrop::payload::(&ctx).as_deref(), + Some(&PanelDrag::Symbol { document, name: "Leaf".into() }), + "{view}" + ); let out = frame_held(&ctx, &mut app, vec![egui::Event::PointerMoved(new.center())], egui::Modifiers::NONE); assert!(outlined(&out, new), "{view}: outlined while Leaf is held over it"); frame(&ctx, &mut app, vec![button(new.center(), false)]); @@ -2008,14 +2420,14 @@ mod tests { let undo = app.session.active().unwrap().history.undo.len(); let ctx = egui::Context::default(); // The payloads are set directly, as if dragged from this document's panel. - set_pstate(&ctx, DRAG_DOC, uid(&app)); + let document = uid(&app).expect("an active document"); let new = button_rect(&ctx, &mut app, "New Symbol"); let elsewhere = new.center() - vec2(0.0, 60.0); let cases = [ ("a library symbol", PanelDrag::LibrarySymbol { library: "basic-shapes".into(), name: "Leaf".into() }, new.center()), ("art", PanelDrag::Art(vec![leaf]), new.center()), - ("a stale name", PanelDrag::Symbol("Gone".into()), new.center()), - ("a symbol released elsewhere", PanelDrag::Symbol("Leaf".into()), elsewhere), + ("a stale name", PanelDrag::Symbol { document, name: "Gone".into() }, new.center()), + ("a symbol released elsewhere", PanelDrag::Symbol { document, name: "Leaf".into() }, elsewhere), ]; for (case, drag, at) in cases { egui::DragAndDrop::set_payload(&ctx, drag); @@ -2042,7 +2454,8 @@ mod tests { frame(&ctx, &mut app, vec![egui::Event::PointerMoved(tile), button(tile, true)]); frame(&ctx, &mut app, vec![egui::Event::PointerMoved(tile + vec2(40.0, 40.0))]); frame(&ctx, &mut app, vec![egui::Event::PointerMoved(tile + vec2(80.0, 80.0))]); - assert_eq!(egui::DragAndDrop::payload::(&ctx).as_deref(), Some(&PanelDrag::Symbol("Leaf".into()))); + let document = uid(&app).expect("an active document"); + assert_eq!(egui::DragAndDrop::payload::(&ctx).as_deref(), Some(&PanelDrag::Symbol { document, name: "Leaf".into() })); // While Leaf is held, a new document with a Leaf of its own becomes active. app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 30})).unwrap(); @@ -2222,14 +2635,14 @@ mod tests { let ctx = egui::Context::default(); crate::theme::install_fonts(&ctx); // The payloads are set directly, as if dragged from this document's panel. - set_pstate(&ctx, DRAG_DOC, uid(&app)); + let document = uid(&app).expect("an active document"); let trash = button_rect(&ctx, &mut app, "Delete Symbol"); let elsewhere = trash.center() - vec2(0.0, 60.0); let cases = [ ("a library symbol", PanelDrag::LibrarySymbol { library: "basic-shapes".into(), name: "Leaf".into() }, trash.center()), ("art", PanelDrag::Art(vec![leaf]), trash.center()), - ("a stale name", PanelDrag::Symbol("Gone".into()), trash.center()), - ("a symbol released elsewhere", PanelDrag::Symbol("Dot".into()), elsewhere), + ("a stale name", PanelDrag::Symbol { document, name: "Gone".into() }, trash.center()), + ("a symbol released elsewhere", PanelDrag::Symbol { document, name: "Dot".into() }, elsewhere), ]; for (case, drag, at) in cases { egui::DragAndDrop::set_payload(&ctx, drag); @@ -2246,7 +2659,7 @@ mod tests { frame(&ctx, &mut app, vec![egui::Event::PointerMoved(tile), button(tile, true)]); frame(&ctx, &mut app, vec![egui::Event::PointerMoved(tile + vec2(40.0, 40.0))]); frame(&ctx, &mut app, vec![egui::Event::PointerMoved(tile + vec2(80.0, 80.0))]); - assert_eq!(egui::DragAndDrop::payload::(&ctx).as_deref(), Some(&PanelDrag::Symbol("Leaf".into()))); + assert_eq!(egui::DragAndDrop::payload::(&ctx).as_deref(), Some(&PanelDrag::Symbol { document, name: "Leaf".into() })); app.run("symbol.delete", json!({"name": "Leaf"})).unwrap(); let undo = app.session.active().unwrap().history.undo.len(); let out = frame_held(&ctx, &mut app, vec![egui::Event::PointerMoved(trash.center())], egui::Modifiers::NONE); @@ -2258,7 +2671,7 @@ mod tests { frame(&ctx, &mut app, vec![egui::Event::PointerMoved(tile), button(tile, true)]); frame(&ctx, &mut app, vec![egui::Event::PointerMoved(tile + vec2(40.0, 40.0))]); frame(&ctx, &mut app, vec![egui::Event::PointerMoved(tile + vec2(80.0, 80.0))]); - assert_eq!(egui::DragAndDrop::payload::(&ctx).as_deref(), Some(&PanelDrag::Symbol("Dot".into()))); + assert_eq!(egui::DragAndDrop::payload::(&ctx).as_deref(), Some(&PanelDrag::Symbol { document, name: "Dot".into() })); app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 30})).unwrap(); app.run("symbol.new", json!({"name": "Dot"})).unwrap(); @@ -2274,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_links.rs b/crates/ui-egui/src/panels/tests_links.rs index aaf0ed0be7..1d38e6eb9b 100644 --- a/crates/ui-egui/src/panels/tests_links.rs +++ b/crates/ui-egui/src/panels/tests_links.rs @@ -136,6 +136,36 @@ fn the_panel_lists_the_images_with_link_info_for_the_selected_one() { } } +/// A frame that fetches nothing keeps the stored rows and Link Info as they are, without a copy; the +/// two-second recheck, another first selected image and an edit each store a new cache. +#[test] +fn frames_that_fetch_nothing_reuse_the_cached_rows() { + let dir = Folder::new("cache"); + let (mut app, linked, _) = app(&dir); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let frame = |app: &mut VectorcraftApp, time: f64| { + let raw = egui::RawInput { time: Some(time), ..Default::default() }; + let text: Vec = super::tests_appearance::frame_raw(&ctx, app, raw, super::links::show).into_iter().map(|(t, _)| t).collect(); + (super::pstate::>(&ctx, "links-cache"), text) + }; + let (first, text) = frame(&mut app, 1.0); + assert!(text.iter().any(|t| t == "linked.png") && text.iter().any(|t| t == "40 × 20 px"), "{text:?}"); + let (same, text) = frame(&mut app, 1.5); + assert!(std::sync::Arc::ptr_eq(&first, &same), "a frame that fetches nothing stores no new cache"); + assert!(text.iter().any(|t| t == "linked.png") && text.iter().any(|t| t == "40 × 20 px"), "{text:?}"); + let (rechecked, _) = frame(&mut app, 3.6); + assert!(!std::sync::Arc::ptr_eq(&same, &rechecked), "the files are looked at again after two seconds"); + app.run("select.set", json!({"ids": [linked]})).unwrap(); + let (picked, text) = frame(&mut app, 3.7); + assert!(!std::sync::Arc::ptr_eq(&rechecked, &picked), "Link Info follows the first selected image"); + assert!(text.iter().any(|t| t == "300 × 200 px"), "{text:?}"); + app.run("edit.clear", json!({"ids": [linked]})).unwrap(); + let (edited, text) = frame(&mut app, 3.8); + assert!(!std::sync::Arc::ptr_eq(&picked, &edited), "an edit lists the rows again"); + assert!(!text.iter().any(|t| t == "linked.png") && text.iter().any(|t| t == "embedded.png"), "{text:?}"); +} + /// Copy Info copies the file names of the selected links, or of `ids` in the order given, one per /// line; it is off with nothing selected, and a bad `ids` leaves the clipboard as it was. #[test] diff --git a/crates/ui-egui/src/panels/tests_strokedepth.rs b/crates/ui-egui/src/panels/tests_strokedepth.rs index 1d80cc1c66..c4f2a9fff4 100644 --- a/crates/ui-egui/src/panels/tests_strokedepth.rs +++ b/crates/ui-egui/src/panels/tests_strokedepth.rs @@ -1,5 +1,6 @@ //! Headless frames of the Stroke panel's width profile library: the ≡ menu's Add to Profiles…, -//! Delete Profile and Reset Profiles, and the Profile dropdown listing saved profiles. +//! Delete Profile and Reset Profiles, and the Profile dropdown listing saved profiles and dimmed +//! while the strokes draw with a brush. use serde_json::json; use vectorcraft_doc::WidthProfile; @@ -88,6 +89,206 @@ fn dropdown_lists_saved_profiles_and_applies_them() { assert_eq!(profile_points(&app), Some(custom().points)); } +/// The Stroke panel's Profile dropdown button, right of the "Profile:" label. +fn profile_button(ctx: &egui::Context, app: &mut VectorcraftApp) -> egui::Pos2 { + let t = frame_events(ctx, app, vec![], stroke::show); + let label = text_rect(&t, "Profile:"); + egui::pos2(label.right() + ctx.global_style().spacing.item_spacing.x + 50.0, label.center().y) +} + +/// Is the Profile dropdown dimmed for the stroke the panels show? +fn dimmed(ctx: &egui::Context, app: &VectorcraftApp) -> bool { + stroke::brush_keeps_size(app, ctx, current_stroke(app).as_ref()).is_some() +} + +/// The rows the Profile dropdown lists after a click on it. +fn listed(ctx: &egui::Context, app: &mut VectorcraftApp) -> Vec<&'static str> { + let button = profile_button(ctx, app); + click(ctx, app, button, stroke::show); + let t = frame_events(ctx, app, vec![], stroke::show); + let out = WidthProfile::PRESETS.iter().map(|p| p.label).filter(|l| t.iter().any(|(s, _)| s == l)).collect(); + // Close the list. + let escape = egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; + frame_events(ctx, app, vec![escape], stroke::show); + out +} + +/// A stroke drawn with a brush (here the 3 pt. Round calligraphic brush) keeps the brush's size, +/// so a width profile does not change it: the Profile dropdown is dimmed, opens no list on a +/// uniform stroke, and lists only Uniform on a stroke that has a profile (which resets it). +/// Without the brush, the full list comes back. +#[test] +fn dropdown_is_dimmed_while_the_brush_keeps_its_size() { + let ctx = egui::Context::default(); + let mut app = app_with_line(); + let id = app.session.active().unwrap().selection.objects[0].0; + run(&mut app, "brush.apply", json!({"ids": [id], "name": "3 pt. Round"})); + assert!(dimmed(&ctx, &app)); + assert_eq!(listed(&ctx, &mut app), Vec::<&str>::new(), "no list on a uniform stroke"); + + set_profile(&mut app, custom()); + assert_eq!(listed(&ctx, &mut app), ["Uniform"]); + let button = profile_button(&ctx, &mut app); + click(&ctx, &mut app, button, stroke::show); + let t = frame_events(&ctx, &mut app, vec![], stroke::show); + click(&ctx, &mut app, text_rect(&t, "Uniform").center(), stroke::show); + assert_eq!(profile_points(&app), None, "Uniform resets the profile"); + + run(&mut app, "brush.remove", json!({"ids": [id]})); + assert!(!dimmed(&ctx, &app)); + assert_eq!(listed(&ctx, &mut app).len(), WidthProfile::PRESETS.len()); +} + +/// With an Appearance panel stroke row active, the dropdown follows that row: a brushed row below +/// a plain top stroke dims it, and the plain row does not. +#[test] +fn the_active_stroke_row_decides_whether_the_dropdown_is_dimmed() { + let ctx = egui::Context::default(); + let mut app = app_with_line(); + let id = app.session.active().unwrap().selection.objects[0].0; + run(&mut app, "brush.apply", json!({"ids": [id], "name": "3 pt. Round"})); + run(&mut app, "appearance.addStroke", json!({})); + let items = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().appearance.items.clone(); + let rows: Vec<(usize, bool)> = items + .iter() + .enumerate() + .filter_map(|(i, it)| if let vectorcraft_doc::AppearanceItem::Stroke(s) = it { Some((i, s.brush.is_some())) } else { None }) + .collect(); + let [(lower, true), (top, false)] = rows[..] else { panic!("{rows:?}") }; + assert!(!dimmed(&ctx, &app), "the top stroke has no brush"); + run(&mut app, "appearance.setActiveItem", json!({"index": lower})); + assert!(dimmed(&ctx, &app)); + assert_eq!(listed(&ctx, &mut app), Vec::<&str>::new()); + run(&mut app, "appearance.setActiveItem", json!({"index": top})); + assert!(!dimmed(&ctx, &app)); +} + +/// A selected group with a brushed stroke of its own dims the dropdown, though the panel shows its +/// first member's plain stroke: the list edits the group's stroke. +#[test] +fn a_groups_own_brushed_stroke_dims_the_dropdown() { + let ctx = egui::Context::default(); + let mut app = app_with_line(); + let a = app.session.active().unwrap().selection.objects[0].0; + run(&mut app, "shape.line", json!({"x1": 10, "y1": 150, "x2": 150, "y2": 150})); + let b = app.session.active().unwrap().selection.objects[0].0; + let g = run(&mut app, "object.group", json!({"ids": [a, b]}))["id"].as_u64().unwrap(); + run(&mut app, "appearance.addStroke", json!({"ids": [g]})); + app.session + .edit("Brush", |d, _| { + d.node_mut(vectorcraft_doc::NodeId(g)).unwrap().appearance.stroke_mut().unwrap().brush = Some("3 pt. Round".into()); + Ok(()) + }) + .unwrap(); + run(&mut app, "select.set", json!({"ids": [g]})); + assert!(current_stroke(&app).is_some_and(|s| s.brush.is_none()), "the panel shows a member's plain stroke"); + assert!(dimmed(&ctx, &app)); + assert_eq!(listed(&ctx, &mut app), Vec::<&str>::new()); +} + +/// A selection change with no edit between decides whether the dropdown is dimmed: from a brushed +/// line to a plain one and back. +#[test] +fn selecting_another_object_without_an_edit_updates_the_dimming() { + let ctx = egui::Context::default(); + let mut app = app_with_line(); + let a = app.session.active().unwrap().selection.objects[0].0; + run(&mut app, "shape.line", json!({"x1": 10, "y1": 150, "x2": 150, "y2": 150})); + let b = app.session.active().unwrap().selection.objects[0].0; + run(&mut app, "brush.apply", json!({"ids": [a], "name": "3 pt. Round"})); + run(&mut app, "select.set", json!({"ids": [a]})); + assert!(dimmed(&ctx, &app)); + run(&mut app, "select.set", json!({"ids": [b]})); + assert!(!dimmed(&ctx, &app), "the plain line follows a profile"); + run(&mut app, "select.set", json!({"ids": [a]})); + assert!(dimmed(&ctx, &app)); +} + +/// The Flip Along and Flip Across buttons beside a dimmed dropdown do not flip a brushed stroke's +/// profile, which does not change what the stroke draws. +#[test] +fn flip_buttons_leave_a_brushed_strokes_profile_alone() { + let ctx = egui::Context::default(); + let mut app = app_with_line(); + set_profile(&mut app, custom()); + let spacing = ctx.global_style().spacing.item_spacing.x; + // The dropdown is 100 pt wide and the Flip Along button, 22 pt wide, follows it. + let flip = |ctx: &egui::Context, app: &mut VectorcraftApp| { + let button = profile_button(ctx, app); + let at = egui::pos2(button.x + stroke::PROFILE_DROPDOWN_WIDTH / 2.0 + spacing + 11.0, button.y); + click(ctx, app, at, stroke::show); + }; + flip(&ctx, &mut app); + let flipped = profile_points(&app); + assert_ne!(flipped, Some(custom().points), "Flip Along flips a plain stroke's profile"); + let id = app.session.active().unwrap().selection.objects[0].0; + run(&mut app, "brush.apply", json!({"ids": [id], "name": "3 pt. Round"})); + assert!(dimmed(&ctx, &app)); + let before = profile_points(&app); + assert!(before.is_some()); + flip(&ctx, &mut app); + assert_eq!(profile_points(&app), before, "the buttons are off on a brushed stroke"); +} + +/// With several objects selected, the dropdown is dimmed only while every one of their strokes +/// draws with a brush: a profile still changes the strokes without one. A brush name the +/// document's brushes lack draws a plain stroke, which follows the profile. +#[test] +fn mixed_selection_dims_the_dropdown_only_when_every_stroke_has_a_brush() { + let ctx = egui::Context::default(); + let mut app = app_with_line(); + let a = app.session.active().unwrap().selection.objects[0].0; + run(&mut app, "shape.line", json!({"x1": 10, "y1": 150, "x2": 150, "y2": 150})); + let b = app.session.active().unwrap().selection.objects[0].0; + run(&mut app, "brush.apply", json!({"ids": [a], "name": "3 pt. Round"})); + // The first selected object is the brushed one, whose stroke the panel shows. + run(&mut app, "select.set", json!({"ids": [a, b]})); + assert!(current_stroke(&app).and_then(|s| s.brush).is_some()); + assert!(!dimmed(&ctx, &app)); + assert_eq!(listed(&ctx, &mut app).len(), WidthProfile::PRESETS.len()); + + run(&mut app, "brush.apply", json!({"ids": [b], "name": "3 pt. Round"})); + run(&mut app, "select.set", json!({"ids": [a, b]})); + assert!(dimmed(&ctx, &app)); + assert_eq!(listed(&ctx, &mut app), Vec::<&str>::new()); + + // The shown stroke is uniform and the other has a profile: Uniform still removes it. + let edit = |app: &mut VectorcraftApp, f: &dyn Fn(&mut vectorcraft_doc::Appearance)| { + app.session + .edit("Edit", |d, _| { + f(&mut d.node_mut(vectorcraft_doc::NodeId(b)).unwrap().appearance); + Ok(()) + }) + .unwrap(); + }; + edit(&mut app, &|ap| ap.stroke_mut().unwrap().profile = Some(custom())); + assert_eq!(current_stroke(&app).and_then(|s| s.profile), None); + assert_eq!(listed(&ctx, &mut app), ["Uniform"]); + let button = profile_button(&ctx, &mut app); + click(&ctx, &mut app, button, stroke::show); + let t = frame_events(&ctx, &mut app, vec![], stroke::show); + click(&ctx, &mut app, text_rect(&t, "Uniform").center(), stroke::show); + let node = |app: &VectorcraftApp| app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(b)).unwrap().clone(); + assert_eq!(node(&app).appearance.stroke().unwrap().profile, None, "Uniform reset the other stroke"); + + edit(&mut app, &|ap| ap.stroke_mut().unwrap().brush = Some("No Such Brush".into())); + assert!(!dimmed(&ctx, &app)); + + // An object without a stroke item takes a plain stroke from a profile. + edit(&mut app, &|ap| ap.items.retain(|i| !matches!(i, vectorcraft_doc::AppearanceItem::Stroke(_)))); + assert!(node(&app).appearance.stroke().is_none()); + assert!(!dimmed(&ctx, &app)); + assert_eq!(listed(&ctx, &mut app).len(), WidthProfile::PRESETS.len()); +} + +/// The dimmed dropdown's hover text is the Width tool's status message, word for word, so the two +/// share their catalog rows. +#[test] +fn the_hover_text_is_the_width_tools_status_message() { + let literal = format!("tl!(\"{}\")", vectorcraft_tools::distort::KEEPS_SIZE); + assert!(include_str!("stroke.rs").contains(&literal), "panels/stroke.rs has no {literal}"); +} + #[test] fn every_arrowhead_preview_draws_its_head() { use vectorcraft_doc::Arrowhead; diff --git a/crates/ui-egui/src/panels/tests_three_d.rs b/crates/ui-egui/src/panels/tests_three_d.rs index 5ff986af13..1226b292d7 100644 --- a/crates/ui-egui/src/panels/tests_three_d.rs +++ b/crates/ui-egui/src/panels/tests_three_d.rs @@ -1259,6 +1259,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 be7731daf5..61993a8581 100644 --- a/crates/ui-egui/src/panels/three_d.rs +++ b/crates/ui-egui/src/panels/three_d.rs @@ -278,9 +278,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); @@ -299,6 +299,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 95edf87f8c..936fdda1a6 100644 --- a/crates/ui-egui/src/panels/transform.rs +++ b/crates/ui-egui/src/panels/transform.rs @@ -422,10 +422,11 @@ fn pixel_aligned_ids(app: &VectorcraftApp) -> Vec { app.session.active().map(|st| st.selection.objects.iter().filter(|id| st.doc.node(**id).is_some()).map(|id| id.0).collect()).unwrap_or_default() } -/// A live rectangle's, polygon's or ellipse's properties (Transform and Properties panels, and the -/// Contextual Task Bar), their widget ids under `id`. `headed` adds the Rectangle and Polygon -/// Properties headings; an ellipse's heading always shows. Returns false, drawing nothing, for -/// other live shapes. +/// A live rectangle's, polygon's, ellipse's or line's properties (Transform and Properties panels, +/// and for the first three the Contextual Task Bar), their widget ids under `id`. `headed` adds +/// the Rectangle and Polygon Properties headings; an ellipse's and a line's heading always show. +/// Returns false, drawing nothing, for other live shapes, and for a line unless every selected +/// object is one. pub(crate) fn live_shape_rows(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node, live: &LiveShape, id: &str, headed: bool) -> bool { match live { LiveShape::Rectangle { .. } => { @@ -444,27 +445,89 @@ pub(crate) fn live_shape_rows(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node, l widgets::subheader(ui, tl!("Ellipse Properties:")); pie_rows(app, ui, *pie, &format!("{id}-pie")); } + LiveShape::Line { .. } => return line_rows(app, ui, live, &format!("{id}-line")), _ => return false, } true } +/// Whether every selected object is a live line (and one is selected). +fn only_lines_selected(app: &VectorcraftApp) -> bool { + let Some(st) = app.session.active() else { return false }; + let line = |n: &Node| matches!(&n.kind, NodeKind::Path { live: Some(l), .. } if matches!(**l, LiveShape::Line { .. })); + !st.selection.objects.is_empty() && st.selection.objects.iter().all(|o| st.doc.node(*o).is_some_and(line)) +} + +/// A live line's Line Properties (Transform and Properties panels), under its heading: its length, +/// end to end, and its angle (counterclockwise from 3 o'clock, from its first end to its second). A new length keeps each selected line's first end in place, and a +/// new angle turns each one about its midpoint. Returns false, drawing nothing, unless every +/// selected object is a live line. +pub(crate) fn line_rows(app: &mut VectorcraftApp, ui: &mut Ui, live: &LiveShape, id: &str) -> bool { + if !only_lines_selected(app) { + return false; + } + let (units, fw) = (app.session.general_unit(), super::field_width(ui)); + widgets::subheader(ui, tl!("Line Properties:")); + // The `object.setLiveShape` params the edited fields set, all sent in one call. + let mut set = serde_json::Map::new(); + egui::Grid::new((id, "grid")).num_columns(2).spacing([6.0, 6.0]).show(ui, |ui| { + widgets::dim_label(ui, tl!("Line Length:")); + if let Some(l) = widgets::num_field_named(ui, (id, "length"), Some(tl!("Line Length:")), live.line_length(), units, fw) { + set.insert("lineLength".into(), json!(l)); + } + ui.end_row(); + widgets::dim_label(ui, tl!("Line Angle:")); + if let Some(a) = widgets::plain_field_named(ui, (id, "angle"), Some(tl!("Line Angle:")), live.line_angle().unwrap_or(0.0), "°", 1, fw) { + set.insert("lineAngle".into(), json!(a)); + } + ui.end_row(); + }); + if !set.is_empty() + && let Err(e) = app.run("object.setLiveShape", serde_json::Value::Object(set)) + { + app.status(e); + } + true +} + /// 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. @@ -521,7 +584,13 @@ pub(crate) fn polygon_rows(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node, live /// popover under it, as the Stroke link does with the Stroke panel. pub fn link(app: &mut VectorcraftApp, ui: &mut Ui) { let resp = ui.link(link_text(ui)).on_hover_text(tl!("Transform options")); - widgets::popover(&resp, resp.clicked(), |ui| { + popover(app, &resp); +} + +/// The Transform panel in a popover under `resp`, which a click on it toggles: the Control bar's +/// Transform [`link`], and its X:, Y:, W: and H: labels. +pub fn popover(app: &mut VectorcraftApp, resp: &egui::Response) { + widgets::popover(resp, resp.clicked(), |ui| { ui.set_width(300.0); show(app, ui); }); diff --git a/crates/ui-egui/src/panels/transform/tests.rs b/crates/ui-egui/src/panels/transform/tests.rs index a798fc75ce..fe284bbe22 100644 --- a/crates/ui-egui/src/panels/transform/tests.rs +++ b/crates/ui-egui/src/panels/transform/tests.rs @@ -154,6 +154,113 @@ 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 +/// Expand Shape, show none. +#[test] +fn a_line_shows_and_takes_its_line_properties() { + let ends = |app: &VectorcraftApp| match &first_selected(app).unwrap().kind { + NodeKind::Path { live: Some(l), .. } => match **l { + LiveShape::Line { a, b } => (a, b), + ref k => panic!("{k:?}"), + }, + k => panic!("{k:?}"), + }; + let near = |p: Point, x: f64, y: f64| (p.x - x).abs() < 1e-6 && (p.y - y).abs() < 1e-6; + 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(); + // 100 pt long, going down the page to the right: 53.13° clockwise, 306.87° counterclockwise. + let id = app.run("shape.line", json!({"x1": 50, "y1": 50, "x2": 110, "y2": 130})).unwrap()["id"].as_u64().unwrap(); + let shown = texts(&mut app, draw); + for t in ["Line Properties:", "Line Length:", "100 pt", "Line Angle:", "306.9°"] { + assert!(shown.iter().any(|s| s == t), "{t} in {shown:?}"); + } + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + type_into(&ctx, &mut app, draw, "100 pt", "50"); + let (a, b) = ends(&app); + assert!(near(a, 50.0, 50.0) && near(b, 80.0, 90.0), "{a:?} {b:?}"); + type_into(&ctx, &mut app, draw, "306.9°", "90"); + let (a, b) = ends(&app); + assert!(near(a, 65.0, 95.0) && near(b, 65.0, 45.0), "{a:?} {b:?}"); + assert!(texts(&mut app, draw).iter().any(|s| s == "90°")); + app.run("edit.undo", json!({})).unwrap(); + let (a, b) = ends(&app); + assert!(near(a, 50.0, 50.0) && near(b, 80.0, 90.0), "one undo step: {a:?} {b:?}"); + // With a rectangle selected too, the fields would set the line alone: they don't show. + let rect = app.run("shape.rectangle", json!({"x": 200, "y": 200, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [id, rect]})).unwrap(); + assert!(!texts(&mut app, draw).iter().any(|s| s == "Line Properties:" || s == "Line Length:")); + app.run("select.set", json!({"ids": [id]})).unwrap(); + assert!(texts(&mut app, draw).iter().any(|s| s == "Line Properties:")); + app.run("object.expandShape", json!({})).unwrap(); + assert!(!texts(&mut app, draw).iter().any(|s| s == "Line Properties:" || s == "Line Length:")); + } +} + #[test] fn the_artboard_tool_shows_the_active_artboard() { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); @@ -262,8 +369,9 @@ fn type_into(ctx: &egui::Context, app: &mut VectorcraftApp, draw: fn(&mut Vector } /// The panel menu's Transform Object Only, Transform Pattern Only and Transform Both, one -/// checked: a new X typed in the panel (or the Properties panel's Transform section) moves the -/// pattern-filled rectangle and leaves its tiles, moves its tiles alone, or moves both. Until +/// checked: a new X typed in the panel (or the Properties panel's Transform section, or the +/// Control bar) moves the pattern-filled rectangle and leaves its tiles, moves its tiles alone, or +/// moves both. Until /// one is chosen the panels do as General › Transform Pattern Tiles says, as they did before /// the menu acted, and the menu checks Transform Both while it is on, Transform Object Only /// while it is off; a choice overrides it, and resetting the preferences returns to it. @@ -277,7 +385,7 @@ fn the_menu_chooses_whether_the_object_its_pattern_or_both_transform() { let labels = ["Transform Object Only", "Transform Pattern Only", "Transform Both"]; let modes = ["object", "pattern", "both"]; let checked = |shown: &[String]| -> Vec { (0..3).filter(|i| shown.contains(&format!("✓ {}", labels[*i]))).collect() }; - for draw in [show as fn(&mut VectorcraftApp, &mut Ui), crate::panels::properties::transform_section] { + for draw in [show as fn(&mut VectorcraftApp, &mut Ui), crate::panels::properties::transform_section, crate::chrome::control_bar] { for general in [false, true] { for pick in [None, Some(0), Some(1), Some(2)] { let case = format!("General › Transform Pattern Tiles {general}, menu choice {pick:?}"); @@ -362,12 +470,12 @@ fn the_menu_choice_also_applies_to_rotation_and_shear() { } } -/// Use Registration Point for Symbol: with one symbol instance selected, the panel and the -/// Properties panel's Transform section show and set X and Y at its symbol's registration point -/// (here the top-left one) instead of the reference point (the centre). +/// Use Registration Point for Symbol: with one symbol instance selected, the panel, the +/// Properties panel's Transform section and the Control bar show and set X and Y at its symbol's +/// registration point (here the top-left one) instead of the reference point (the center). #[test] fn use_registration_point_for_symbol_measures_an_instance_from_its_registration_point() { - for draw in [show as fn(&mut VectorcraftApp, &mut Ui), crate::panels::properties::transform_section] { + for draw in [show as fn(&mut VectorcraftApp, &mut Ui), crate::panels::properties::transform_section, crate::chrome::control_bar] { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); app.run("shape.rectangle", json!({"x": 100, "y": 50, "width": 80, "height": 40})).unwrap(); @@ -395,6 +503,47 @@ fn use_registration_point_for_symbol_measures_an_instance_from_its_registration_ } } +/// The Control bar's X, Y, W and H use the reference point the Transform panel's locator chose: +/// X and Y show that point of the selection's box and a new X or Y moves it there, a new W or H +/// keeps it in place, and choosing another point changes what the fields show without editing the +/// art. Each field edit is one undo step. +#[test] +fn the_control_bar_fields_use_the_shared_reference_point() { + use crate::panels::tests_appearance::frame_events; + let draw = crate::chrome::control_bar as fn(&mut VectorcraftApp, &mut Ui); + // The reference point (top-left, center, bottom-right): X/Y shown for the rectangle at + // (10, 20), 100 × 50; the box after X becomes `x`, and after W becomes 200 and H 100. + let cases = [ + (0usize, ("10 pt", "20 pt"), "30", Rect::new(30.0, 20.0, 130.0, 70.0), Rect::new(30.0, 20.0, 230.0, 120.0)), + (4, ("60 pt", "45 pt"), "80", Rect::new(30.0, 20.0, 130.0, 70.0), Rect::new(-20.0, -5.0, 180.0, 95.0)), + (8, ("110 pt", "70 pt"), "130", Rect::new(30.0, 20.0, 130.0, 70.0), Rect::new(-70.0, -30.0, 130.0, 70.0)), + ]; + for (refi, (x, y), new_x, moved, sized) in cases { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 20, "width": 100, "height": 50})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let revision = |app: &VectorcraftApp| app.session.active().unwrap().revision; + let shown = |app: &mut VectorcraftApp| frame_events(&ctx, app, vec![], draw).into_iter().map(|(t, _)| t).collect::>(); + shown(&mut app); + let before = revision(&app); + ctx.data_mut(|d| d.insert_temp(egui::Id::unique("refpt"), refi)); + let texts = shown(&mut app); + assert!(texts.iter().any(|t| t == x) && texts.iter().any(|t| t == y), "reference {refi}: X {x}, Y {y} in {texts:?}"); + assert_eq!(revision(&app), before, "reference {refi}: choosing the point leaves the art"); + type_into(&ctx, &mut app, draw, x, new_x); + assert_eq!(app.selection_box().unwrap().rect, moved, "reference {refi}: X"); + assert_eq!(revision(&app), before + 1, "reference {refi}: one undo step"); + type_into(&ctx, &mut app, draw, "100 pt", "200"); + type_into(&ctx, &mut app, draw, "50 pt", "100"); + assert_eq!(app.selection_box().unwrap().rect, sized, "reference {refi}: W and H"); + app.run("edit.undo", json!({})).unwrap(); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.selection_box().unwrap().rect, moved, "reference {refi}: undo"); + } +} + /// Use Registration Point for Symbol on a reflected, a rotated and a sheared symbol instance: /// the panel and the Properties panel's Transform section show X and Y at the registration /// point where the instance's transform put it (not at the box's point of the same index), a 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/scrub.rs b/crates/ui-egui/src/scrub.rs index a68759087f..b1de4e585c 100644 --- a/crates/ui-egui/src/scrub.rs +++ b/crates/ui-egui/src/scrub.rs @@ -3,7 +3,8 @@ //! field's value by one unit every [`PX_PER_STEP`] points, ten with Shift and a tenth with //! Ctrl/Cmd, as the arrow keys step a focused field; a click on the label focuses the field. A //! label that is a link (the Control bar's `Stroke:` and `Opacity:`, which open their panels; -//! #4088) scrubs its field the same way, and a click on it still follows the link. The text box +//! #4088) or opens a panel (its `X:`, `Y:`, `W:` and `H:`, which open the Transform panel) scrubs +//! its field the same way, and a click on it still opens the panel. The text box //! itself never scrubs, and a field without a label doesn't. //! //! The panels apply each value the drag passes as they apply a typed one, so the art follows the @@ -117,12 +118,14 @@ struct Label { pass: u64, /// The label is a link, this widget: a click follows it instead of focusing the field. link: Option, + /// The label is a tab stop of its own (a link; not a [`panel_label`]). + tab_stop: bool, } /// Note the label (text or icon) drawn at `rect`: a numeric field drawn right after it on the /// same line takes it as its label, which scrubs the field. pub(crate) fn note_label(ui: &Ui, rect: Rect) { - note(ui, rect, None); + note(ui, Label { rect, pass: 0, link: None, tab_stop: false }); } /// A link that labels the numeric field drawn after it (it opens a panel when clicked): a drag on @@ -135,13 +138,27 @@ pub(crate) fn link_label(ui: &mut Ui, text: egui::RichText) -> Response { ui.link(text) }) .inner; - note(ui, link.rect, Some(link.id)); + note(ui, Label { rect: link.rect, pass: 0, link: Some(link.id), tab_stop: true }); link } -fn note(ui: &Ui, rect: Rect, link: Option) { +/// A field's label that opens a panel when clicked (the Control bar's X:, Y:, W: and H:, which open +/// the Transform panel): a drag on it scrubs the field after it, and a click stays the label's, as +/// with [`link_label`]. Unlike a link it is not a tab stop of its own, so Tab still moves from one +/// field to the next. The pointing hand shows over it. +pub(crate) fn panel_label(ui: &mut Ui, text: egui::RichText) -> Response { + let label = ui.add(egui::Label::new(text).selectable(false).sense(Sense::CLICK)); + if label.hovered() { + ui.ctx().set_cursor_icon(CursorIcon::PointingHand); + } + note(ui, Label { rect: label.rect, pass: 0, link: Some(label.id), tab_stop: false }); + label +} + +/// Keep `label` for the field after it, as drawn this pass. +fn note(ui: &Ui, label: Label) { let pass = ui.ctx().cumulative_pass_nr(); - ui.data_mut(|d| d.insert_temp(label_id(), Label { rect, pass, link })); + ui.data_mut(|d| d.insert_temp(label_id(), Label { pass, ..label })); } /// The label noted just before the field at `field`, on its line. @@ -169,9 +186,11 @@ pub(crate) fn field(ui: &Ui, field: Id, rect: Rect, text: &str, value: Option ui.interact(label.rect, link, Sense::drag()), + Some(link) if label.tab_stop => ui.interact(label.rect, link, Sense::drag()), + Some(link) => ui.interact(label.rect, link, Sense::DRAG), None => ui.interact(label.rect, field.with("scrub-label"), Sense::CLICK | Sense::DRAG), }; drag(ui, &resp, field, text, value, decimals, label.link.is_some()).map(|v| v.max(*bounds.start()).min(*bounds.end())) 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/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index 781bec4e74..56bc5ada08 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -539,7 +539,8 @@ fn escape_ends_one_thing(app: &mut VectorcraftApp, ctx: &egui::Context) { if app.session.active().is_some_and(|d| d.doc.pattern_edit.is_some()) { let _ = app.run("object.pattern.done", json!({})); } else if app.session.active().is_some_and(|d| d.isolation.is_some()) { - let _ = app.run("object.exitIsolation", json!({})); + // From an isolated sublayer, Escape leaves isolation mode rather than going up one layer. + let _ = app.run("object.exitIsolation", json!({ "all": true })); } else if app.session.active().is_some_and(|d| d.global_edit.is_some()) { let _ = app.run("select.globalEdit", json!({})); } else if app.ui.flyout.is_some() { 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/tests/taskbar.rs b/crates/ui-egui/src/tests/taskbar.rs index 8230969c97..bc4734db5a 100644 --- a/crates/ui-egui/src/tests/taskbar.rs +++ b/crates/ui-egui/src/tests/taskbar.rs @@ -215,6 +215,185 @@ fn an_image_with_vector_art_offers_make_clipping_mask() { assert!(has(&texts, "Unite") && !has(&texts, "Make Clipping Mask"), "{texts:?}"); } +/// Places a 2 by 2 pixel image from `dir` and returns its id. +fn place_image(app: &mut VectorcraftApp, dir: &crate::tests_folder::Folder) -> u64 { + let raw = [0u8, 128, 255, 255].repeat(4); + let image = craft_image_codecs::Image::from_raw(2, 2, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, raw).unwrap(); + let png = craft_image_codecs::encode(&image, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap(); + let path = dir.file("tile.png", &png); + app.services.read = Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))); + app.run("file.place", json!({"path": path, "link": false})).unwrap(); + let img = app.session.active().unwrap().selection.objects[0].0; + assert!(matches!(kind(app, img), NodeKind::Image(_))); + img +} + +/// Whether the bar offers Make Clipping Mask, worked out by counting the selected images: some of +/// the selected ids, but not all, are images. +fn mixed_by_count(st: &vectorcraft_engine::DocState) -> bool { + let n = st.selection.len(); + let images = st.selection.objects.iter().filter_map(|id| st.doc.node(*id)).filter(|o| matches!(o.kind, NodeKind::Image(_))).count(); + images > 0 && images < n +} + +/// Sets the selected objects and anchors directly, as no command can select an id with no object, +/// and moves the document's revision as every selection change does. +fn set_selection(app: &mut VectorcraftApp, ids: &[u64], anchors: &[u64]) { + let st = app.session.active_mut().unwrap(); + st.selection.objects = ids.iter().map(|i| NodeId(*i)).collect(); + st.selection.anchors = anchors.iter().map(|i| (NodeId(*i), [(0, 0)].into_iter().collect())).collect(); + st.revision += 1; +} + +/// The task bar's check for images selected with other objects gives the count's answer for every +/// selection: empty, one object, paths only, images only, images with paths or type, an id +/// selected twice, anchors picked out, and ids with no object. +#[test] +fn images_with_other_art_matches_the_image_count() { + let mut app = app(); + let dir = crate::tests_folder::Folder::new("ui-taskbar-mixed"); + let img = place_image(&mut app, &dir); + let img2 = place_image(&mut app, &dir); + let a = id(app.run("shape.rectangle", json!({"x": 10, "y": 200, "width": 40, "height": 40})).unwrap()); + let b = id(app.run("shape.rectangle", json!({"x": 30, "y": 210, "width": 40, "height": 40})).unwrap()); + let t = id(app.run("text.create", json!({"x": 60, "y": 80, "text": "Hello"})).unwrap()); + let stale = 1_000_000; + assert!(app.session.active().unwrap().doc.node(NodeId(stale)).is_none()); + let ctx = egui::Context::default(); + let cases: [(&[u64], &[u64], bool); 17] = [ + (&[], &[], false), + (&[a], &[], false), + (&[img], &[], false), + (&[a, b], &[], false), + (&[img, img2], &[], false), + (&[img, a], &[], true), + (&[a, img], &[], true), + (&[a, b, img], &[], true), + (&[img, t], &[], true), + (&[img, img], &[], false), + (&[img, img, a], &[], true), + (&[img, a], &[a], true), + (&[a, b], &[a, b], false), + (&[img, stale], &[], true), + (&[img, img2, stale], &[], true), + (&[a, stale], &[], false), + (&[stale, stale], &[], false), + ]; + for (ids, anchors, mixed) in cases { + set_selection(&mut app, ids, anchors); + let st = app.session.active().unwrap(); + assert_eq!(mixed_by_count(st), mixed, "{ids:?} with anchors on {anchors:?}: the count"); + assert_eq!(canvas::images_with_other_art(st, &ctx), mixed, "{ids:?} with anchors on {anchors:?}"); + } +} + +/// The check is worked out once for each revision of the document: an unchanged revision gives the +/// kept answer, and a selection change, which moves the revision, works it out again. +#[test] +fn images_with_other_art_is_kept_for_the_revision() { + let mut app = app(); + let dir = crate::tests_folder::Folder::new("ui-taskbar-mixed-kept"); + let img = place_image(&mut app, &dir); + let a = id(app.run("shape.rectangle", json!({"x": 10, "y": 200, "width": 40, "height": 40})).unwrap()); + let b = id(app.run("shape.rectangle", json!({"x": 30, "y": 210, "width": 40, "height": 40})).unwrap()); + select(&mut app, &[img, a]); + let ctx = egui::Context::default(); + assert!(canvas::images_with_other_art(app.session.active().unwrap(), &ctx)); + // Changing the objects behind the revision's back shows the kept answer is used. + app.session.active_mut().unwrap().selection.objects = vec![NodeId(a), NodeId(b)]; + assert!(canvas::images_with_other_art(app.session.active().unwrap(), &ctx), "the revision's answer is kept"); + select(&mut app, &[a, b]); + assert!(!canvas::images_with_other_art(app.session.active().unwrap(), &ctx), "a new revision works it out again"); + select(&mut app, &[b, img]); + assert!(canvas::images_with_other_art(app.session.active().unwrap(), &ctx)); + // Another context keeps its own answer. + assert!(canvas::images_with_other_art(app.session.active().unwrap(), &egui::Context::default())); +} + +/// The CPU time this thread has used, where the system reports it (Linux), else none. +fn cpu_time() -> Option { + std::fs::read_to_string("/proc/thread-self/schedstat") + .ok() + .and_then(|s| s.split_whitespace().next()?.parse::().ok()) + .map(std::time::Duration::from_nanos) +} + +/// Runs `f` and returns the CPU time it used (zero where the system does not report it) and the +/// time it took. +fn timed(f: impl FnOnce()) -> (std::time::Duration, std::time::Duration) { + let (cpu, wall) = (cpu_time(), std::time::Instant::now()); + f(); + let wall = wall.elapsed(); + (cpu_time().zip(cpu).map_or_else(Default::default, |(b, a)| b.saturating_sub(a)), wall) +} + +/// Times the image check on a selection of 131,072 rectangles: 120 frames with an unchanged +/// revision, counting each frame as before against the kept answer, and the first frame after a +/// change. Each cell is the median of 7 runs, CPU time then elapsed time. Run with +/// `cargo test -p vectorcraft-ui-egui --lib images_with_other_art_timing -- --ignored --nocapture`. +#[test] +#[ignore = "a timing run on a large selection"] +fn images_with_other_art_timing() { + let dir = crate::tests_folder::Folder::new("ui-taskbar-mixed-timing"); + let doubled = |app: &mut VectorcraftApp, times: usize| { + for _ in 0..times { + app.run("select.all", json!({})).unwrap(); + app.run("edit.duplicate", json!({})).unwrap(); + } + app.run("select.all", json!({})).unwrap(); + }; + let rects = |app: &mut VectorcraftApp| { + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + doubled(app, 17); + }; + let mut variants: Vec<(&str, VectorcraftApp)> = vec![]; + let mut none = app(); + rects(&mut none); + variants.push(("131,072 rectangles", none)); + let mut one = app(); + rects(&mut one); + place_image(&mut one, &dir); + one.run("select.all", json!({})).unwrap(); + variants.push(("131,072 rectangles and 1 image", one)); + let mut images = app(); + place_image(&mut images, &dir); + doubled(&mut images, 9); + variants.push(("512 images", images)); + let median = |mut v: Vec<(std::time::Duration, std::time::Duration)>| { + let mut wall: Vec<_> = v.iter().map(|t| t.1).collect(); + v.sort(); + wall.sort(); + format!("{:.2?} / {:.2?}", v[v.len() / 2].0, wall[wall.len() / 2]) + }; + println!("| Selection | Count, 120 frames | Kept, 120 frames | Count, 1 frame | First frame after a change |"); + println!("| --- | --- | --- | --- | --- |"); + for (name, mut app) in variants { + let mut runs = [vec![], vec![], vec![], vec![]]; + for _ in 0..7 { + let ctx = egui::Context::default(); + let st = app.session.active().unwrap(); + let expected = mixed_by_count(st); + assert_eq!(canvas::images_with_other_art(st, &ctx), expected, "{name}"); + runs[0].push(timed(|| { + for _ in 0..120 { + assert_eq!(std::hint::black_box(mixed_by_count(st)), expected); + } + })); + runs[1].push(timed(|| { + for _ in 0..120 { + assert_eq!(std::hint::black_box(canvas::images_with_other_art(st, &ctx)), expected); + } + })); + runs[2].push(timed(|| assert_eq!(std::hint::black_box(mixed_by_count(st)), expected))); + app.session.active_mut().unwrap().revision += 1; + let st = app.session.active().unwrap(); + runs[3].push(timed(|| assert_eq!(std::hint::black_box(canvas::images_with_other_art(st, &ctx)), expected))); + } + let [a, b, c, d] = runs.map(median); + println!("| {name} ({} selected) | {a} | {b} | {c} | {d} |", app.session.active().unwrap().selection.len()); + } +} + #[test] fn type_converts_between_point_and_area_type() { let mut app = app(); diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index c7aeadcdc2..ec2ef99db0 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -38,7 +38,7 @@ pub const BASIC: &[(&str, &[&[&str]])] = &[ "Shapes", &[ &["rectangle", "roundedRectangle", "star", "lineSegment", "arc", "spiral", "rectangularGrid", "polarGrid", "flare"], - &["ellipse"], + &["ellipse", "circle"], &["polygon"], &["shaper"], ], @@ -1211,7 +1211,7 @@ fn puppet_warp_options(app: &mut VectorcraftApp, ui: &mut Ui, reserve: f32) { ui.label(text); let unit = app.session.general_unit(); if let Some(v) = widgets::num_field(ui, ("cb-tool", "expand"), opts["expand"].as_f64(), unit, 64.0) { - app.run("tool.setOption", json!({ "key": "expand", "value": v })).ok(); + app.run("tool.setOption", json!({ "key": "expand", "value": v.clamp(0.0, 1000.0) })).ok(); } } let show = opts["showMesh"].as_bool().unwrap_or(true); diff --git a/crates/ui-egui/src/toolbar/tests.rs b/crates/ui-egui/src/toolbar/tests.rs index 37613c72e8..708e5e9807 100644 --- a/crates/ui-egui/src/toolbar/tests.rs +++ b/crates/ui-egui/src/toolbar/tests.rs @@ -853,7 +853,7 @@ fn window_float_tools_floats_and_puts_back_a_group() { assert!(app.ui.floating_flyouts.is_empty() && check(&app) == Some(false)); assert_eq!(app.run("window.floatTools", json!({"tool": "pen", "floating": false})).unwrap(), json!(false)); // A tool alone in its slot, an unknown tool, a bad flag. - assert!(app.run("window.floatTools", json!({"tool": "ellipse"})).is_err()); + assert!(app.run("window.floatTools", json!({"tool": "polygon"})).is_err()); assert!(app.run("window.floatTools", json!({"tool": "nope"})).is_err()); assert!(app.run("window.floatTools", json!({})).is_err()); assert!(app.run("window.floatTools", json!({"tool": "pen", "floating": "yes"})).is_err()); diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index d3278f667d..45818730d1 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -42,21 +42,22 @@ 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}; pub use labels::{dim_label, dim_name, divider, field_label, label_row, link_label, section_header, section_toggle, section_toggle_name, subheader}; -pub(crate) use labels::{dim_label_width, label_field, take_previous_label, text_width}; +pub(crate) use labels::{dim_label_width, field_panel_label, label_field, take_previous_label, text_width}; pub(crate) use numeric::{ANY, round_to, set_bare_numbers_are_points, typed_unit}; pub use numeric::{ SpinPick, mixed_field, mixed_field_named, num_field, num_field_live, num_field_named, num_field_refusing, num_field_within, @@ -211,7 +212,7 @@ pub(crate) mod accessibility_tests { let tree = tree(|ui| { icon_button(ui, "link", "Constrain Proportions", true, 24.0); toggle_icon(ui, "eye", true, 18.0, "Show all plates"); - toggle_icon(ui, "eye", false, 18.0, "Show/hide plate (Alt-click: only this plate)"); + toggle_icon(ui, "eye", false, 18.0, "Show/hide plate (Alt-click: only this plate; Alt-click again: all plates)"); orientation_button(ui, false, true, "Portrait"); orientation_button(ui, true, false, "Landscape"); layout_button(ui, &[(0, 0), (1, 0)], true, "Grid by Row"); @@ -221,7 +222,7 @@ pub(crate) mod accessibility_tests { let off = |label| assert_eq!(role_and_state(&tree, label), (Role::Button, Some(Toggled::False)), "{label}"); on("Constrain Proportions"); on("Show all plates"); - off("Show/hide plate (Alt-click: only this plate)"); + off("Show/hide plate (Alt-click: only this plate; Alt-click again: all plates)"); on("Portrait"); off("Landscape"); on("Grid by Row"); 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 a3df5a4098..e0eec69ecd 100644 --- a/crates/ui-egui/src/widgets/drag.rs +++ b/crates/ui-egui/src/widgets/drag.rs @@ -13,19 +13,23 @@ pub enum PanelDrag { /// it is dropped. Paint { paint: Paint, params: serde_json::Value, rows: Option, library: Option<(String, String)> }, /// The Appearance panel's thumbnail: art it is dropped on takes object `0`'s appearance - /// (`appearance.copyFrom`); the Graphic Styles panel makes a style of it. + /// (`appearance.copyFrom`); the Graphic Styles panel makes a style of it, or with Alt held + /// 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`), the Symbols panel a symbol of it all + /// makes a style of the first object (`graphicStyle.new`), or with Alt held replaces the style + /// it is dropped on with that object's look (`graphicStyle.redefine`), the Symbols panel a symbol of it all /// (`symbol.new`), the Swatches panel a pattern swatch of a copy (`object.pattern.make`) and the /// Brushes panel an Art brush (`brush.new`). Art(Vec), - /// A Symbols panel symbol: the canvas places an instance of it centred where it is dropped - /// (`symbol.place`). - Symbol(String), + /// A Symbols panel symbol (`document`: the uid of the document whose panel it was dragged + /// from): the canvas places an instance of it centered where it is dropped, adding the symbol + /// first when another document is active by then (`symbol.placeFromDocument`). + Symbol { document: u64, name: String }, /// A symbol of a symbol library panel (`name`: its name in `library`): the canvas adds it to the /// document's Symbols and places an instance where it is dropped (`symbol.addFromLibrary` with /// `place`). @@ -48,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/labels.rs b/crates/ui-egui/src/widgets/labels.rs index 9843ffbf44..d7c0d9813d 100644 --- a/crates/ui-egui/src/widgets/labels.rs +++ b/crates/ui-egui/src/widgets/labels.rs @@ -144,6 +144,14 @@ pub fn field_label(ui: &mut Ui, text: impl Into) -> Response { resp } +/// A field's label (`text` as given) that a click follows to a panel ([`scrub::panel_label`]): +/// before a numeric field it scrubs the field and names it. +pub fn field_panel_label(ui: &mut Ui, text: egui::RichText) -> Response { + let resp = scrub::panel_label(ui, text); + remember_next_label(ui, resp.id); + resp +} + /// [`dim_label`] for a name that is user or file data (a swatch, style, artboard or font name): /// shown as it is, never translated. pub fn dim_name(ui: &mut Ui, text: &str) -> Response { diff --git a/crates/ui-egui/src/widgets/look_tests.rs b/crates/ui-egui/src/widgets/look_tests.rs index 274861386b..0b89811929 100644 --- a/crates/ui-egui/src/widgets/look_tests.rs +++ b/crates/ui-egui/src/widgets/look_tests.rs @@ -421,7 +421,7 @@ fn a_popover_stays_open_for_a_click_on_its_anchor_or_during_a_panel_drag() { shown.get() }; let far = Some(pos2(500.0, 350.0)); - let panel_drag = || Some(PanelDrag::Symbol("s".into())); + let panel_drag = || Some(PanelDrag::Symbol { document: 1, name: "s".into() }); // Whether it is open after: a click elsewhere; a click on its anchor that doesn't toggle it; // a panel drag released elsewhere. let open = [open_after_click(far, None), open_after_click(None, None), open_after_click(far, panel_drag())]; @@ -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/control-protocol.md b/docs/control-protocol.md index 7eba21351a..e3d6636c3e 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -131,7 +131,10 @@ the two can still win that race. Swatch editors: `engine.execute` with `ui.swatchOptions {name}` opens the `swatchOptions` dialog for a colour swatch (fields `name`, `spot`, `global`, `mode`: `gray`/`rgb`/`hsb`/`lab`/`cmyk`/`web`, `color`: `"#rrggbb"` or a colour object, `preview`), which previews on the canvas while open; `ui.dialog.confirm` applies it with `swatch.edit` as one undo -step and `ui.dialog.cancel` rolls the preview back. For a gradient swatch the dialog has `name` only (it shows the +step and `ui.dialog.cancel` rolls the preview back. Under the colour it shows the out-of-gamut warning (in RGB, HSB +and Lab) and the out-of-web-color warning (in every mode but `web`); a click on one sets `color` to the correction +and `mode` to `cmyk` for the gamut correction, or to `rgb` for a web correction of a `gray`, `lab` or `cmyk` colour. +The warnings are not fields: set `color` and `mode` to apply a correction from a script. For a gradient swatch the dialog has `name` only (it shows the gradient) and OK renames it; pattern swatches open pattern editing instead. Dropping a gradient (or colour) on a swatch of its kind in the Swatches panel with Alt held replaces it (`swatch.edit {name, paint}`), unless that is a tint swatch. A swatch dragged from the panel with Alt held also replaces the swatch of its kind it is dropped on, @@ -601,6 +604,9 @@ Width Point Edit: double-clicking a width point with the Width tool, or `ui.widt `widthPoint` dialog (fields `id`, `index`, `t`, `side1` and `side2`: the left and right widths in points, `linked`, `adjustAdjoining`). `ui.dialog.confirm` runs `stroke.widthPoint.set` with them; `ui.dialog.set {field: "discard", value: true}` then confirm (the Delete button) removes the point with `stroke.widthPoint.remove`. +Either half of a discontinuous point opens both: `index` is the incoming half, and `outIndex`, `outSide1`, `outSide2` +and `outLinked` hold the outgoing half; `single` (`""`, `"incoming"` or `"outgoing"`) is Single Width Only. Confirm +sets both halves in one `stroke.widthPoint.set` (one undo step), and Delete removes both. Corners: double-clicking a Live Corners widget with the Selection or Direct Selection tool, or `ui.corners {id?, corners?}`, opens the `corners` dialog for a path's corners (the Direct-Selected ones, else every corner; fields `id`, @@ -971,7 +977,11 @@ Halftone… (`engine.execute {command: "ui.menuDialog", params: {command: "objec Tool options last: `tool.setOption {key, value}` or `{values: {…}}` (and `tool` to set another tool's) sets them, and the options a tool keeps (Liquify brush and tool options, Mirror & Cut, Puppet Warp, Symbolism, drawing tools) stay when you switch tools or documents and are saved with the preferences. The Liquify tools share their Global Brush -Dimensions (`width`, `height`, `angle`, `intensity`). +Dimensions (`width`, `height`, `angle`, `intensity`). `{}` reads the options and sets nothing; parameters that are +not an object are an error. Every option given is checked before any is set: an option the tool doesn't have, a value +of the wrong type, a number outside the tool's range or an unknown choice is an error that names the tool and the option +(``tool `smooth`: `fidelity` must be a number from 0.05 to 100``), and no option, preference or undo step changes. +The Live Paint tools' `width` and the Shape Builder's `gapLength` are set to the nearest end of their range instead. Perspective grid: View → Perspective Grid → Define Grid… (`ui.perspectiveGridDialog`) opens the `perspectiveGrid` dialog prefilled from the grid. Its fields are those of `perspective.grid.define` (`kind`, `units`, `scale`, diff --git a/docs/effects-parity.md b/docs/effects-parity.md index b797dcfd45..d92dc159f7 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, and wrapped around Revolve's side ([three-d.md](three-d.md#graphics)); no base materials, graphics on Inflate or 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, and wrapped around Extrude & Bevel's walls and bevels and around Revolve's side ([three-d.md](three-d.md#graphics)); no base materials, graphics on Inflate, or ray tracing | | 3D (Classic): Extrude & Bevel, Revolve, Rotate | Extrude & Bevel (Classic) initial: live, round seam joins, Extrude Depth, Cap, five original bevel shapes with Height and Bevel Extent In or Out, Position presets and rotation gizmo, Perspective, Wireframe, No Shading, Diffuse and Plastic surfaces with one to ten lights, Light Intensity, Ambient Light, Highlight Intensity and Size, Blend Steps, Black, Custom, Black Overprint or no Shading Color ([Black Overprint](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=188)), Draw Hidden Faces ([create 3D objects](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/create-3d-objects.html)); Revolve (Classic) initial: live, round seam joins, Angle, Cap, Offset from the left or right edge, Position presets and rotation gizmo, Perspective, the same four surfaces, lights, highlight, Blend Steps and Shading Color, groups and layers revolved about one shared axis (same page); Rotate (Classic) initial: live, round seam joins, every fill and stroke turned as one plane, Position presets and rotation gizmo, Perspective, No Shading and Diffuse surfaces with lights, Ambient Light, Blend Steps and Shading Color ([rotate objects in 3D](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/rotate-objects-in-3d.html)); Preserve Spot Colors in all three, unavailable with a Custom Shading Color ([Preserve Spot Color](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=260)); all three: a lighting sphere on the Lighting tab whose lights drag, move to the back or front, and are added at the front center or deleted down to one ([lighting options](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=272)); all three: the track cube (face, edge, Shift and ring drags, keyboard steps; [three-d.md](three-d.md#track-cube)); Map Art: 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 e1f2b735f8..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). @@ -300,7 +300,7 @@ private editing data. VectorCraft: The app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping (several clipping paths in a clipping group, a layer or an opacity mask's art clip to their intersection, and a compound path of clipping paths stays one clip; a filled clipping path keeps its fill, which paints under the art it clips, except the path of a mask that covers several layers, whose fill is read as a path of its own in the layer that holds the mask's path, and a compound clipping path whose subpaths paint differently, whose filled subpaths are read as a compound path of their own under the art it clips; clipping paths that would nest the art past the document's 32 levels stop the editing data from being read: #5789), object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint; a stroke of width 0, `0 w`, on a path, a gradient-filled path, legacy type or in an art style comes in as a 0.25 pt hairline, as from PDF: #1671), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), gradient and pattern names in the file up to their first newline (a name that another swatch, or a gradient or pattern defined earlier, already has is numbered "Sky 2"; a name without a newline is kept, and when another swatch has it, the pattern's swatch, or a named color sharing a gradient or pattern swatch's name, is numbered the same way), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), with the folder the file keeps relative to the document's, where the link is looked for when its path is gone, placed PDF and `.ai` pages as placed documents of the [page and Crop to box](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-other-file-types/adobe-pdf-placement-options.html) their dictionary names (`AI11 PlacedPDFPageIndex`, `AI11 PlacedPDFCropTo`; a value VectorCraft doesn't read, or a binding to an image variable, leaves a linked image), guides, and every artboard where it is, with its center mark, cross hairs, video safe areas and video ruler pixel aspect ratio. VectorCraft reads `CropAreaActive`, an `/Int` in the dictionary that holds the artboard array, as the index of the active artboard in that array, and the file opens with that artboard active; without it, or when it names no artboard that opens, the first artboard is active. It also reads the Document Raster Effects Settings (resolution, color model, background, anti-alias, clipping mask, Add Around Object and Preserve Spot Colors), the author from the header's `%%For` (an EPS's own header when the editing data's has none), swatches for the header's `%%CMYKCustomColor` and `%%RGBCustomColor` colors that the document has none of, and `%%TemplateBox` in older files; a setting with a value of another type or out of range keeps its default. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile on a Stroke Offset stroke or written as each side's widths) with Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners, Scribble, Offset Path, Outline Object, Outline Stroke, Convert to Shape, Tweak (only when it moves nothing), Pucker & Bloat at 0 or Bas Relief (read from its settings block: [raster effects reference](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/raster-effects-reference.html), [layered image file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), [scripting the filter gallery](https://community.adobe.com/questions-712/scripting-support-for-the-filter-gallery-1064646)) comes in as itself with them and their saved settings. A path, compound path or group (not a clipping group) whose only effect is Transform (not with copies or Random) or a Free Distort whose corners make a parallelogram comes in as itself with it too, when neither it nor anything in it paints with a gradient or pattern and everything in it is a path, compound path or group with no opacity mask and no effects of its own; Transform that scales, rotates or reflects needs nothing in it to be stroked and, with Transform Objects on, no guide in it that reaches past the rest of its art (hidden members count as art), and a Free Distort that moves a corner of a group needs no guide in the group that reaches past the rest of its art. Twist as the only effect is read the same way when nothing in the object is stroked: up to 180° either way (a limit VectorCraft sets) on a path or compound path whose segments are all straight, except a compound path with a guide member that reaches past its other members at an angle other than 0°, and up to 90° either way (a limit VectorCraft sets) on another path, compound path or group with no guide in it. One with more, other effects (Zig Zag, a Pucker & Bloat of another amount, a Free Distort with other corners), an effect setting that is not read (an unknown key, a missing or out-of-range value, a Scribble with a color of its own), a variable-width stroke with one centered width array, dashes aligned to corners, a brush other than a Calligraphic or Art one, a Calligraphic brush with settings of its own, an entry that isn't read, a variable width or an angle that follows the path, a path followed by samples of the pen (`(…) Xt n XD`) whose Calligraphic brush varies with the pen, or an Art brush other than the ones described next comes in as its drawn look (a group named after it). Objects in a symbol defined before the file's art styles section, as newer files write it, take the same styles as the layers' objects. A path with a Calligraphic brush otherwise comes in as the path, the brush on its stroke at the stroke's weight, which scales the brush (#372), and so does a path with an Art brush, whose weight scales the art across the path, when all of these hold: the brush is in Tints or None, at a fixed width from 1% to 1,000%, stretched to the path or stretched between guides that leave art between them, flipped along or across or not ([Art brush options](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf), printed page 193), with `Spacing` 0, `Adjustment` 1 and `FoldAdjustment` 1 (VectorCraft's own reading of these numbers; a brush that scales its art proportionately comes into the Brushes panel with that option, and its paths keep their drawn look); the path's settings are the brush's own (apart from the lowest and highest width of a fixed width and the guides' lengths without Stretch Between Guides, which don't draw), with no entry that isn't read, no variable width and no effects; a stroke in Tints isn't a swatch; and the art is paths, compound paths and groups in solid fills, with no strokes, masks or effects, and has some length along the path. A stroke takes the brush the Brushes panel keeps under its name, and one whose name the panel doesn't keep comes in as its drawn look. Type with an Art brush keeps its drawn look under the type. A Calligraphic brush's Pressure, Tilt, Bearing and Rotation come in as those channels (a 6D Art Pen's brushes vary with the pressure, the bearing and the barrel's rotation); its Stylus Wheel varies at random. The file's Calligraphic, Scatter, Art and Bristle brushes replace the default ones in the Brushes panel, in the file's order, also when the file comes in as its PDF part (a brush library has no layers); pattern brushes and brushes it can't read are left out with a note. When the file opens from its layers, the spot colors in the art of each brush that comes in become swatches, and that art's colors count toward the document's color mode, as a pattern's do. The swatches take at most 20,000 color names in all across the brush art, and each brush-art section keeps at most 20,000 names. Each name keeps its first definition, with the color operators' names before the gradient stops' names. A spot color past those limits makes no swatch, and its color still counts toward the color mode. A spot color that the page's art, a pattern or a symbol also defines keeps the value defined there. Type keeps its art style as a live appearance whatever its stack (an Art brush aside), so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Outline Object, Outline Stroke, Transform (with copies, Transform Objects, Transform Patterns and Scale Strokes & Effects; not with Random), Free Distort, Pucker & Bloat, Twist, Zig Zag, Tweak (only when it moves nothing, the file holding none of its random outline), Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners, Scribble, Gaussian Blur, Bas Relief (its detail, smoothness and light direction from its settings block, or the effect's defaults when the style holds no settings block; a settings block that isn't read keeps the drawn look) and Convert to Shape, and a style with others, or with an effect setting that isn't read, keeps the type's drawn look. Convert to Shape keeps its Rectangle, Rounded Rectangle or Ellipse, its Absolute or Relative size (a relative size in the file is added to each side) and its corner radius; a relative Ellipse, or a setting that isn't read, keeps the drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and its stroke, and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an EPS with editing data from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); area type keeps its frame's Area Type Options rows and columns, the gutter between rows and the gutter between columns, and its first baseline (Fixed, Cap Height, Leading or x Height) with its minimum; type on a path keeps its frame's Type on a Path effect, Align to Path and Flip (a frame whose options set key 6 to true keeps their defaults), and the first frame's Spacing is fitted from the file's layout, not read from the dialog's value; the distance from the path under Align to Path is measured for each character at its size and vertical scale (in vertical type, its horizontal scale), from the top of its font's em box (Ascender), half the height of the top of its font's H (Center) or the bottom of its font's bounding box (Descender); the fit under Gravity does not reproduce the file's layout, and its glyphs can lie up to 7.4 pt from the positions the file keeps; the page's drawing of it (often in pieces) is left out. Vertical type keeps its orientation, its columns from right to left, and a run set to Tate-chu-yoko keeps that setting. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Text wrap is read too: an object whose dictionary has the wrap options (offset and Invert Wrap), or any graphic of a legacy wraparound group (`*w` … `*W`, before or after its type, with no offset), is a wrap object, and area type below it in its layer flows around it when the file opens, threaded type included (#2763). Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). In a PDF saved with some of its artboards, the type on each page after the first goes to an artboard of that page's size after the previous page's artboard, and only to one that leaves an artboard for each later page; the first page's artboard also leaves one for each later page. When several artboards fit a later page, VectorCraft takes the one whose art draws most like the page, and compares at most 16 artboards for all the later pages together. Symbols are read into the Symbols panel, in the file's symbol list order, with their art, their registration point and the instances in their art, and their instances come in live with their matrix, name, hide, lock, opacity, blending mode, isolation, knockout and opacity mask; a symbol whose art isn't read whole (type, placed files, an image it leaves out or anything else it doesn't read) isn't kept. A file that comes in as its page or PDF part because its editing data has no layers (a symbol library), or because its layers can't be read or used (any of the cases below), gets the symbols its editing data defines before its first layer, in the symbol list's order, while its page art stays as the page draws it. Instances of symbols it can't read, instances with appearance changes of their own (a dynamic symbol's), pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards or lies on an artboard that has no page, when no page art lies inside its box, when that page art is inside a page group with a clip, mask, transparency or appearance, when the object holds a frame of threaded type, when the page art uses a pattern, image or swatch that the page lacks or that differs from the editing data's, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). A `.ai` is not compared with its page, and its PDF part is not imported, when its text document makes the type of every text object (at least one shows, and none is drawn by the appearance of the layer or group it is in), no object is unread, no placed file has a second placement, no live envelope keeps its drawn art, it declares no large canvas, and its artboards are its pages' trim boxes one for one, in points or in the first page's `UserUnit`: it opens from its layers, with the bleed of its pages' bleed boxes. When they differ because some objects draw differently (an object in another color, or one that only one of them draws), each top-level object of the layers that holds such a difference comes in as a group of the page's objects inside its box and the layers stay, with a warning that names the layer or sublayer of each such object as the Layers panel shows it (`` for one without a name) and how many came in from it; an export or Save As to the file's own path then needs `acknowledgeLoss: true`, and a wrap object replaced this way keeps its wrap options. The file still comes in as its page when only edges or type differ, when a difference lies outside every top-level object, when more than half of the top-level objects or more than 64 hold one, when such an object is or holds type or holds a wrap object inside a group, when the page's type of a text object that stays lies inside such an object's box, when the page's art can't replace such an object for one of the reasons above for an unread object, when matching the differences to the objects would take too much work, or when the result still differs from the page. `editingData: "always"` keeps the objects as read, and placed files at the other point their data gives are tried as well. An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so live objects that only the editing data holds arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (the PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068); the page of the artboard `CropAreaActive` names is then the active artboard. A `.ai` whose editing data has artboards but no layers also opens on that page under the same check, and its pages stay where they are. A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. A run of type in the editing data whose baseline direction is 1 opens with Standard Vertical Roman Alignment (https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html) on, which is VectorCraft's own mapping: its half-width characters stand upright in vertical type, and horizontal type keeps the mark with no change to its layout. A run whose baseline direction is 2 or 3 (Tate-chu-yoko), or that names none in the run, its character style or the document's defaults, opens with it off. The scripting reference lists 1, 2 and 3 as the Standard, vertical rotated and Tate-chu-yoko baseline directions (https://web.archive.org/web/20170621180804/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20VBScript%20Reference.pdf, page 256). -A Scatter brush in the editing data whose last 15 numbers start with 1 comes into the Brushes panel in Tints. Each brush art section is read without its frame: an unnamed, unpainted rectangle with no settings of its own at the art's bounds (within 1/1000 pt), closed, or open with its first corner again at the end. A wider frame stays in the art, and an art group with a state or look of its own (hidden, locked, isolated, knockout, an opacity, a blend mode, a name, a mask, a note or an appearance) stays a group. +A Scatter brush in the editing data whose last 15 numbers start with 1 comes into the Brushes panel in Tints. A Scatter brush's art comes in turned over from its section, as an Art brush's does: in each copy the side of the section with y up goes down the page before the copy's rotation, and the writer writes the art back the same way. Each brush art section is read without its frame: an unnamed, unpainted rectangle with no settings of its own at the art's bounds (within 1/1000 pt), closed, or open with its first corner again at the end. A wider frame stays in the art, and an art group with a state or look of its own (hidden, locked, isolated, knockout, an opacity, a blend mode, a name, a mask, a note or an appearance) stays a group. An object in a pattern's art or in a brush's art takes the file's art styles in the same way as an object on a layer: with a style VectorCraft reads, it comes in as itself with its effects live, not as the look it draws. An object in a pattern's art with a style in the file's style list keeps that graphic style's id, as does an object in an opacity mask's art. An art styles section inside a symbol's, a pattern's or a brush's art is skipped. @@ -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`) | 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 96a94b325c..304535dacb 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,8 @@ # 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. ## Feature submission evidence @@ -34,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). | @@ -120,6 +123,8 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall macOS cursor delivery (#2292) is narrowed to a native host adapter using the existing artwork and aligned 1×/2× representations. Headless tests cover visible fallbacks, preparation and ownership; native focus/menu/handback timing, mixed displays, Spotlight and full-screen Spaces remain open validation work (see [hardware parity](hardware-parity.md)). This does not close the interaction-fidelity gap or change its score/estimate. +- **Selection fill eligibility (#6625):** Path and compound-path interiors use any enabled non-None fill row (#6625). A lower visible fill remains selectable beneath a top None row in the same object; hidden-only and true-None interiors miss. Zero-opacity fills remain selectable. Original CPU-render and document-hit regressions in `crates/engine/tests/path_fill_hits.rs` cover seven Path and five Compound cases, including stroke edges, geometric outlines, Outline/path-only modes and compound holes. Hidden-fill and no-fill stroked paths must respect butt, round and square caps and bevel, round and miter joins. Focused cap/join CPU regressions passed. Scores and estimates unchanged. + - **Panel collapse controls (#5925, in part):** The small » in a floating tab-group header moves that group into the side icon rail, reusing the existing rail or creating one. An opened rail panel has the same control to fold its flyout back into the rail, including after a tab switch. Both controls preserve the tab group and its menu; other floating groups and full-width docked headers stay as they were. Pointer regressions in `crates/ui-egui/src/panel_docking/tests.rs` cover grouped tabs, reopening, separate groups, a missing rail, the menu and flyout closure after switching tabs; `native_tests.rs` covers the native-window click and removal of the empty palette. Scores and estimates unchanged. - **Done:** Distance Guides ([public page](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/use-distance-guides-for-accurate-placement.html)): with Smart Guides on and something selected, the Selection tool with Alt/Option held over another object shows the horizontal and vertical distances between them, and over an empty part of an artboard the selection's distances from its four edges, labelled in the General unit; Preferences › Smart Guides › Invoke Distance Guides turns them off. Hover only, as documented: not while moving or nudging. No entry closed; estimates unchanged. @@ -865,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) @@ -911,6 +916,7 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv | 2026-11-12 | minor | 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 (the seams of Revolve and of colored lights, and 3D (Classic) Wireframe edges, were already round): no thorns on edge-on facets, and facets with no neighbour now have rounded convex corners ([three-d.md](three-d.md#seams)). Scores and estimates unchanged. | | 2026-11-15 | minor | G12: Swatches item menus validated in all five views: 39 focused tests passed, regression fails without the menu hooks, rendered list/thumbnail layouts inspected, and fresh local deep CodeRabbit review found zero issues. Full workspace CI passed on Linux/WSL on the merged branch (all 13 gates), including the test-helper correction for the upstream compile error tracked in #7727; native Windows full CI has two unchanged engine-test failures. Scores and estimates unchanged. | | 2026-11-12 | minor | Explicit editing-data import keeps a single artboard beyond a capped 14,400 pt PDF page (#6865), with a warning; automatic mode stays unchanged. Scores and estimates unchanged. | +| 2026-11-12 | minor | #6625 cap/join follow-up: hidden-fill and no-fill stroke hits must respect their cap/join geometry; focused CPU regressions passed. Existing fill-stack evidence, scores and estimates unchanged. | | 2026-11-09 | minor | G4 review (#6084): positional variants no supported feature draws can be applied as glyph choices in both Glyphs views; unlisted glyphs still respect name ownership. OpenType style options keep only a valid last on-value when enabling a set. Existing contextual/ligature lookup and unsupported-feature gaps remain; estimate unchanged. | | 2026-11-07 | minor | G4: the Glyphs panel's Alternates for Current Selection applies the OpenType feature that draws a variant to that letter alone (`salt=2`; the style commands take `tag=N`; runs that differ only in their features shape as one piece of text), so an Arabic word stays joined, and Show › Entire Font lists the unencoded glyphs (#5514). Estimate unchanged. | | 2026-11-12 | minor | G11: numeric fields keep the caret when a focus click is released more than 1 pt from its press; a tap within 1 pt still selects the whole value (#6659, follow-up to #1326); short-drag and jitter-tap regressions in `tests/numfields.rs`; estimates unchanged. | @@ -921,6 +927,7 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv | 2026-11-11 | minor | G5: built-in Skill Icons symbol library (Attack, Defend, Heal, Buff, Ult); Missing trimmed; estimate 6–16 → 5–15 h; MCP Symbol libraries list Skill Icons. | | 2026-11-11 | minor | G5: built-in Status Effects graphic style library (Poison Tint, Freeze Edge, Burn Aura, Stun Pulse, Stealth Fade, Shield Buff); Missing trimmed; estimate 7–17 → 6–16 h; MCP docs list UI Frames and Map Markers under Symbol libraries. | | 2026-11-11 | minor | G5: built-in Inventory Icons symbol library (Sword, Shield, Potion, Key, Gem; no default 9-slice); Missing trimmed; estimate 8–18 → 7–17 h. | +| 2026-11-11 | minor | #6625: path and compound-path interior hits follow enabled non-None fill rows, including lower fills beneath a top None row; hidden-only interiors miss; zero-opacity fills remain selectable. Scores and estimates unchanged. | | 2026-11-10 | minor | G6: MCP catalogue (#6460): headless lists `UI_COMMANDS` (`ui: true`), eight prompts, effect vs command ids, 33 tools, commands/reference; estimate unchanged. | | 2026-11-10 | minor | G4 type: Edit › Edit Custom Dictionary… adds, deletes and changes the custom dictionary's words, #4936; the Check Spelling dialog remains; scores and estimates unchanged. | | 2026-11-10 | minor | Tidy-up, no content change: in Feature submission evidence, a stray table row and two "PR #NNNN revision" notes move into Feature revisions, the three "Feature evidence last updated" lines become one, the duplicate Flyout update note goes (its row stays), and eight reconciliation rows become two. Scores and estimates unchanged. | diff --git a/docs/mcp.md b/docs/mcp.md index 00f289af50..4aead3b4ce 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` @@ -711,13 +721,13 @@ ends the wait, so the sampler can be shown again. The BSDs and headless sessions | `open_file` | `{path, importer?, params?}` | Opens any readable file as a new active document: `.vectorcraft`/`.drawcraft`, `.vctemplate`, `.svg`/`.svgz`, `.pdf`/`.ai`, `.ait`, `.eps`/`.epsf`, `.ps`, `.dxf`, `.emf`, `.wmf`, PICT (`.pct`/`.pic`/`.pict`, and a version 2 picture of any extension), HP-GL (`.plt`/`.hpgl`/`.hgl`/`.hpg`, and a file of an extension no other format reads that starts with plotter instructions), PNG (`.png`/`.pns`), JPEG, GIF, WebP, TIFF, BMP (`.bmp`/`.dib`/`.rle`), Targa (`.tga`/`.vda`/`.icb`/`.vst`), PCX, Pixar (`.pxr`), JPEG 2000 (`.jpf`/`.jpx`/`.jp2`/`.j2k`/`.j2c`/`.jpc`), HEIC/HEIF (`.heic`/`.heif`), JPEG XL (`.jxl`), PSD (`.psd`/`.pdd`)/PSB (an image opens as a document of its pixel size; a PSD or PSB file with its layers as layers, or as its merged image through `run_command document.open` with `layers: false`; a JPEG XL file as its first frame). Templates (`.vctemplate`, `.ait`) open as a new untitled document. PDF, `.ai` and SVG files saved with Preserve Editing reopen as the document they carry. The reply is `document.open`'s: its `warnings` say what didn't come in as it was (an EPS whose PostScript can't be read opens as its preview, and the warning names the PostScript error, the operator and the procedure). A file of an extension only an installed importer plug-in lists opens with that importer ([Plug-ins](#plug-ins)); `importer: "plugin."` opens the file with the importer it names, which must list the file's extension, also one a built-in format reads (in the app, as File › Open With does), and `params` gives that importer's parameters (their defaults when omitted). `run_command document.formats` lists the formats. | | `save_file` | `{path?, compress?, version?, preview?, precision?, options?}` | Runs `document.save`: the document's own file in its own format (native `.vectorcraft` unless it was opened from or saved as SVG, PDF or a restorable `.ai`; then `warnings` say what that format loses). A path's extension picks the format (`.vectorcraft`, `.vctemplate`, `.pdf`, `.svg`, `.svgz`, `.ai`: a PDF carrying the native document, which reopens editable; `.eps`: by default one file whose bounding box fits the visible art, the first artboard when no art shows; `options.useArtboards: true` makes the chosen artboard the page and, with two or more chosen, the file at the path is the central file of the visible art and each artboard is also written to `_.eps` beside it, listed in the reply's `files`). For a native file, `compress: true` gzips it (default: the `useCompression` preference, Preferences › File Handling › Use Compression), `version` (1 to 4) writes it for an older VectorCraft (1 and 2 are never compressed, and `version: 2` with `compress: true` is an error), `preview: true` embeds a PNG of the first artboard, and `precision` (0 to 9) rounds path anchors and handles to that many decimal places for that save only (colors, transforms and type stay exact). `options` passes the format's save options as `run_command document.formats` lists them. When `compress`, `version`, `preview` or `precision` is given both at the top level and in `options` with different values, the call is an error (`` `compress: true` and `options.compress: false` disagree: give the option once ``) and nothing is written. A key in `options` that no save format takes is an error, and nothing is written (see Parameter keys). The save drops each option the written format doesn't read. The reply's `warnings` then name each such option given (for example `` `compress` was not used: SVG files don't read it `` for an `.svg` path, and `` `options.preview` was not used: … `` for a key in `options`; a PDF-compatible `.ai` file reads `compress` but not `version`, `preview`, `precision`, `outlineText`, `hiddenObjects`, `transparentImages` or `preserveEditing`, and a legacy `.ai` file reads only its own options). For a `.ai` file, these warnings name the kind of `.ai` written: a legacy .ai (version 7) for `aiVersion: "7"`, a non-PDF-compatible .ai for `pdfCompatible: false`, and a PDF-compatible .ai otherwise, including a save that reuses the options the document was last saved with. `run_command document.save` and the other save commands refuse any option given beside the path and in `options` with different values, and give the same warnings for each key given beside the path or in `options` that the file doesn't read. The headless session and the app receive the same `app.save` params, and the app is also sent `wait: true`: the call returns once the file is written, or with the error (such as a path outside the write root), even with Background Save on. When the save asks first (the question before replacing a file that opened with losses, or on macOS and Linux the file dialog for an untitled document without `path`), the reply is `{pending}` or `"cancelled"` as before, and the save that runs after the answer uses the Background Save preference. Location refusals return `READ_ONLY_LOCATION: ` without a fallback panel for automation; see [Save location errors](#save-location-errors). | | `export` | `{path?, format?, scale?, artboard?, range?, selection?, outlineText?, options?}` | `svg`, `svgz`, `pdf`, `ai` (the PDF-compatible `.ai` that Save writes, which carries the document when every artboard is written in order), `eps`, `dxf`, `emf`, `wmf`, `hpgl` (a `.plt` plot file for plotters and cutters), `png`, `jpg`, `webp`, `gif`, `png8` (an indexed `.png`), `tiff`, `bmp`, `tga`, `psd` (layered), `txt` (the document's text), `vectorcraft` or `template` (a native template). The tool's `format` enum and `document.formats` list them, generated from the engine's format table. When `format` is omitted, it comes from the path's extension. PDF and `.ai` write one page per artboard: all of them, or `artboard` (0-based) / `range` (`"1-3, 5"`, 1-based). SVG and SVGZ write one file per chosen artboard. EPS writes one file of the visible art; with `artboard`, `range`, `options.artboards` or `options: {"useArtboards": true}` it writes one file per chosen artboard, after a central file of the visible art when there are two or more, and `useArtboards: false` keeps the one file. Rasters, DXF, EMF, WMF and HP-GL write one artboard, or one file per chosen artboard with `options: {"useArtboards": true}`. Rasters also take `options: {"rect": [x, y, width, height]}` (page points, y down): that area of the page at the given `ppi`/`scale`, without an artboard and without changing the document; it is refused with `artboard`, `artboards`, `range` or `useArtboards`, with a non-positive or non-finite size, and for non-raster formats. `options` carries more format options (e.g. `{"quality": 80}` for JPEG). `selection: true` exports the selected objects cropped to their bounds (the reply adds their `bounds`, and reports `format` and the encoder's `warnings` as a whole-document export does); `outlineText: true` writes SVG text as paths. Template layers are left out, live effects are kept, and exporting `vectorcraft` never changes the document's path. Without `path` the bytes come back as `dataBase64`. Both backends run the same `document.export` call. | -| `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` (`rainbow`, `skew`, `3dRibbon`, `stairStep`, `gravity`; SVG export writes type on a path with any effect other than `rainbow` as outlines, with a warning); `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. | +| `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. `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. | +| `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. | For example, create editable Japanese area type with the engine's vertical writing mode: @@ -839,6 +849,9 @@ stroke instead of the whole object: `run_command effect.apply {"effect": "path.o `effect.remove`, `effect.setParams` (`visible` toggles one) and `effect.duplicate` address that item's effects; `apply_effect` uses the active item. `effect.list` reports each object's item effects under `applied[].items`. +`distort.twist` keeps anchors on its outer circle fixed. Their handles follow the tangent of the +rotation inside that circle, including for positive and negative angles. + On a path directly inside a graph series, `appearance.setItem`, `appearance.addFill`, `appearance.addStroke`, `appearance.removeItem`, `appearance.moveItem`, `appearance.duplicateItem`, `appearance.clear`, `appearance.reduceToBasic`, `appearance.showAllHidden`, `appearance.transfer`, `appearance.copyFrom`, `paint.default`, @@ -1117,7 +1130,9 @@ Color Themes (local only: no online service) keeps five-colour themes in the pre harmony rule makes from a base colour (base first; `name?` defaults to "Theme N", `replace: ""` overwrites that theme in place). `colorTheme.list` answers `{themes: [{name, colors: [hex], keys: [colour keys], rule?}]}`, `colorTheme.delete {name}` removes one and `colorTheme.addToSwatches {name}` adds one to the Swatches panel as a -colour group (one undo step). +colour group (one undo step). The Create tab's Set the current fill or stroke to the selected color button runs +`paint.setFill` (or `paint.setStroke` with the Stroke proxy in front) with the selected colour and `keepModel: true`; +a script does the same with those commands. ```json {"name":"run_command","arguments":{"command":"colorTheme.save","params":{"color":"#2266aa","rule":"splitComplementary","name":"Harbor"}}} @@ -1204,6 +1219,13 @@ styles and brushes. `color.removeProfile`, `view.proofSetup`, `view.proofColors`, `view.overprintPreview`, `view.separationsPreview` and `swatch.setSpot` reject a param of the wrong type, such as `"bpc": "no"`, `"on": 1`, `"to": 5` or `"colors": "#fff"`, and change nothing. Omitting a param or giving null keeps its default. +`view.separationsPreview {soloToggle: plate}` is the Separations panel's Alt-click on a plate's eye: it shows that +plate alone, and when that plate is already the only one of the active document's plates shown, it shows every +plate, spot plates included ([Print color separations](https://helpx.adobe.com/illustrator/using/printing-color-separations.html) +describes the second Alt-click or Option-click on the eye bringing every separation back, and the first one showing +that plate alone). A hidden plate, another plate while one shows alone, or any plate while none is shown becomes +the only plate shown; these cases are VectorCraft's own rules. `only` always shows just the named plate, so +repeating it changes nothing. Neither adds an undo step. The Separations panel's Assign rows (where Edit › Assign Profile… goes) act on the profile of the document's color mode: Don't Color Manage This Document runs `edit.assignProfile` with null for that model (no profile, so the colors show through the working space), Working RGB or Working CMYK with the working space's name (that profile stays @@ -1266,6 +1288,10 @@ Draw, look, export: {"name":"export","arguments":{"path":"/tmp/icon.png","range":"1-3","options":{"useArtboards":true}}} ``` +The desktop command `file.export.png` accepts `document.export` options. Without `path`, it asks for a destination +and opens PNG Options with supplied values such as `ppi`, `background`, `antiAlias`, and `interlaced` retained. +Omitted options use the dialog defaults. Nonpositive resolutions are rejected when the export is confirmed. + Export As goes through `options` too: for PNG, JPEG and WebP `useArtboards: true` writes one file per artboard (all, or `range`), named `-.`, and returns `{path, files}` (a PDF keeps them as pages of one file; an SVG writes one file per artboard of a `range`); `useArtboards: false` exports the bounds of the visible art with what @@ -1372,7 +1398,7 @@ the image at, and all paint that one image. A 16-bit PNG that is not resampled, recompressed or converted keeps its 16 bits a sample in PDF 1.5 and later files, and is written at 8 bits in PDF 1.3 and 1.4 files. CMYK images stay CMYK (DeviceCMYK, or ICC-based with the CMYK profile when colours are tagged, as in PDF/X-3 and -PDF/X-4): a CMYK JPEG neither resampled nor recompressed is written unchanged, and the others' ink amounts are +PDF/X-4, where an image in the output intent's profile is DeviceCMYK): a CMYK JPEG neither resampled nor recompressed is written unchanged except that its `ICC_PROFILE` segments are removed when `output.profiles` is `none` (except in PDF/A, and in PDF/X-3 and PDF/X-4 files that do not write CMYK colors as DeviceCMYK) and in PDF/X-3 and PDF/X-4 when they are the CMYK output intent's profile and CMYK colors are DeviceCMYK, and the others' ink amounts are resampled and compressed again (CMYK JPEG or ZIP). `output.conversion` converts them like CMYK colours: `destination` to another CMYK profile or to RGB, `preserveNumbers` (and PDF/X-1a) keeps their numbers in a CMYK destination. `document.pdfSettings` lists the options that differ from the preset and the warnings without writing a file. @@ -1474,9 +1500,11 @@ a layer named after the page (`Page 2`). A PDF-compatible `.ai` with `cropTo: "c when it opens as art. A page on its trim box shows its bleed box round the artboard, and the pages give the document their bleed; the artboards are then 36 pt apart plus the bleed on both sides. The document opens in CMYK when most of those pages are painted mostly in CMYK, unless `colorMode` names a mode. All the pages' objects share one copy of the file. The Links panel lists each -page, and `links.embed` makes a page editable art. +page, and `links.embed` makes a page editable art. The command's `linkPages` defaults to false; the dialog checks the +box when All is picked and clears it when Range is picked, for a file it can link, and `ui.dialog.set` of `allPages` +does the same. A box checked or cleared by hand keeps that state until the other of All and Range is picked. `document.open` refuses `linkPages` for a file that is not a PDF or a PDF-compatible `.ai`, for a file given as -`dataBase64` without a path, with a `password`, and with `textAs: "outlines"`, and rejects a `linkPages` that is not +`dataBase64` without a path, with a `password`, with `textAs: "outlines"` and for a file over 256 MB, and rejects a `linkPages` that is not true or false. Save then asks for a name. `document.open`, `file.place` and `document.pdfInfo` reject a `cropTo`, `crop`, `password`, `colorMode` or `textAs` that is not a string, and `document.pdfInfo` rejects a `thumbnailSize` that is not a number. The error names the param, @@ -1485,8 +1513,9 @@ Imported colours keep their model: DeviceCMYK and CMYK ICC colours stay CMYK (a file painted mostly in CMYK opens as a CMYK document), DeviceGray is Gray, and Separation and DeviceN inks become spot swatches the art links to at its tint (gradient stops too). CMYK images (DeviceCMYK, or ICC-based with four components) keep their ink amounts: a CMYK JPEG as it is, any other as a CMYK TIFF -(masked CMYK images, and ones with 1, 2 or 4 bits per sample, open in RGB with a warning). Placing a CMYK TIFF keeps it -CMYK too. +(masked CMYK images keep their inks, the mask coming in as an opacity mask; ones with 1, 2 or 4 bits per sample open in RGB with a warning). In a file with a CMYK +`/GTS_PDFX` output intent, a DeviceCMYK image carries the output intent's profile, except where it is drawn with a +`/DefaultCMYK` in the resources in scope. Placing a CMYK TIFF keeps it CMYK too. `colorMode: "rgb" | "cmyk"` opens any file in that mode instead, its colours converted as `file.documentColorMode` does (`grays` too): @@ -1836,8 +1865,8 @@ preferences (the folder the desktop app uses, so both see the same ones; `VECTOR `file.new`, `document.open`, `document.activate`, `file.close`, `file.revert`, `edit.undo`, `edit.redo` and a failed `command.batch` too; with none assigned, or no document open, the working spaces are. The `workingCmyk` target of `view.proofSetup` simulates the working CMYK space in such a document too. `color.convert`'s - `outOfGamut` and `deltaE`, `color.gamutCheck`, and the out-of-gamut warning of the Color panel and Color Picker - check against the assigned CMYK profile, else the working CMYK space; the warning updates when either changes. + `outOfGamut` and `deltaE`, `color.gamutCheck`, and the out-of-gamut warning of the Color panel, the Color Picker, + Swatch Options and New Swatch check against the assigned CMYK profile, else the working CMYK space; the warning updates when either changes. Not remembered: the document, anything else. Nothing is read or written when `VECTORCRAFT_NO_PREFS` is set, and a server confined with `--automation-read-root` or @@ -2298,6 +2327,11 @@ path to a value inside a list or an object, and the document and its undo histor → invalid parameters for `view.saved.edit`: `edits[0].delete` must be true or false, not 1 ``` +A refused step of a `command.batch` gives its command's error as it is. A refused step of an `action.batch` is named +by its place in `commands`, from 1, before its command's error: with `commands` of an Unlock All and the +`view.saved.new` above, the error is +``invalid parameters for `action.batch`: action step 2 (`view.saved.new`) failed: invalid parameters for `view.saved.new`: `zoom` must be a number > 0, not 0``. + A schema nests at most 16 lists and objects. A value that would go past that depth is refused with the same kind of parameter error, ``invalid parameters for ``: `` is nested too deeply``, where `` is the path to the value. A schema that is wrong in itself, such as one that nests past 16 levels or puts a list of ids or a point @@ -3422,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 @@ -3600,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 @@ -3616,9 +3689,19 @@ already walks Image Trace. Short agent entry points: art, where it is, snaps the art again after it is edited, and does not count instances in `select.object.notAlignedToPixelGrid`; `alignToPixelGrid` alone with the value the symbol already has adds no undo step), - `symbol.place {name?, x?, y?}`, `symbol.breakLink {ids?}` (the art keeps the instance's opacity mask and its bounding box, square after + `symbol.place {name?, x?, y?}`, `symbol.placeFromDocument {sourceDocument, name, x?, y?}` (an instance of a symbol + of another open document, as a symbol dragged from that document's Symbols panel onto the canvas places it: the + symbol, the symbols it nests and the resources they use are added as `edit.dropSelection` adds them, in the same + undo step, and a symbol with the same name but other art or Symbol Options is added under a free name; an error + 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 @@ -3743,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 @@ -4532,7 +4629,16 @@ A graphic style holds an appearance (fills, strokes, effects) plus opacity, blen object's, type its characters'). `graphicStyle.apply {name, ids?}` gives the objects the style and links them; `add: true` adds the style on top of the existing appearance instead. Linked objects stay linked while they keep the style's look: editing their appearance or transparency breaks the link, and `graphicStyle.redefine {name?, id?}` -updates only the objects still linked. The art of a column or marker design in a graph series is never linked: +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. +`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. @@ -4724,20 +4830,24 @@ 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) or Revolve (front only: its swept side), 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) or Revolve (front only: its swept +side), 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)). The graphics are the `graphics` parameter of `threeD.extrude`, `threeD.rotate` and `threeD.revolve`, which `effect.setParams` also 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 is VectorCraft's own rule. +how a graphic wraps around the side is VectorCraft's own rule. 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). @@ -5665,11 +5775,15 @@ and `layerRows`, the rows highlighted in the panel. layer, group or Intertwine group (on top of its contents), keeping their stacking order; `copy` (Alt-drag) moves copies. Layers go only in layers or at the top level and objects in layers, groups and Intertwine groups (see Intertwine for the members an Intertwine group takes; an object placed beside a top-level layer goes - inside it); a row never goes into itself or a row inside it, and a locked layer or group takes nothing. Dragging the + inside it); a row never goes into itself or a row inside it, and a locked layer or group takes nothing. With `copy`, + the target may be one of the rows copied: the copies go above or below it, as an Alt-drag onto a row's own row (or a + bottom layer's into the empty space under the list) places them, unless objects are copied with a top-level layer + that is the target, which would put them inside it (#8237). Dragging the selected-art square is `layer.move` with the selected objects. `node.move {id, parent?, index}` is the low-level form with the same nesting rules; unlike `layer.move`, it also moves a row into a locked layer or group. -- **Buttons**: `layer.new {name?, top?, below?, …options}` (above the current layer at its level; `top` with - Ctrl/Cmd; `below`, directly below the current layer at its level, with Ctrl/Cmd+Alt), +- **Buttons**: `layer.new {name?, top?, below?, …options}` (above the current layer at its level, or directly + below it in Draw Behind; `top` with Ctrl/Cmd; `below`, directly below the current layer at its level, with + Ctrl/Cmd+Alt; `top` and `below` apply in every drawing mode), `layer.newSublayer {parent?, bottom?, name?, …options}` (on top of the parent's contents; `bottom`, under them but above a clipping layer's clipping path, with Ctrl/Cmd+Alt; both refused while an opacity mask is edited), `layer.delete {ids?}` (rows with what they hold; the @@ -5678,7 +5792,9 @@ and `layerRows`, the rows highlighted in the panel. locked or nested art included, dialog `confirm` asks "Delete this layer and its artwork?" for one layer, else "Delete the selected items and their artwork?"; OK deletes the rows it asked about in that document, one undo step, and Cancel keeps them; an empty layer, a layer with only guides, and groups or objects alone are deleted at once), - `layer.locate {id?}` (highlights the selected object's row; the panel opens the rows around it) + `layer.locate {id?, layersOnly?}` (highlights the selected object's row; the panel opens the rows around it and + scrolls to it on every call, also when the row was already highlighted; `layersOnly: true`, which the panel sends while Show Layers Only is on, as Locate Layer, highlights the innermost + layer or sublayer holding the object instead, or a layer `id` itself, and returns `{id, objectId, ancestry}`) and `layer.clippingMask.toggle`. - **Panel menu**: `layer.duplicate {ids?}`, `layer.merge {ids?}` (into the layer highlighted last, keeping the stacking order), `layer.flatten {id?}` (every other visible layer's art into one layer; hidden layers are deleted, @@ -5690,7 +5806,16 @@ and `layerRows`, the rows highlighted in the panel. runs Hide or Lock Others for the row's layer, or Show or Unlock All when the others already are), `layer.pasteRemembersLayers`, `object.isolate {id?}` (a group, a layer or a single object, by default the first selected object; not type, not a hidden or locked object or one in a hidden or locked group or layer, not a guide path while Lock Guides is on, and - while a symbol is edited only the editing layer or art on it) / `object.exitIsolation`. Leaving an isolated Live + while a symbol is edited only the editing layer or art on it) / `object.exitIsolation {all?}`. With a sublayer + isolated, `object.exitIsolation` isolates its parent layer and selects the sublayer, so repeated calls go up one + layer at a time until the top-level layer is left, as the + [help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/isolate-objects.html) + describes for Exit Isolation Mode; the Layers panel menu item, the isolation bar's back arrow, the Control bar + button, the canvas context menu and a double-click outside the art run it this way. As VectorCraft's own rules, a + step up records no undo step, a hidden or locked parent layer is not isolated (the call leaves isolation mode), and + `all: true` (Esc, the top-level layer's crumb on the isolation bar) leaves isolation mode from a sublayer at any + depth; `all` must be true or false. While a symbol is edited, a group isolated in its art still goes back to the + symbol's layer first, with or without `all`. A sublayer's crumb on the isolation bar isolates that sublayer. Leaving an isolated Live Paint group (`object.exitIsolation`, or `object.isolate` on a level outside it) adds the paths, compound paths and groups of them drawn in it, shown and unlocked with everything in them, to the group as `livePaint.merge` does, in one undo step; type, images and other objects stay in it as they are, and with nothing drawn no undo step is @@ -6299,7 +6424,7 @@ The command refuses another mode, and a variation below 0 or past its range, and the Eraser's tip outline at the pointer takes the angle, roundness and size the pen gives while it erases, and the outline of the area a drag covers takes, at each step, the tip the pen's readings give halfway along it. A Random value shows as the value itself there, since the release draws it. -`tool.setOption {tool: "eraser"}` takes the same keys. +`tool.setOption {tool: "eraser"}` takes the same keys, with `sizeVariation` from 0 to 1000. `path.eraseRegion {rect: [x, y, width, height]}` takes a rectangle in place of `points` and erases everything inside it from the paths (selected, or all), as an Alt-drag with the Eraser does ([Eraser tool @@ -6347,7 +6472,10 @@ in `path.curvatureEdit`; `perpendicular` in `path.reshapeSegment`; and `keepSele `path.freehand` (and `brush.freehand`, which runs it) refuses a `style` other than "pencil" or "brush" with `style must be "pencil" or "brush"`, and an `end` of `extend` other than "start" or "end" with `extend end must be "start" or "end"`; the document does not change and no undo step is recorded. Left out or null, -`style` is "pencil" and the `end` of `extend` is "end". +`style` is "pencil" and the `end` of `extend` is "end". It refuses a `connect` without `extend` with +`connect needs extend`, and checks a `connect` given with `extend` (its `id`, a path other than the one extended with +an open end, and an `end` of "start" or "end") before a stroke of one point returns, so a bad `connect` is refused +there too and a `brush.freehand` call does not change the path's brush or the selection. A `pointer_gesture` with `mods: {cmd: true}` held at the press, with any tool but the selection tools (Command on macOS, Ctrl elsewhere), drags with the selection tool chosen last (`select_tool`), or Direct Selection with the Pen, @@ -6449,17 +6577,32 @@ slider (`ui.menuDialog {command: "object.path.smooth"}`, dialog `smoothSlider` w Auto-Smooth level, and the slider previews the result until `ui.dialog.confirm`; `ui.smoothAuto` moves the open slider back to the Auto-Smooth level. -## Circle through three points +## Circle through two or three points -`shape.circleThroughPoints {points?: [[x, y], [x, y], [x, y]]}` draws the circle whose edge passes through three -points, as a live ellipse with the current paint, and selects it. Without `points`, it uses the three selected anchor -points, from one path or several: anchor points selected with Direct Selection, or all the anchor points of a path -selected whole, such as a triangle. The ends of selected segments do not count. The result is `{id, cx, cy, radius}`, -and one undo removes the circle. The circle is not pixel-aligned, even while the document's -[Align New Objects to Pixel Grid](#align-new-objects-to-pixel-grid) is on, so it stays through the points. The command -returns an error and draws nothing when two points are the same or the three lie on one line (twice the triangle's area -at most 10⁻¹⁰ of its longest side squared), when `points` is not three pairs of numbers, and when `points` is left out -and the selection does not hold exactly three anchor points of paths. +`shape.circleThroughPoints {points?: [[x, y], [x, y]] or [[x, y], [x, y], [x, y]]}` draws the circle whose edge passes +through the points, as a live ellipse with the current paint, and selects it. Two points are the ends of a diameter. +Without `points`, it uses the two or three selected anchor points, from one path or several: anchor points selected with +Direct Selection, or all the anchor points of a path selected whole, such as a triangle. The ends of selected segments +do not count. The result is `{id, cx, cy, radius}`, and one undo removes the circle. The circle is not pixel-aligned, +even while the document's [Align New Objects to Pixel Grid](#align-new-objects-to-pixel-grid) is on, so it stays +through the points. The command returns an error and draws nothing when two points are the same or the three lie on +one line (twice the triangle's area at most 10⁻¹⁰ of its longest side squared), when the circle would reach past the +canvas (4,000,000 pt from the origin), when `points` is not two or three pairs of numbers, and when `points` is left +out and the selection does not hold two or three anchor points of paths. + +The Circle tool, after the Ellipse tool in its toolbar group, draws with this command. A drag from one point to +another, or a click on each, draws the circle with the two points as the ends of a diameter. A click on a first point, +then a press on a second point dragged to a third, draws the circle through the three. Shift keeps the second point at +45° steps from the first, measured from General › Constrain Angle. For a circle on two points, Alt rounds the diameter +to the nearest tick of the rulers at the current zoom, in the General unit (every 5 pt at 100% in points); the three +points of a circle through three are not rounded. Each point snaps to Smart Guides. Until +the release, the tool shows the circle as a dashed outline (solid once it is more than 50,000 screen points around) +with its points, a small cross at its center, a line from +the center to each point and, with Measurement Labels on, the diameter by the pointer. Three different points on one +line, or a circle past the canvas, show "Circle too large" by the pointer instead, and the release draws nothing. +Escape, a dropped press, and an edit, Undo or Redo made outside the tool drop the first point. A second press within 3 +screen points of the first point, or one that snaps to it, is a press on it: let go there (a double-click), it places no second point, and +dragged out, it draws the circle on the diameter it drags out. With the Ellipse tool, the first two Shift-clicks place points, and the third draws the circle through the three with this command. After two points the tool previews the circle through them and the pointer as a dashed outline. Once a @@ -6552,13 +6695,18 @@ The destination is any profile `edit.colorSettings` lists (default: the document for its colour mode). `profiles` (`all`, `destination`, or `taggedSource` for a document assigned profiles with `edit.assignProfile`) writes colours in ICC-based spaces with their profiles embedded: CMYK with the destination's or the document's CMYK profile, RGB as sRGB, grey with the sRGB tone curve (PDF/A, PDF/X-3 and PDF/X-4 files are -always tagged, whatever `profiles` says). A CMYK image that keeps its numbers carries the CMYK profile it embeds -with `all` and `taggedSource`, and in PDF/A, PDF/X-3 and PDF/X-4 unless `profiles` is `destination`; PDF/X-1a +always tagged, whatever `profiles` says). In PDF/X-3 and PDF/X-4 files, CMYK colors whose profile is the profile of a +CMYK output intent are written as DeviceCMYK, and the profile is embedded once, as the output intent's. With `none` and a CMYK output intent, PDF/X-3 and PDF/X-4 files write every CMYK color as DeviceCMYK +(unless colors are converted to a CMYK `destination` of another profile, which then tags them), and RGB and gray +colors stay tagged. A CMYK image that keeps its numbers carries the CMYK profile it embeds +with `all` and `taggedSource`, and in PDF/A, PDF/X-3 and PDF/X-4 unless `profiles` is `destination`, but not when +CMYK colors are DeviceCMYK and either its profile is the output intent's or `profiles` is `none` (a CMYK JPEG +then loses its `ICC_PROFILE` segments); PDF/X-1a images are always untagged CMYK. Left unset (the default; `"default"` unsets it over a preset, while `null` keeps the preset's value), `profiles` writes device colours and gray and RGB images keep the profiles they carry (not in PDF/X-1a). Set to `none`, it also writes every image without the profile it carries, and a JPEG kept as it is without its `ICC_PROFILE` segments, its other segments and compressed samples unchanged; PDF/A, PDF/X-3 and PDF/X-4 files keep -the profiles they tag images with. The Save PDF dialog lists the unset value as Default. `outputIntent` embeds a profile as the file's +the profiles they tag images with, except CMYK images when CMYK colors are DeviceCMYK. The Save PDF dialog lists the unset value as Default. `outputIntent` embeds a profile as the file's `/GTS_PDFX` output intent with `outputCondition`, `outputConditionId` and `registry`, and `trapped` sets `/Trapped` (PDF/A files keep their own output intent). Type is written as selectable, searchable text in embedded subset fonts with a ToUnicode map (fonts whose licence forbids embedding stay outlines, with a warning); `advanced: {outlineText: @@ -6620,6 +6768,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 @@ -6760,7 +6924,15 @@ 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. Each call is +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, +and a line that would reach past the coordinate limit (±4,000,000 pt), are errors that change no line. Each call is one undo step. `object.setLiveShape` returns a parameter error, and leaves the document and its undo history as they were, for a key @@ -6773,6 +6945,8 @@ 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}}} ``` ## Align to Artboard @@ -7029,8 +7203,14 @@ A null is read as a key left out. When a step fails on a file or data set, that place in the `commands` sent, from 1, counting the Open steps the batch skips: with `commands` of an Open, an Unlock All and an Align, a failed Align gives `` action step 3 (`object.align`) failed: `` and the reason. The batch's own opening of a source file, choosing of a data set and destination save, export or close give their errors without a -step number. This numbering is VectorCraft's own rule. A `prefs.import` step is refused before any file is opened, -with `` commands[1]: `prefs.import` runs on its own, not as a batch step `` (counted from 0, as for an unknown command). An action recorded in the Actions panel leaves the artboard out, +step number. This numbering is VectorCraft's own rule. Before any file is opened, `action.batch` refuses a step +without a command, with a command the engine does not have, with params its command refuses, or with +`command.batch`, `action.batch` (batches cannot nest) or `prefs.import`, and names it the same way, from 1: with +`commands` of an Unlock All and a `prefs.import`, the error is +``invalid parameters for `action.batch`: action step 2 (`prefs.import`) failed: `prefs.import` runs on its own, not as a batch step``. +Override Open skips `document.open` steps, and Override Save points `document.save` and `file.saveAs` steps at the +destination folder. `file.open` and `file.save` are the app's commands, not the engine's, so a step with one is +refused as an unknown command. An action recorded in the Actions panel leaves the artboard out, and its steps of these commands get the artboard that is active when the action plays. A press with the Selection, Direct Selection or Group Selection tool inside an artboard makes that artboard the active one; with the Selection tool, a Shift-click on an empty spot inside an artboard makes it active and keeps the selection. Choosing the Artboard @@ -7114,8 +7294,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 @@ -7174,6 +7359,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`, @@ -7239,13 +7440,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. @@ -7329,8 +7537,8 @@ Guides change where a snapped point lands: - `anchorPathLabels` (on by default): off, no "anchor", "center", "path" or "align" label. - `measurementLabels` (on by default): off, no size or offset readout while drawing, moving (Free Transform's move too), dragging a ruler guide, drawing and resizing an artboard, or moving and resizing a slice. -- `transformToolsGuides` (on by default): off, no readout while scaling or rotating with the Selection tool, the - Free Transform tool or the Rotate, Scale, Shear and Reflect tools. +- `transformToolsGuides` (on by default): off, no readout while scaling, rotating or shearing with the Selection + tool, the Free Transform tool or the Rotate, Scale, Shear and Reflect tools. - `objectHighlighting` (on by default; desktop app): off, the Selection tools no longer outline the object under the pointer. The outline also needs View › Smart Guides on. - `snappingTolerance` (0–40 px, 4 by default): how near an anchor, edge, centre or artboard edge pulls a drawn point, @@ -7516,6 +7724,14 @@ writes over it. with `index`, edits or moves one; `adjustAdjoining` changes the nearest points either side in proportion. Moving a point onto another one's `t` (or `stroke.widthPoint.copy {id, index, t}` landing there) makes a discontinuous point: two points at the same `t` (the width before it, then after it), and the stroke's width steps there. +`stroke.widthPoint.set {id, t, index, left, right, outIndex, outLeft, outRight, single?, adjustAdjoining?}` sets both +halves of one in one undo step: `index` is the incoming half, `outIndex` the outgoing half after it, and `t` must be +their place. With `adjustAdjoining`, the nearest point before changes with the incoming half and the nearest point +after with the outgoing half. `single: "incoming"` or `"outgoing"` keeps only that half's widths, leaving one +continuous point. Indices that are not the two halves of one discontinuous point (three or more points at one `t` +included), another `t`, or another `single` value are errors that leave the document and its undo history unchanged. +Width Point Edit on either half shows both halves as Incoming and Outgoing, with Single Width Only, and its Delete +removes both. `document.inspect` reports a path's `strokeOptions.widthPoints` (`[t, left, right]`, factors of half the weight; null for a uniform stroke). `stroke.widthPoint.remove {id, index | indices}` deletes points; `stroke.widthProfile.set {ids, points}` replaces them all, as dragging several Shift-selected points with the Width tool does in one undo step. @@ -7666,6 +7882,9 @@ small caps size (1 to 200%) lies outside those ranges opens with the nearer end `document.setup` does not take the color mode or the assigned profiles. The Document Setup dialog's Color tab sets them with `edit.assignProfile` and `file.documentColorMode`: its OK runs `document.setup`, then `edit.assignProfile`, then `file.documentColorMode` in one `command.batch`, and the document's changes are one undo step. +On the dialog's Transparency tab, a click on either grid color's box (or Enter or Space with the keyboard on it) opens +the `colorPicker` dialog over Document Setup on that color. Its OK sets only that entry of the dialog's `gridColors` +and goes back to Document Setup, whose OK runs `document.setup`; its Cancel goes back with `gridColors` unchanged. ```json {"name":"run_command","arguments":{"command":"document.setup","params":{"gridColors":"Blue","gridSize":"large","language":"German","bleed":9}}} @@ -7800,10 +8019,25 @@ starts with one empty layer. The grid comes from Preferences › Guides & Grid, preset's color mode differs from the profile's, the profile's colors are converted as `file.documentColorMode` converts them. +A profile also sets the default fill and stroke of its documents (VectorCraft's own rule). When the profile's Default +Graphic Style differs from the shipped one (white fill, 1 pt black stroke, with the shipped colors converted to the +document's color mode), `file.new` resets new art to that style's fills, strokes and effects, at full opacity and not +linked to the style, and `paint.default` (Default Fill and Stroke) gives the defaults and the selected art the same +look; type still gets a black fill and no stroke. With the shipped style, `file.new` leaves the fill and stroke as they +were. For example, to start with no fill and a 0.25 pt red stroke: edit the profile with `file.newProfiles.edit`, draw a +path with that fill and stroke, select it, run `graphicStyle.redefine {name: "Default Graphic Style"}`, delete the +path and save. + A built-in preset names its category's profile in `file.newPresets` (`profile`). Saved and Recent presets keep the 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 @@ -9810,9 +10044,10 @@ layers are refused. - **pdfX1a** (PDF/X-1a:2001, written as PDF 1.3): CMYK, grey and spot colours only. Every colour and image is converted to `output.destination` (blank: the output intent's CMYK profile, else the working CMYK profile), untagged; an RGB destination or output intent is refused. Transparency is flattened before writing. -- **pdfX3** (PDF/X-3:2002, written as PDF 1.3): colours are tagged with ICC profiles; transparency is flattened. -- **pdfX4** (PDF/X-4:2010, PDF 1.6 at most): transparency and layers are kept, colours are tagged, and the XMP metadata - names the standard and has an `xmp:MetadataDate` equal to its `xmp:ModifyDate`. +- **pdfX3** (PDF/X-3:2002, written as PDF 1.3): colours are tagged with ICC profiles, except CMYK colors in the CMYK + output intent's profile, which are DeviceCMYK (see `output.profiles`); transparency is flattened. +- **pdfX4** (PDF/X-4:2010, PDF 1.6 at most): transparency and layers are kept, colours are tagged as in pdfX3, and the + XMP metadata names the standard and has an `xmp:MetadataDate` equal to its `xmp:ModifyDate`. Flattening uses `flattenerPreset` (default High Resolution, see PDF 1.3 above) on a copy (the document is untouched; a warning says so), and images with see-through pixels count as transparency. The written file is checked against @@ -10182,7 +10417,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. @@ -11717,6 +11952,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`, @@ -11809,6 +12048,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}}} @@ -11949,10 +12189,23 @@ intensity), and the Symbolism tools one brush. Interaction state (pins, a refere desktop app, while the Artboard tool is in use, a change to its `selected` or `active` makes the artboard it then has active the active artboard (the navigator's and the Artboards panel's). +Every option given is checked before any is set. A key that the tool's `check_option` does not take (it is unknown +to that tool), a value of the wrong type, a number outside the tool's range, an unknown choice, a `key` without a +`value`, a `values` that is not an object or a `tool` that is not a tool id is an error result that names the tool and +the option, and nothing changes: no option, no saved preference and no undo step, also when another option given with +it is good. Parameters that are not an object are an error too. `{}`, or no parameters, reads the options and sets +nothing. The ranges are VectorCraft's own (for example the Smooth tool's `fidelity` takes 0.05 to 100, the Pencil's +0.01 to 100); a refused value in a Tool Options dialog keeps the dialog open. The Live Paint tools' `width` and the +Shape Builder's `gapLength` are set to the nearest end of their range when a number outside it is given, as their +sections above say. + ```json {"name":"run_command","arguments":{"command":"tool.setOption","params":{"tool":"twirl","values":{"width":60,"rate":90}}}} +{"name":"run_command","arguments":{"command":"tool.setOption","params":{"tool":"smooth","key":"fidelity","value":-3}}} ``` +The second call returns the error ``tool `smooth`: `fidelity` must be a number from 0.05 to 100``. + The Pencil's, the Paintbrush's and the Smooth tool's `fidelity` is in screen pixels: the tools send `path.freehand` and `path.smoothRegion` the option divided by the zoom, so a stroke keeps as many points and a Smooth drag smooths as much at any zoom. The Smooth tool's `fidelity` (0.05 to 100 px, 2.5 by default) is also the one an Alt smoothing drag with @@ -13031,6 +13284,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 4c8cc28361..2e9fe39fe9 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,9 +1,11 @@ # Roadmap: milestones and what's next -> **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; 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). > +> 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. +> > Vector Halftone preview update (2026-11-10): temporary dot selection marks are hidden, and the bounding box stays available (#6369). > > **Flyout update:** 2026-11-06 — resizable icon-strip flyouts and bottom-aligned panel footers (#5713); scores and estimates unchanged. @@ -57,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. | @@ -158,7 +161,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | # | Milestone | Status | Est. remaining, one agent (h) | |---|---|---|---| | M0 | Skeleton + vertical slice | ✅ done | — | -| M1 | Selection, transform, layers, MCP (common command tools, strict keys, session resources and version-aware result hints) | ✅ mostly done (document-tab artwork drag with lossless resource transfer and one target Undo; malformed MCP app replies discard the connection without replay, #1761; bounded control socket waits and connection-slot recovery, #1726; bounded synthetic control input, #1709; no-op anchor Align keeps Undo, Redo and saved state (#1180 follow-up); transform reference point snaps to anchors/centres; rotated objects keep a rotated bounding box and their angle; Free Transform, Scale and Reflect along a rotated box pending; the Transform fields take one Tab each, the W/H link after them) | 4–6 | +| M1 | Selection, transform, layers, MCP (common command tools, strict keys, session resources and version-aware result hints) | ✅ mostly done (path and compound-path interior selection follows enabled fill rows (#6625); hidden-fill and no-fill stroke cap/join CPU regressions passed; document-tab artwork drag with lossless resource transfer and one target Undo; malformed MCP app replies discard the connection without replay, #1761; bounded control socket waits and connection-slot recovery, #1726; bounded synthetic control input, #1709; no-op anchor Align keeps Undo, Redo and saved state (#1180 follow-up); transform reference point snaps to anchors/centres; rotated objects keep a rotated bounding box and their angle; Free Transform, Scale and Reflect along a rotated box pending; the Transform fields take one Tab each, the W/H link after them) | 4–6 | | M2 | Drawing tools + smart guides | ✅ mostly done (#3380 deletion creates independent selected path pieces and keeps bounds-fitted gradients in place; endpoint highlighting remains open; Polygon/Star exact-size count persistence, with repeated-drag, tool-switch and Cancel regression coverage; Curvature point markers without direction handles (#1236, in part); Direct Selection segment click/Delete preserves neighboring edges, #1278; Flare, Reshape, Live Corners widget dragging and per-corner radii and kinds landed, on any path's corners; Shaper rough-shape recognition and orientation steps, the remaining Pen modifier nuances; Shaper Groups with editable sources and separate fill/stroke edits landed; custom ruler origin with drag preview, active-artboard reset, relative X/Y fields and native round-trip (#1212); construction widget/refinements pending); a shape just drawn moves by its centre point and turns from the zone outside a corner with its tool still active (#5477); Tangent and straight-segment perpendicular snapping use saved Smart Guides Geometric Guides preferences and Control bar quick access (#2537), including the existing Snap to Glyph and Alignment Guides toggles (#6164); no View submenu; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123) | 12–18 | | M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Eyedropper copies transformed character dimensions (#6404) and styles highlighted text only (atomic transparency rejection); Eyedropper reads visible locked and outside-isolation sources (#1251); Color Picker, Color panel (its spectrum grows with a resized panel, #8005), Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416; native Lab entry and swatch libraries in the picker, Assign-row menus, #8031/#4028); gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; visible strokes when paint is added to inherited None/zero-width art (#1253); stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool (Shift-double-click enables adjoining adjustment in Width Point Edit; finite-arithmetic follow-up regressions and full CI passed ([Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area))), Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries; CSS library export preserves fractional linear and radial gradient stop positions. Left: freeform gradients in SVG/PDF, mixed spot/process gradients in SVG and PDF gradients mixing a spot color with RGB or Lab stops export as stops or process colors; PDF export writes dithered gradient fills with spot stops, and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, as images in process colors; confirm the Scale Strokes & Effects default; Recolor model selection is available through the engine and MCP only (#2520); the dialog retains its existing controls; Library panels' lists (swatch, Color Book, brush, symbol and graphic style libraries) fill a taller panel above its footer (#2992; scores and estimates unchanged); Graphic Styles list fills a taller panel above its footer (#2992; scores and estimates unchanged); Swatches list fills a taller panel above its footer (#1638; `the_list_fills_a_tall_panel_above_its_footer`; scores and estimates unchanged); | 4–8 | | M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300; estimates unchanged); PDF import: type filled and stroked by one text-showing operator comes in as one filled and stroked type object (#8015; not yet for type filled and stroked at less than full opacity, or a `TJ` whose kerning starts a new line part way through, which still come in as a filled object and a stroked one; estimates unchanged); PDF import: stroked type keeps the file's line cap, line join and miter limit (#7741; estimates unchanged); Rename artboards in Export for Screens (#7275); Explicit editing-data import keeps oversized capped-page artboards (#6865; estimates unchanged); Save refusal continuation (#6146): ordinary Save offers Save As; unchanged format keeps options, changed format opens its Save options; cancellation/automation isolation; focused UI regressions passed, native acceptance pending; PDF authored ActualText preserved once in editable import (#6165; first-glyph line/style, bounded input; estimates unchanged); PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import preserves authored ActualText separately (#6165), with cross-line/style layout limits; separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. `.ai`/EPS type from the text document keeps its paragraphs' tab stops (#6147); `.ai`/EPS type from the text document keeps auto leading per line, its hyphenation options, and may show more of the last lines the file sets in an area frame of its own, when growing the frame by its lines' deepest descent plus 0.05 pt shows them (#6137); ✅ done (M4.14–M4.98 on 2026-10-05): Save As/Save a Copy/Revert/templates, Data Recovery and background save, SVG import and export fidelity (units, text, symbols, filters, SVGZ, Preserve Editing, SVG Options), shared guarded PDF writer and windowed reader ([pdf-backend.md](pdf-backend.md)), PDF import (colours, layers, masks, editable text, security) and export (presets, marks, bleed, ICC and output intent, raster effects, subset fonts, PDF/X-1a, X-3 and X-4, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3), Place and Links, Package, EPS and DXF in and out (EPS legacy mesh corners, vector opacity masks and raster page comparison verified; closed SPLINE flags round-trip and circular paths export as native CIRCLE/ARC, #1299), EMF/WMF, TIFF/BMP/Targa/PSD/GIF/PNG-8 export, Print and print presets, slices, Save for Web, TIFF in Export for Screens and Asset Export, clipboard flavours, File Info; AF.1–AF.4 add Affinity import (native layers, artboards, vectors, text and images from Affinity 1–3 files; the embedded preview only as a warned fallback; AF.4 expands current `.af` fixtures and every-board round-trip validation); EPS Save and Save As keep an opened EPS as EPS with its page frame and complete editable VectorCraft document (2026-10-26; G9 import fidelity unchanged). Left: DWG (use DXF), PSD placement as layers, overprint read back from PDF, Affinity export, polish; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke, adding no text (#6971; scores and estimates unchanged); | 3–6 (existing scope; Affinity export unestimated) | @@ -171,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 | @@ -215,6 +218,7 @@ not take the artwork yet. Overflow-menu drag remains separate. Scores and hours |---|---|---| | 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 | M1: an Alt-drag in the Layers panel copies a row above or below its own place (`layer.move` with `copy` and that row as the target), so the top layer dragged up, the bottom layer dragged down and a document's only layer are copied (#8237). 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. | | 2026-11-16 | minor | M1: rows or the selected-art square dragged over the Layers panel's list show the copy cursor while Alt is held, as the drop then copies, and the grabbing hand otherwise (#8217). Scores and estimates unchanged. | | 2026-11-16 | minor | Gradient panel: the strip under the ramp, where a click adds a stop, shows the white arrow with a plus on Windows and X11, where the system copy cursor showed as the plain arrow (#8241). Scores and estimates unchanged. | @@ -231,10 +235,12 @@ not take the artwork yet. Overflow-menu drag remains separate. Scores and hours | 2026-11-12 | minor | M14: numeric fields keep the caret when a focus click is released more than 1 pt from its press; a tap within 1 pt still selects all (#6659, follow-up to #1326); estimates unchanged. | | 2026-11-12 | minor | M12: Live Paint Bucket fills faces crossed in one drag (#6373). Scores and estimates unchanged. | | 2026-11-12 | minor | Save refusal follow-up (#6146): changed format opens its Save options; unchanged format retains original options. Focused UI regressions passed, including the format-change case that failed before the fix; native panel acceptance pending. Scores and estimates unchanged. | +| 2026-11-12 | minor | #6625 cap/join follow-up: hidden-fill and no-fill stroke hits must respect their cap/join geometry; focused CPU regressions passed. Existing fill-stack evidence, scores and estimates unchanged. | | 2026-11-11 | minor | Eyedropper copies effective character dimensions between transformed text objects (#6404); scores and estimates unchanged. | | 2026-11-11 | minor | Ordinary Save to a location refusing writes offers Save As (#6146); cancellation preserves the original path and modified state; automation receives READ_ONLY_LOCATION. Scores and estimates unchanged. Validation pending. | | 2026-11-11 | minor | M10/G5: Energy Beams built-in brush library; MCP docs catch-up; estimates unchanged | | 2026-11-11 | minor | M10/G5: Skill Icons built-in symbol library; MCP docs catch-up; estimates unchanged | +| 2026-11-11 | minor | #6625: path and compound-path interior hits follow enabled non-None fill rows, including lower fills beneath a top None row; hidden-only interiors miss; zero-opacity fills remain selectable. Scores and estimates unchanged. | | 2026-11-10 | minor | M10/G5: Status Effects built-in graphic style library; MCP docs catch-up for UI Frames and Map Markers; estimates unchanged | | 2026-11-10 | minor | M10/G5: Inventory Icons built-in symbol library (Sword, Shield, Potion, Key, Gem); estimates unchanged | | 2026-11-10 | minor | M7: the Edit Custom Dictionary dialog (#4936); the Check Spelling dialog remains; scores and estimates unchanged. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index c1fa01ee0f..4b1ca71624 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 (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). > @@ -10,6 +10,8 @@ > > Live Paint Bucket update (2026-11-12): one drag fills the faces crossed in the same group (#6373). > +> 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. +> > Vector Halftone preview update (2026-11-10): temporary dot selection marks are hidden, and the bounding box stays available (#6369). > > **Flyout update:** 2026-11-06 — resizable icon-strip flyouts and bottom-aligned panel footers (#5713); scores and estimates unchanged. @@ -61,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. | @@ -251,7 +254,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Area | Weight | Done | Main gaps | One agent (h) | Kind | |---|---:|---:|---|---:|---| -| Selection, transform & align tools | 6 | 85% | Direct Selection segment click/Delete corrected (#1278); deletion splits an ordinary contour into selected sibling objects with bounds-fitted gradients kept in place (#3380, deletion only; `crates/engine/tests/it/delete_path_pieces.rs`); open-path anchor Delete keeps gaps; Select › Start Global Edit finds the paths, compound paths and symbol instances of the selected object's shape (Appearance, Size and artboard options) and gives an edit of one to all of them in proportion, as one undo step (#3521), and on a group the groups like it, an edit inside one reaching the same object in the others (#4939), and a Shift-click on a highlighted match leaves it out; the Align panel menu's Align to Glyph Bounds › Point Text and Area Text measure type by its glyphs' ink for Align and Distribute (#4231); remaining: Free Transform/Scale/Reflect along a rotated box, Global Edit of rotated copies, transform nuances (no-op anchor Align history regression-tested, #1180 follow-up) | 4–6 | estimated; Global Edit regression-tested (`crates/engine/src/tests/globaledit.rs`; Quick Action, menu label and Escape in `panels::properties::tests::start_global_edit_quick_action_and_escape`) | +| Selection, transform & align tools | 6 | 85% | Direct Selection segment click/Delete corrected (#1278); deletion splits an ordinary contour into selected sibling objects with bounds-fitted gradients kept in place (#3380, deletion only; `crates/engine/tests/it/delete_path_pieces.rs`); open-path anchor Delete keeps gaps; Select › Start Global Edit finds the paths, compound paths and symbol instances of the selected object's shape (Appearance, Size and artboard options) and gives an edit of one to all of them in proportion, as one undo step (#3521), and on a group the groups like it, an edit inside one reaching the same object in the others (#4939), and a Shift-click on a highlighted match leaves it out; the Align panel menu's Align to Glyph Bounds › Point Text and Area Text measure type by its glyphs' ink for Align and Distribute (#4231); remaining: Free Transform/Scale/Reflect along a rotated box, Global Edit of rotated copies, transform nuances (no-op anchor Align history regression-tested, #1180 follow-up) | 4–6 | estimated; fill-stack selection regression-tested (`crates/engine/tests/path_fill_hits.rs`, #6625); cap/join follow-up CPU regressions passed; Global Edit regression-tested (`crates/engine/src/tests/globaledit.rs`; Quick Action, menu label and Escape in `panels::properties::tests::start_global_edit_quick_action_and_escape`) | | Drawing tools (Pen, Curvature, Pencil, shapes, Shaper) | 7 | 85% | Shaper construction widget, Pencil/Pen nuances, Blob Brush options, Touch Type, Dimension tool; see [ui-parity.md](ui-parity.md) | 8–13 | estimated; Curvature point display regression-tested (#1236, in part); Polygon/Star exact-size count persistence regression-covered; Live Corners' Relative rounding done (#3091), score unchanged; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123), score and hours unchanged; the Pen, Smart Pen and Curvature tool show the measurement readout with the rubber band off (#7043), score, gaps and hours unchanged | | Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 80% | Shape Builder on the reporter's file (#937: art past 4,096 segments is cut by lines again; unconfirmed on the file itself); gap detection shares Live Paint’s finder, with a 72 pt custom cap and the existing options; Live Paint Gap Options | 4–8 | estimated; Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog (lowered from 86%: open issues); compound attributes regression-tested (#1197); single-result source names survive SVG export/import (#1293), with [SVG ID semantics](https://www.w3.org/TR/SVG2/struct.html#IDAttribute) and original-shape tests; Simplify component selection and preview regression-tested (#1272); Simplify of a Direct Selection part of a path regression-tested (`tests/simplify_part.rs`); Divide open-cutting-path geometry and appearance regression-tested (#1307); the Shape Builder's edge-source grid is bounded in memory and files a segment once per cell (`planar.rs` test `rect_index_holds_a_bounded_number_of_references`); live compound shapes (Make, Alt-click, member Shape Modes, Release, Expand, saved and exported) regression-tested (#4522); Live Paint Bucket face drags, including narrow faces and one Undo, regression-tested (#6373) | | Colour, swatches, gradients, patterns, mesh, recolor | 7 | 92% | Picker Lab entry, picker libraries and Assign-row menus complete the deferred #4028 UI paths (#8031); scores and estimates unchanged; Eyedropper copies effective character dimensions across text transforms (#6404); 30.0's gradient additions are done (dither, perceptual blending, presets); freeform gradients in SVG/PDF, mixed spot/process gradients in SVG, PDF gradients mixing a spot color with RGB or Lab stops, and dithered spot gradient fills and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, which PDF export writes as images in process colors| 4–7 | estimated; Recolor model selection is available through the engine and MCP (#2520), and the dialog's color sliders (HSB, RGB, CMYK, Lab, Tint for a spot color) edit the selected row's new color in its mode, and the Edit tab's Global Adjust sliders (Saturation, Brightness, Temperature, Luminosity, -100% to 100%) change every recolored color at once (lowered from 96%: target moved); unpainted zero-width stroke restoration fixed (#1253), score and hours unchanged; Eyedropper source reads regression-tested (#1251); screen-bounded Recolor Edit chip list (#3416), score and hours unchanged; a point on a gradient mesh's outline locates on its edge on every side (#7006: `mesh_locate_takes_a_point_on_any_side_of_the_outline`, `mesh_add_line_exactly_on_the_edge_needs_no_tolerance`), score and hours unchanged; Color panel spectrum grows with the resized panel (#8005) | @@ -547,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 @@ -589,11 +592,14 @@ since 2026-10-01. ## Evidence: what ships today, by area - `object.setBounds` uses the same reference point for whole-number integer and floating-point values, including `0` and `0.0`. It rejects negative and fractional indices without changing geometry, selection, or undo history. An omitted or null reference uses the center, and whole-number references above 8 use point 8. Object and direct-anchor selections follow these rules (`tests::bboxrotate::set_bounds_whole_number_references_match_integer_references`, `set_bounds_rejects_invalid_references_without_changes`). +- Twist keeps boundary handles tangent to the rotation inside its outer circle. Regressions cover 90, 400, and -720 degree twists, unchanged boundary anchors, and a sampling midpoint that rounds to an endpoint at large coordinates (`twist_boundary_handles_follow_the_inward_tangent` and `a_midpoint_rounded_to_an_endpoint_keeps_the_handle_direction`). - **Recolor picker follow-up (#8031/#4028):** native Lab numeric entry, document/loaded-library swatches in the Color Picker, and Assign-row Pick from Swatches / Limit to Library menus. #4090 provided the double-click picker and #5113 the Assign sliders. Regression tests `native_lab_entry_in_color_picker` and `row_context_menu_pick_from_swatches_and_limit_to_library` exercise the fields and menu callbacks rather than writing their result state. Area score and hours unchanged. - **Save refusal (#6146):** ordinary File > Save to its own location offers Save As after a terminal permission/read-only refusal, suggesting the original name and format, preserving options for the unchanged format and opening the chosen format’s Save options on a change. Cancel keeps the failed-save state. Busy pickers, recovery-copy errors, other failures, explicit destinations and Close/Quit keep the existing dialog. Engine, UI and MCP regression cases are in `cmd/fileio/tests_readonly.rs`, `io/tests_read_only_save.rs` and MCP `tests/fileio.rs`; focused UI regressions passed; engine regression execution and native panel acceptance pending. Scores and hours unchanged. +**Selection fill eligibility (#6625):** Path and compound-path interiors use any enabled non-None fill row (#6625). A lower visible fill remains selectable beneath a top None row in the same object; hidden-only and true-None interiors miss. Zero-opacity fills remain selectable. Original CPU-render and document-hit regressions in `crates/engine/tests/path_fill_hits.rs` cover seven Path and five Compound cases, including stroke edges, geometric outlines, Outline/path-only modes and compound holes. Hidden-fill and no-fill stroked paths must respect butt, round and square caps and bevel, round and miter joins. Focused cap/join CPU regressions passed. Scores and estimates unchanged. + - **PDF authored replacement text (#6165):** `crates/pdf/src/tests/actual_text.rs` covers replacement once with suffix placement, PDF text-string decoding, empty and nested owners, sibling spans, page reset, multiple text-show operations, style/line changes, fill-and-stroke, reader windows and bounded input. Authored logical-order stretches are protected while adjacent ordinary text still undergoes reconstruction. The replacement takes its first placed glyph's style and line; its characters are not redistributed over later lines/styles. Exact mixed-direction paragraph layout is not claimed. No export changes; scores and hours stay at 75% / 10–20 h. - **PDF stroked type (#7741):** `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs` covers round, projecting and butt caps, round, bevel and miter joins and a miter limit of 3 on type stroked in rendering modes 1, 2, 5 and 6, shown as a word, a glyph at a time and under `ActualText`; glyphs stroked with another join as runs of their own; and a glyph filled and stroked after one stroked otherwise, which keeps the join of the glyph before it. Synthetic PDFs written in the test (standard Helvetica, not embedded); no fonts or fixtures added. The dash array is not yet carried to the characters. @@ -631,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. @@ -682,6 +689,7 @@ since 2026-10-01. - **EPS writes a repeated freeform gradient's image once:** a freeform gradient whose image samples the same on more than one fill (copies of a shape moved with their points, or one shape in a symbol's instances) has its samples written once in the setup, as a repeated image's are, and a fill whose image differs (other colors, another size) gets its own. A freeform fill drawn once is written where it is drawn, as before, and a fill whose placement cannot be drawn, or that arrives when the page is already at the 256 MB limit, is no longer sampled first (eps `tests::a_freeform_gradients_image_drawn_twice_writes_its_samples_once`, `tests::freeform_gradients_sampled_differently_dont_share_an_image`, `tests::a_field_taken_back_at_the_page_limit_leaves_no_image_behind`). Scores and hours unchanged. - **EPS releases the images of art left out at the page limit:** art taken back because it passes the 256 MB limit on the page no longer keeps the encoded samples of the placed images, colorized images and freeform fills it drew, and an image whose first placement does not fit under the limit is not kept after it is encoded. Later placements of that image are left out with the same warning without encoding it again while it still does not fit; once art taken back leaves room, it is encoded again and written where it is drawn. The page the EPS file draws is the same as before; a repeated image or field written after art taken back can take a lower resource number in the setup (eps `tests::a_rolled_back_node_frees_its_image_codes`, `tests::a_rolled_back_image_does_not_pin_an_earlier_field_code`, `tests::an_image_rejected_by_the_page_limit_keeps_no_unused_code`, `tests::an_image_rejected_by_the_page_limit_is_encoded_once`, `tests::an_image_rejected_in_art_taken_back_is_encoded_again_when_it_fits`). Scores and hours unchanged. - **PDF writes a warped image once:** with downsampling on, the pieces of an image bent by a Warp effect are resampled for the widest and the highest size any piece places the image at, so every piece paints one image XObject (a colorized image: one colorized image and its soft mask), instead of one image for each size a piece is placed at. Another placement of the same image is still resampled for its own size. Without downsampling, a colorized image and a CMYK image with a grayscale image mask on its grid are decoded and encoded once for all the sizes they are placed at (pdf `tests::compression::a_warped_image_is_written_once_for_all_its_pieces`, `tests::colorize::a_colorized_warped_image_is_written_once_for_all_its_pieces`, `export::images::tests::colorized_and_grid_masked_images_are_made_once_for_every_size_without_downsampling`). Scores and hours unchanged. +- **PDF import reads a Type 3 font's glyph procedures once:** a Type 3 font that many pages or forms list, each in a font dictionary of its own, has its glyph procedures checked for glyphs that set their own color once for the document, when the font is first noted, instead of again on every page and form. The pages open as before (pdf `tests::import_fidelity::a_type3_font_on_every_page_has_its_glyph_procedures_read_once`). Scores and hours unchanged. - **Distort Appearance with Transform effect options:** with Envelope Options › Distort Appearance on, a path whose Transform effect has Scale Strokes & Effects or Transform Patterns on, or copies it with a gradient, is bent as the same per-copy art it draws and expands as outside the envelope: each copy's own stroke weight, dashes, pattern placement and gradient (effects `bake::tests`). Scores and hours unchanged. - **Fitted gradients turn with the Transform effect:** a gradient fitted to the object (not placed with the Gradient tool) turns, reflects and stretches with the object when its Transform effect rotates, reflects or scales it unevenly, as Object › Transform already does: the gradient is fixed to its fit on the geometry the effect takes, then follows the effect and the effects after it as a placed gradient does. Under moves and even scales it draws as a refit does, and a Transform effect that scales the object to nothing across leaves it fitted, with Scale Strokes & Effects or Transform Patterns on too, and on each copy. This holds on the canvas and in Object › Expand of the fill, for an object's own effects, a fill's or stroke's own, and a group's, where the gradients fitted to its paths, to its own fill, to the groups inside it and to its images' and symbol instances' own fills each fix to their own object's fit. Existing documents with such a Transform effect on fitted-gradient art draw differently: before, the gradient refit to the turned outline. The Gradient tool still shows a fitted gradient's vector at its unturned fit. How gradients follow the effect is VectorCraft's own rule; what the effect does to the object is described in [Distort and transform effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html) (effects `bake::tests::a_fitted_gradient_turns_reflects_and_stretches_with_a_transform_effect`, `bake::tests::a_transform_effect_that_scales_to_nothing_leaves_a_fitted_gradient_fitted`, `group::tests::a_groups_transform_turns_the_gradients_fitted_to_its_members_and_its_own_fill`; render `objectfx::a_fitted_gradient_turns_and_reflects_with_its_transform_on_the_canvas`; engine `objexpand::a_fitted_gradient_turned_by_a_transform_expands_as_the_canvas_draws_it`). Scores and hours unchanged. - **Placed gradients follow Transform and Free Distort effects:** a gradient placed with the Gradient tool moves, turns and scales with the object when the object's Transform effect moves its outline, and each copy of the Transform effect takes it as many times as it takes the transform. Under Free Distort it moves and scales from the path's bounds before the effect to its bounds after it. This holds on the canvas, in export, in Expand Appearance, in Pathfinder and compound shapes, and in Object › Expand of the fill, for an object's own effects, a group's (the own fills of the group, of the groups inside it, of a symbol's art, and of the images and symbol instances it moves, included) and a fill's or stroke's own. A gradient on a path inside a group with a Transform effect now moves with the path (#2214 moved only the gradients of type), and so does a gradient on an image's or symbol instance's own fill. When a path keeps its shape because the effect would pass the geometry budget, the group's own gradients stay in place; a hidden path in a layer, which the layer's bounds leave out, does not hold them. A freeform gradient whose points were edited moves its points in the same way. How gradients follow each effect is VectorCraft's own rule; what each effect does to the object is described in [Distort and transform effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html) (effects `bake::tests::a_baked_transform_moves_a_placed_gradient_with_the_path`, `bake::tests::a_strokes_own_transform_and_free_distort_move_its_placed_gradient`, `bake::tests::a_fills_gradient_follows_the_effects_around_its_transform_with_options`, `bake::tests::baked_free_distort_moves_placed_gradients_from_the_bounds_to_the_distorted_bounds`, `group::tests::a_groups_transform_and_free_distort_move_the_gradients_placed_on_its_paths`, `group::tests::a_groups_transform_moves_the_gradient_of_its_own_fill`, `group::tests::a_nested_groups_own_gradient_follows_the_outer_groups_transform_and_free_distort`, `group::tests::a_groups_transform_moves_the_gradients_placed_on_an_images_own_fills`, `group::tests::shape_art_moves_gradients_with_a_transform_effect`, `group::tests::shape_art_moves_the_gradient_of_a_symbol_instances_art_with_its_transform`, `tests::art_past_the_budget_keeps_its_own_gradients_in_place`, `tests::a_hidden_path_past_the_budget_leaves_a_layers_gradients_free_to_move`, `tests::edited_freeform_points_follow_a_transform_effect_and_free_distort`; render `objectfx::a_paths_gradient_moves_with_its_transform_and_free_distort`; engine `objexpand::a_placed_gradient_moved_by_a_transform_or_free_distort_expands_as_the_canvas_draws_it`). Scores and hours unchanged. @@ -697,6 +705,7 @@ since 2026-10-01. - **Cut of picked anchors (#6361):** Edit › Cut removes direct-selected anchors from their path and from a compound path's member, with the segments attached to them, as Clear does. Picked segments still lose only those segments. When a path also has a picked segment, Cut removes and copies only its picked segments and ignores its picked anchors, on every contour, as Clear does; an anchor left without a surviving segment is removed with them. Regression tests: `cut_*_anchors_*` and `cut_of_an_anchor_with_a_segment_on_another_contour_leaves_the_source_as_clear_does` in `crates/engine/tests/it/copy_direct_selection.rs`. - **Escape in Selection tool drags:** Escape during a Selection tool move or Alt-drag copy, a bounding-box scale or rotation, a marquee, or a corner widget, pie widget or bracket drag cancels it: the art returns to its state at the press, no copy is left, no undo step is added, the release does nothing, and the tool stays chosen. This is VectorCraft's own behavior. Regression tests: `escape_cancels_*` in `select/tests.rs` and `pie.rs`, and `escape_cancels_a_selection_tool_move_copy_scale_or_rotation` in `tests/selectescape.rs`. - **Large Shift-marquee selections and Select › Inverse:** `select.toggle` and `select.add` with many ids (a Shift-drag marquee sends them together) go through the selection once instead of once per id, and Select › Inverse looks each object up in a set of the selected ones. The resulting selection, its order and the reply are the same as before. With 50,000 objects the selection step of toggling every object off took 528 to 655 ms before and 2.5 to 4.6 ms after in 7 runs, wall clock on a machine that was running other builds (`cargo run --release -p vectorcraft-engine --example selection_bench`). Regression tests: `add_all_does_what_adding_each_does` and `toggle_all_does_what_toggling_each_does` in `crates/doc/src/selection/tests.rs`, and `toggle_and_add_handle_each_listed_id_in_order` in `crates/engine/tests/it/selection_commands.rs`. +- **Shift-click in the Layers panel's selection column on a large layer:** `layer.selectAll {id, add: true}` checks whether the row's art is all selected with a set of the selected objects, and removes or adds that art in one pass instead of once per object. The resulting selection, its order, the reply and the highlighted rows are the same as before. On a layer of 50,000 objects the whole command took a median of 733 ms before and 6.9 ms after when all of the layer's art was selected, and 369 ms before and 24 ms after when every other object was, in 7 runs each, wall clock on Linux while other builds were running (`cargo run --release -p vectorcraft-engine --example layer_select_bench`). Regression test: `a_shift_click_in_the_selection_column_matches_adding_or_removing_each_id` in `crates/engine/src/tests/layers.rs`. - **Selection passes through raster effects:** clicks with the Selection, Direct Selection and Group Selection tools (Group Selection's repeated click included), the Selection tool's pointer and marquee, Direct Selection's marquee, pointer and anchor highlight, and Group Selection's marquee (E for enclosed objects included) leave out the area that a drop shadow, a glow, a blur or another raster effect paints beyond an object. A click on a shadow selects the object under it, or nothing over an empty canvas, a repeated Group Selection click there adds the groups of the object under it, and a press on the shadow of a selected object does not move it ([the help page](https://helpx.adobe.com/illustrator/using/selecting-objects.html)). Over a shadow, Direct Selection highlights only the anchors of the object under it, and Group Selection keeps its own pointer and highlights no anchor, as it does everywhere (VectorCraft's own rule). No setting changes this. This covers paths, groups, type, symbol instances and images. Regression tests: `crates/engine/src/tests/select_effects.rs`. - **Symbol instances are selected where their art draws past their box:** a click or a marquee selects a symbol instance where a clipping path in its art, moved or reshaped by its live geometry effects, shows the art past the instance's box, as it selects a group of the same art; a click also selects it where a stroke in its art paints past the box ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/select-objects.html)). The rest is VectorCraft's own rule: inside the box the instance is selected as before; in Outline view and below a layer whose Preview is off only the box counts; hidden art and the area a raster effect paints are left out. This covers instances in groups, nested in other symbols' art, moved and scaled. Regression tests: `a_symbol_instance_is_hit_where_a_moved_clipping_path_in_its_art_shows_the_art` and `a_symbol_instance_is_hit_on_the_stroke_of_its_art_past_its_box` in `crates/doc/src/hit/tests.rs`. - **Selection follows geometry effects:** a click or a marquee with the selection tools selects a path or compound path where its live geometry effects (Transform, Offset Path, Roughen, Zig Zag and the other effects that reshape a path, on the object or on its fills and strokes) draw it, the copies a Transform effect makes included, and not where its own geometry no longer paints. The members of a group or layer whose own geometry effects move or reshape them are selected where they are drawn, at the depth each tool selects, and a locked member there lets the click through to what is below and is listed there in the Unlock submenu. A group's own fills and strokes are clicked where they paint its members, and a clipping path inside such a group is taken on its drawn outline before the art it clips. A compound path keeps its holes, Object Selection by Path Only takes the drawn outline and not its fill, and stacking order is kept. The selection tools select objects by clicking or by a marquee ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/select-objects.html)), and the effects leave the art they reshape editable ([the help page](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/apply-and-modify-effects.html)); where clicks land on the reshaped art is VectorCraft's own rule. In Outline view clicks and marquees use the plain paths, and in a layer with Preview off they take outlines only. The area a raster effect paints is still left out. Regression tests: `a_*_shifted_art_*`, `a_click_hits_a_paths_copy_and_evaluates_its_art_once_until_it_changes`, `a_groups_own_effect_moves_where_its_members_are_hit`, `a_layers_own_effect_moves_where_its_art_is_hit`, `a_preview_off_sublayer_of_an_effected_layer_is_clicked_in_outline`, `a_painted_group_around_an_effected_symbols_instance_is_hit_where_its_art_is_drawn`, `an_intertwine_group_in_a_layers_drawn_art_is_hit_in_its_woven_order`, `a_click_in_a_plain_group_evaluates_only_its_member_with_effects`, `a_clip_groups_own_effect_moves_where_its_mask_outline_is_hit`, `an_isolated_clip_group_with_its_own_effect_is_marqueed_by_its_members_own_geometry` and `a_clip_groups_art_is_hit_when_its_drawn_art_holds_only_the_clipping_path` in `crates/doc/src/hit/tests.rs`, and `a_click_and_a_marquee_select_art_where_its_transform_effect_draws_it`, `a_click_selects_a_group_where_its_own_fill_paints_a_moved_member`, `a_marquee_takes_an_inner_groups_own_fill_inside_a_painted_group` and `a_marquee_takes_a_groups_own_fill_inside_a_painted_layer` in `crates/engine/src/tests/select_effects.rs`. @@ -776,6 +785,7 @@ since 2026-10-01. - **Tab stop drag guide:** while a stop is dragged on the Tabs panel's ruler, the canvas draws a line through the text whose stops the ruler shows, where the stop would land: across the frame cell the paragraph starts in for area type, measured from where the frame lets the paragraph's first line start (the cell's edge inside the inset, or past a text wrap object), and across the paragraph's lines from the type's origin for point type. It turns with rotated type and runs across the columns of vertical type. In a Ctrl-drag (Command on macOS) it follows the grabbed stop. No line is drawn while a release would delete the stop, and the line goes on release, on Escape, when no button is down, and when the panel is closed. It is not a document object and records no undo step. Its extent, color and these rules are VectorCraft's own. A stop drag whose release the ruler does not get also ends then, as a marker drag already did. Tests `panels::tabs::tests::dragging_a_stop_draws_a_guide_through_the_text`, `a_command_drag_guide_follows_the_grabbed_stop`, `the_stop_guide_ends_with_the_drag`, `the_stop_guide_follows_rotated_point_and_vertical_type` and `the_stop_guide_starts_where_a_wrap_object_lets_the_line_start`. Public reference: [Manage tab stops](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/manage-tab-stops.html), which describes a guide shown through the selected text during a tab stop move. - **Tabs indent markers on threaded frames:** when a marker drag gives the paragraphs of a threaded story values of their own, the Tabs panel sends one `text.setFormat {paragraphIndents}` with an entry for each paragraph of the story, whatever order the frames were selected in with the Selection tool, so the story flows through its frames again once rather than once for each paragraph, and a drag that changes no paragraph runs nothing; a paragraph that runs on from one frame into the next gets one entry, after Type tool Select All too. A selected story is one text: with the Selection tool, a marker drag on any of its frames sets every paragraph of the story, in its locked and hidden frames too. Tests `panels::tabs::tests::indent_markers_on_selected_threaded_frames_follow_the_story_and_set_a_split_paragraph_once`, `indent_markers_over_many_threaded_paragraphs_send_one_format_command`, `indent_markers_after_select_all_list_a_split_paragraph_once`, `indent_markers_on_some_threaded_frames_list_the_whole_story_once`, `indent_markers_on_one_threaded_frame_set_its_locked_and_hidden_frames`, `cmd::threads::tests::paragraph_indents_flow_a_threaded_story_once_as_one_command_per_paragraph_would`, `paragraph_indents_over_thousands_of_paragraphs_flow_the_story_once` and `paragraph_indents_check_every_entry_and_skip_a_change_that_changes_nothing`, and `cmd::typecmd::area_tests::set_format_refuses_a_param_of_the_wrong_type`. Public reference: [Indent text](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/indent-text.html). - **Width Point Edit:** Shift-double-click enables Adjust Adjoining Width Points; plain double-click and direct opening retain the default. Tool dispatch and headless dialog tests cover neighboring widths, Undo/Redo and Cancel. Public reference: [Variable-width strokes](https://helpx.adobe.com/illustrator/using/stroke-object.html). +- **Width Point Edit on a discontinuous point:** opening the dialog on either half shows both sets of side widths, Incoming and Outgoing, each with Side 1, Side 2, Total Width and its own link; OK sets both halves in one `stroke.widthPoint.set` and one undo step, and Delete removes both. Single Width Only keeps the incoming or the outgoing widths as one continuous point. With Adjust Adjoining Width Points, the nearest point before follows the incoming change and the nearest point after follows the outgoing change; the group layout and that rule are VectorCraft's own. Tests `dialogs::width_point::tests::either_half_of_a_discontinuous_point_shows_both_sets_of_side_widths`, `ok_sets_both_halves_of_a_discontinuous_point_in_one_step`, `delete_removes_both_halves_of_a_discontinuous_point`, `single_width_only_keeps_the_chosen_half_as_one_point` and `a_compound_member_edits_both_halves_of_its_owners_point`, and `tests::widthpoints::paired_set_*` and `single_width_only_leaves_one_continuous_point`. Public references: [Apply stroke on an object](https://helpx.adobe.com/illustrator/using/stroke-object.html), which describes editing the widths before and after a discontinuous point in that dialog, and an [archived user guide, p. 161](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=167), which describes keeping either the incoming or the outgoing width to leave one continuous point. Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a feature lands. - **New ruler guides (G1):** Alt swaps orientation while dragging from either ruler, following the [public shortcut reference](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html). Preview, snapping and final placement use the current axis. Tool and egui event tests exercise both rulers, modifier changes, cancellation and one-step Undo/Redo; existing-guide Alt-copy and ruler-origin gestures are unchanged. @@ -784,6 +794,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Width-point finite-arithmetic follow-up (G1/M3):** Adjoining adjustments avoid intermediate overflow; non-finite normalized or resulting factors are rejected before committing. Engine regressions in `tests/widthpoints.rs` cover finite extremes, small nonzero results, atomic rejection, Undo/Redo and native save/reopen. Historical focused validation on the `a3357121` integration observed 2 expected RED failures with 11 passing controls, then all 13 tests passing with the repair; none were ignored. All three added regressions passed in current full CI. A full CI retry on the five-unit combined source at `a0671777` passed all seven stages with 6,613 test outcomes on 2026-10-14. An earlier full-CI run on the identical source panicked in the randomized `ai_mutated_save_never_panics` test; the cause remains unresolved. This five-fix batch does not claim to repair that failure. Scores and hours unchanged. - **Width-point creation (G1):** double-click a stroked segment with the Width tool to open Width Point Edit using sampled side widths. OK creates the point and optionally adjusts adjoining widths in one undo step. Cancel or Delete discards a prospective point without changing the document or redo history. Command and pointer tests cover profiles, compound paths, adjoining adjustment, existing-point editing and Undo/Redo. Message-catalog checks and full CI passed; the original capture verifies opening and Cancel, and the dialog layout was reviewed (2026-10-13: 28 focused Width tests, all seven cargo xtask ci stages, and a headless opening/Cancel capture with original PNG review). [Variable-width strokes](https://helpx.adobe.com/illustrator/using/stroke-object.html). - **Escape deselects width points:** with the Width tool, Escape deselects the selected width points, on the key 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 for deselecting a width point. The path, its widths and the undo history do not change. With no width point selected, Escape does what it does with the other tools, such as leaving isolation mode. +- **Width profiles on brushed strokes:** brush art does not follow a stroke's width profile, so while every stroke the list edits draws with a brush, the Profile list in the Stroke panel, the Properties panel and the Control bar is dimmed and says why when hovered (VectorCraft's own rule while brushes ignore width profiles; art and pattern brushes that follow one are still missing). It opens no list while every one of those strokes is uniform, and only Uniform, which removes the profiles, while one has a profile. The Flip Along and Flip Across buttons beside it are off. The strokes are the ones `stroke.set` edits: the active Appearance stroke row in each selected object that has an equal row and the top stroke in the others, else a selected group's or compound shape's own stroke, else the objects' strokes. Images and symbol instances, which take no stroke from the list, do not count. A selection where some of them have no brush, or an object has no stroke, keeps the full list. The Width tool adds, edits and deletes no width points on a brushed stroke, and a press or a double-click on one says why in the status bar; without Shift it deselects the width points of other strokes, and the cursor over a brushed stroke offers no edit. A plain stroke under a selected brushed one stays reachable. Width points selected before their stroke took a brush show no handles, and Delete, Backspace and Escape act as if none were selected. Tests: `panels::tests_strokedepth::{dropdown_is_dimmed_while_the_brush_keeps_its_size, the_active_stroke_row_decides_whether_the_dropdown_is_dimmed, a_groups_own_brushed_stroke_dims_the_dropdown, selecting_another_object_without_an_edit_updates_the_dimming, flip_buttons_leave_a_brushed_strokes_profile_alone, mixed_selection_dims_the_dropdown_only_when_every_stroke_has_a_brush, the_hover_text_is_the_width_tools_status_message}`, `panels::properties::tests::the_width_profile_of_a_brushed_stroke_offers_only_uniform`, `tests::appearance::{brushed_strokes_profiled_reads_the_strokes_stroke_set_edits, brushed_strokes_profiled_reads_a_compound_shapes_own_stroke, brushed_strokes_profiled_reads_a_targeted_layers_active_stroke_row, brushed_strokes_profiled_leaves_out_symbol_instances, brushed_strokes_profiled_falls_back_to_the_top_stroke_where_the_active_row_has_no_match}`, `tests::widthtool::the_width_tool_says_why_it_leaves_a_brushed_compound_path_alone`, `distort::width::tests::{brushed_stroke_is_left_alone_with_a_reason, delete_leaves_the_width_points_of_a_brushed_stroke, a_press_on_a_brushed_stroke_deselects_and_its_cursor_offers_no_edit, shift_on_a_brushed_stroke_keeps_the_selected_width_points, a_plain_stroke_under_a_selected_brushed_one_stays_reachable, a_brush_applied_under_a_still_pointer_takes_away_the_hover, a_brush_added_to_the_library_is_seen_at_the_next_revision}`. - **Smooth widths between width points (#5714):** a variable-width stroke changes width along a smooth curve from one width point to the next, where it used to run in a straight line and turn a corner at each point. The public description is that the path "gradually gets wider or narrower from one point to the next" in "a flowing, continuous curve", and that stacked points make a sharp break ([Peachpit, Expressive Strokes](https://www.peachpit.com/articles/article.aspx?p=2979069)); the exact curve is not documented, so each side follows a monotone cubic (Fritsch–Carlson): no kink at a point, flat where a point is wider or narrower than both neighbours, never past the points either side, points on one line kept on it. The outline samples straight runs between width points closely enough to follow the curve to the drawing tolerance (at most 64 samples per span and 4,096 per piece). Presets with a middle point (Lens, Pinch, Teardrop, Wave) look softer; two-point tapers are unchanged. Tests: `appearance::profile::tests::{widths_run_smoothly_through_width_points, widths_never_pass_the_points_either_side, a_step_ends_the_curve_on_each_side, widest_covers_every_width_along_the_profile}`, `stroke::width::tests::{a_straight_run_follows_the_curve_between_width_points, samples_between_width_points_are_capped}`. - **Stroke gradients where a variable-width stroke meets itself (#5960):** with a gradient along or across a stroke that has a width profile, where the stroke crosses itself the later part paints over the earlier one only where the two overlap, and a narrow part running close beside a wide one leaves its edge alone. Each slice of the gradient reaches as far as the stroke is wide where it sits (for a dashed stroke, as wide as it gets within the reach of a cap or dot, found in one pass along the path, so a densely flattened path costs no more per point), where it used to reach as far as the stroke is wide anywhere and paint a square of its colour over the wider part. Strokes without a profile are unchanged. Tests: `stroke::tests_gradient::a_narrow_pass_over_a_wide_one_paints_only_where_they_overlap`, `a_narrow_pass_beside_a_wide_one_leaves_its_edge_alone`, `a_densely_flattened_dashed_pass_beside_a_wide_one_leaves_its_edge_alone` and `widest_ahead_is_the_widest_within_the_window`, with the existing coverage tests (joins, caps, arrowheads, profiles, dashes, aligned strokes). - **Width strokes zoomed out (#995):** a stroke with a width profile keeps its shape while the view zooms out. The canvas keeps a hairline visible (at least half a device pixel); for a profiled stroke it is the profile's widest point that gets that minimum, not the weight, so a 1 pt stroke with a 6x width point is no longer drawn twice as thick at 25% zoom than at 100%. Plain strokes are unchanged. Test: `render::tests::widthzoom`. @@ -815,16 +826,20 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Window › New Window (G7, #4116):** New Window (`window.newWindow`) opens another view of the current document ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html) describes showing one document in several windows at once), with its own zoom, center, rotation, artboard and Outline or Preview, as a tab of its own; an edit in one view shows in every view. Tile, Cascade, Float in Window, Float All in Windows and Consolidate All Windows arrange each view as they arrange a document, and Next and Previous Document step through the views. Closing a view leaves the document open; closing its last view closes the document, asking to save it first. The view's number after the name in its tab ("Name:2", while the document has more than one view) is VectorCraft's own. Tests: `crates/ui-egui/src/doc_windows/tests.rs`. - **Document Setup modal handoff:** Document Setup → Edit Artboards applies valid settings, closes the dialog and activates the Artboard tool. Pointer-click tests cover successful handoff, invalid settings, OK, Cancel and Undo in `dialogs/document_setup.rs`. +- **Document Setup › Transparency grid color boxes:** a click on either color box beside Grid Colors opens the Color Picker on that color, as [the help page](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/view-transparency-in-artworks.html) describes choosing a custom color for each of the grid's two alternating squares. The picker's OK sets only that color in the dialog, Grid Colors then names the pair (Custom unless it matches one of VectorCraft's presets), and Document Setup's OK applies it in one undo step; the picker's Cancel leaves both colors as they were. With the keyboard on a box, Enter or Space opens the picker. The keyboard handling and staging the color until Document Setup's OK are VectorCraft's own. Tests: `a_grid_color_box_opens_the_color_picker_and_its_ok_sets_that_color` and the other grid color tests in `dialogs/document_setup.rs`. - **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`. - **Assign Profile and the working spaces:** Edit › Assign Profile… tags the document and leaves the working spaces of Edit › Color Settings… as they are, in Color Settings, the Separations panel and the settings saved for the next start. Colors show and convert through the profiles assigned; a change in Color Settings keeps the profiles the document in front is assigned in use, and removing an assigned profile in use puts the working space back in its place. The profiles in use follow the document in front: a new, opened or reverted document, a switch to another tab, a close, Undo and Redo of Assign Profile, a failed batch, each step of a batch, Export All Open and the update of placed documents put that document's profiles in use, and the working spaces where it is assigned none or no document is open. With Window › Arrange › Tile or floating document windows, each document behind the front one draws its art, paper and transparency grid through its own assigned profiles, and loading or removing a profile redraws the documents assigned it; placed documents inside it still draw through the front document's profiles. How documents behind the front one draw is VectorCraft's own rule. View › Proof Setup › Working CMYK simulates the working CMYK space of Color Settings in Proof Colors and Separations Preview, also in a document assigned another CMYK profile. Public references: [Changing the color profile for a document and About color working spaces](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=150) and [Soft-proof presets](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=134). Tests in `engine/tests/color_settings.rs`. - **Color management policies:** Edit › Color Settings… (the Separations panel's Color Settings section and `edit.colorSettings`) has an RGB and a CMYK policy: Off, Preserve Embedded Profiles and Convert to Working Space, and Preserve Numbers for CMYK. When a document tagged with a profile other than the working space is opened, reverted or opened as a template, the policy keeps the profile, takes it off with the color numbers kept, or converts that model's colors into the working space, with black point compensation as Color Settings set it, and takes it off. The policies are kept in `Color Settings.json`. Preserve Embedded Profiles as the default for both, and the per-model policy for a document tagged with both an RGB and a CMYK profile, are VectorCraft's own rules; placed images and the Profile Mismatches and Missing Profiles prompts are not covered. Public reference: [Color management policy options](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=157). Tests in `engine/tests/color_settings.rs`, `color/src/cms/tests.rs` and `color/src/cms/tests_icc.rs`. - **New Document's units:** the dialog opens in Preferences › Units › General, also on a Recent entry made in other units (an entry in pixels, or a saved preset in the units it was saved in, keeps its units), so File › New and New Without Dialog make documents in the General unit. Units chosen in the Units menu stay when another tab or preset is chosen and when a card is clicked or double-clicked; without such a choice, clicking another Recent or Saved card brings back the units that card was made in (#7944). These are VectorCraft's own rules. Tests: `the_dialog_opens_in_the_general_units_over_a_recent_entry`, `a_recent_saved_preset_keeps_its_units_and_name`, `units_chosen_in_the_menu_survive_tabs_and_presets` and `units_set_over_a_popup_stay_chosen` in `dialogs/new_document.rs`; `a_recent_card_keeps_the_units_chosen_in_the_menu` and `a_double_clicked_card_keeps_the_units_chosen_in_the_menu` in `panels/tests_units.rs`. - **New Document's More Settings and Save Preset:** More Settings opens a pop-up over New Document with only Number of Artboards, the artboard layout, Change to Right-to-Left Layout, Spacing and Columns; Done, Escape or a click outside closes it and keeps the values. Save Preset turns the top of Preset Details into a Save Document Preset heading with the preset's name, Cancel and Save, and hides the document's name, Close and Create until the preset is saved or canceled; nothing in that mode creates a document. Save Preset's default name is the first "Preset N" no saved preset has. VectorCraft's own layout. Harness tests in `dialogs/new_document.rs` cover both. - **New Document profiles:** each built-in category's presets start documents from that category's profile, a native document holding the starting swatches, graphic styles, brushes, symbols and other assets, the ruler and Document Setup options and the print settings ([Create a custom new document profile](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/start-a-new-file/create-a-custom-new-document-profile.html)). New Document's Manage Profiles pop-up opens a profile to edit and resets one to the shipped profile (`file.newProfiles`, `file.newProfiles.edit`, `file.newProfiles.reset`; `file.new {profile}`). The profiles live in VectorCraft's own `New Document Profiles` folder next to the preferences; a profile that cannot be read or is larger than 64 MiB leaves the defaults and is reported. Tests: `tests::newdoc::an_edited_profile_starts_the_documents_of_its_category`, `the_profile_follows_the_preset_access_and_reset`, `profile_errors_name_the_file_by_its_name_outside_the_read_roots`, `a_damaged_or_oversized_profile_leaves_the_defaults_and_is_reported`, `profile_names_are_checked_and_editing_needs_the_folder`, `dialogs::new_document::tests::manage_profiles_edits_and_resets_the_profiles`. +- **Default fill and stroke from a profile:** when a New Document profile's Default Graphic Style is redefined (for example no fill and a 0.25 pt red stroke), documents from that profile start new art with that style's fills, strokes and effects, and Default Fill and Stroke (`paint.default`, D) gives the defaults and the selection the same look in those documents (VectorCraft's own rule). Test: `tests::newdoc::a_redefined_default_graphic_style_in_a_profile_is_the_default_fill_and_stroke`. - **Control bar with the Artboard tool:** while the Artboard tool is in use, the Control bar shows the active artboard's controls in place of the object controls: Preset, Portrait and Landscape, New Artboard, Delete Artboard, the Name field, Artboard Options, Rearrange All Artboards, the Transform link, Move and Scale Artwork with Artboard and, while the bar has room, the reference point with X and Y, and W and H with the Constrain Width and Height Proportions link. Each runs the command its Properties or Transform panel counterpart runs (`artboard.setProps`, `artboard.new`, `artboard.delete`, `tool.options {tool: "artboard"}`), and the reference point is the one the Transform panel uses. In an 800-point window the controls up to the Transform link fit, Move and Scale Artwork with Artboard show as their boxes alone with their names in tooltips, and the link opens the Transform panel with the artboard's position and size. Pointer and key tests in `panels/artboards.rs` cover the controls, W about the reference point, the orientation and the name. Public reference: [Using multiple artboards](https://web.archive.org/web/20210925094818/https://helpx.adobe.com/illustrator/using/using-multiple-artboards.html) (archived copy). - **Names of new and renamed artboards, brushes and patterns:** `artboard.new` and `artboard.setProps` trim the white space around the name they are given, as the Artboards panel's rename does, and a blank name gives the artboard its default name, Artboard N for the Nth artboard. `brush.new`, `brush.duplicate`, `brush.options`, `object.pattern.make`, `object.pattern.saveCopy` and `pattern.options` trim the name as the Brush Options dialog and the Pattern Options panel do, and compare the trimmed name with the names there are; a blank name gives the name each command gives when there is none, and Brush Options and Pattern Options keep the name. Tests in `tests/panelcmds.rs`, `tests/brushsym.rs` and `tests/pattern.rs` cover each command. Public references: [Using multiple artboards](https://web.archive.org/web/20210925094818/https://helpx.adobe.com/illustrator/using/using-multiple-artboards.html), [Brushes](https://web.archive.org/web/20251018101754/https://helpx.adobe.com/illustrator/using/brushes.html) and [Create and edit patterns](https://web.archive.org/web/20211031180358/https://helpx.adobe.com/illustrator/using/create-edit-patterns.html) (archived copies). - **Repeated brush names in a file:** a document or brush library file whose brushes repeat a name opens with the first brush of that name as stored and each later one numbered, as "Name 2", "Name 3" and so on, skipping names the file already has. Strokes that name the brush keep drawing the first one, and `brush.list`, `brush.options`, `brush.delete`, `brush.library` and the Brushes panel then reach each brush by its own name. This numbering is VectorCraft's own rule. Tests in `crates/brush/src/tests.rs`, `tests/brushsym.rs` and `tests/brushlib.rs` cover it. @@ -849,6 +864,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Parameter schemas:** a command can carry a machine-readable parameter schema (the new `vectorcraft-apischema` crate): each parameter's type, range, unit, whether it is required, its default, whether null counts as left out, and the API levels it was added and deprecated at. `engine.commands` lists the schema in the shape of a JSON Schema 2020-12 object schema, a test keeps the command's `params` text equal to the text the schema writes, and a new call has the params checked against it before the command runs (batch steps before the first step), with an error naming the parameter and no change to the document (a value nested past the schema's 16 levels is such a parameter error, and only a schema that is wrong in itself is an internal error); saved steps keep a key the schema does not name, and their values are checked. The View commands `view.capsLock`, `view.saved.new`, `view.saved.edit`, `view.saved.list`, `view.transparencyGrid` and `view.snapToGlyph.options` have schemas. The schemas belong to API level 1 (`vectorcraft_engine::schemas::API_VERSION`), and a test fails when a schema changes without a new level. Tests: `crates/apischema/src/tests.rs` (with `conformance.rs`, a separate check of the JSON form against the JSON Schema 2020-12 rules), `schemas::tests` and `cmd::views::tests::each_view_command_refuses_a_bad_value_naming_the_parameter` in `vectorcraft-engine`. - **Input schemas in the command listings:** `engine.commands` and the MCP tools `command_list` and `list_commands` give each command with a parameter schema an `inputSchema` next to `schema`: the same schema with the root `type` `"object"`, the form an MCP tool's input schema takes ([MCP schema reference](https://modelcontextprotocol.io/specification/2026-07-28/schema)). A command without a schema lists neither, and `brief` leaves out both schemas with the `params` text. Tests: `schemas::tests::engine_commands_list_an_input_schema_with_an_object_root` and `schemas::tests::an_input_schema_keeps_deprecation` in `vectorcraft-engine`, and `tests::conventions::command_listings_carry_input_schemas` in `vectorcraft-mcp`, which check every listed input schema against the JSON Schema 2020-12 rules. - **Command API reference:** `engine.apiReference` returns a Markdown reference written from the parameter schemas when it is asked for, and MCP serves the same text as the resource `vectorcraft://commands/reference` (`text/markdown; charset=utf-8`). Each command that has a schema gets a section in registry order with its label, menu path, API levels, what it writes, summary and return, and a table of its parameters (type, range with its ends marked included or not, unit, default, required, levels and description; members of objects as dotted rows). Commands without a schema, plug-in commands included, are left out. Schema text is escaped so it stays plain text in its table cell, the same build always returns the same bytes, and a reference past 1 MiB is an error rather than a cut-short text. The command's own schema raised the API level to 2. This is a VectorCraft documentation feature; no score changes. Tests: `cmd::apiref::tests` and `schemas::tests` in `vectorcraft-engine`, `resources::tests` in `vectorcraft-mcp`. +- **Tool option errors:** `tool.setOption` checks every option it is given before it sets any: an option the tool doesn't have, a value of the wrong type, a number outside the tool's range or an unknown choice is an error naming the tool and the option (``tool `smooth`: `fidelity` must be a number from 0.05 to 100``), and no option, saved preference or undo step changes; `{}` only reads. Most ranges are the ones each tool's setter clamped to; the Arc tool's `lengthX` and `lengthY` take more than 0 up to 1e6 and the Line tool's `length` 0 to 1e6, where a negative length was taken as its absolute value. The Live Paint tools' `width` and the Shape Builder's `gapLength` are still set to the nearest end of their range. A Tool Options dialog with a refused value stays open. This is VectorCraft's own rule; no score changes. Tests: `option_check::tests` in `vectorcraft-tools`, `tests::toolsettings` in `vectorcraft-engine`, `tests::liquify` in `vectorcraft-mcp`, `dialogs::freehand::tests::a_refused_fidelity_keeps_the_dialog_open`. - **Automation:** - Variables: Update Data Set writes what the art holds into the active data set for the variables that data set holds, and keeps the data set's value for a text, image or graph variable whose objects are locked or inside a locked layer or group; `dataset.update {all: true}` also adds the other variables that the art reports a value for. - Variables: `dataset.select`, `dataset.next` and `dataset.prev` rewrite type and apply the other values on hidden objects and in hidden layers and groups, which stay hidden unless a visibility value shows them, so a layer shown later holds the selected data set's text; objects that are locked or in a locked layer or group are skipped, except by a visibility value. @@ -862,6 +878,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Batch…: Override Save and Override Export name each file with the extension of the format the step writes, however the step spells the format (`.svg` and `SVG` give `.svg`, `png8` gives `.png`), in `action.batch`. - Batch…: Override Export writes the files of an Export for Screens or Export Assets step into a folder for each source file or data set inside the destination folder, under the names the export gives them (`action.batch`). The folder and file names drop trailing periods and spaces (`a..svg` gives `a`). When two source files would get the same name that way (compared without case), or a later file's folder or file would take the name of an output an earlier file wrote, of a source file in the destination folder or, for data sets, of a file already there, Batch adds `-2`, `-3`… to the later one's name. - Batch…: when a step fails on a file or data set, the error names the step by its place in the action's steps, from 1, counting the Open steps the batch skips (`action.batch`). This numbering is VectorCraft's own rule. Tests `cmd::fileio::action_batch::tests::{a_folder_batch_error_names_the_step_in_the_commands_sent, a_recorded_open_that_fails_is_the_first_step, a_data_set_batch_error_names_the_step_in_the_commands_sent, a_redirected_export_that_fails_keeps_its_place, a_source_that_does_not_open_names_no_step}`. + - Batch…: a step refused before any file opens (no command, a command the engine does not have, params its command refuses, a nested batch or `prefs.import`) is named the same way, by its place from 1 and its command id (`action.batch`). Tests `cmd::fileio::action_batch::tests::{a_refused_step_is_named_by_its_place_from_1, the_parameter_check_names_the_refused_step, steps_with_ids_that_are_not_engine_commands_are_refused}`. - Actions panel menu: Save Actions… writes the current action set with all its actions to a file, and Load Actions… adds the set from such a file to the panel ([Manage a set of actions](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/manage-a-set-of-actions.html); `ui.actionSet.save`, `ui.actionSet.load`). The file is VectorCraft's own action set file (`.vcactions`); a loaded set named like one in the panel gets the next free number. - Actions panel menu: Load Actions… keeps a step whose command this build or its installed plug-ins do not have, and reports each one when the set loads: the `ui.actionSet.load` answer lists the action, step and command id (`unknownCommands`, `unknownCount`), and the status bar names the first and the count. An action with such a step included does not play, and the error names the step and its id before any step runs; an excluded one does not stop it. These are VectorCraft's own rules. Tests `panels::actions::tests::{load_actions_reports_steps_with_unknown_commands, load_actions_bounds_what_it_reports_of_unknown_commands, an_action_with_an_unknown_command_does_not_play}`. - Actions panel menu: Save Actions… does not write a set with a step that sets a folder preference (the Fonts, Plug-ins, Templates and Recovery folders and the two scratch disks) to a folder, and names the action and the preference instead; an empty folder and the scratch disk choices Startup and None save. Export Preferences leaves out both scratch disks, and `ui.inspect` under automation read roots leaves such a folder outside them out of recorded steps. These are VectorCraft's own rules (`ui.actionSet.save`, `prefs.export`). @@ -950,6 +967,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`. @@ -957,6 +975,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Plug-in, recovery and script report replies under `--automation-read-root`: `plugin.list`, `plugin.info` and `plugin.safeMode` name the plug-in folder, failed files, plug-in sources and disabled plug-ins' files outside the read roots by file name or `null`, `file.recovery.*` leave out a document's original file and the recovery folder outside them, and `ui.inspect`'s `scriptReport` names files a run wrote outside them by file name. `crates/engine/src/tests/plugins.rs` (`plugin_list_leaves_out_paths_outside_the_read_root`), `crates/engine/src/tests/recovery.rs` (`recovery_replies_leave_out_paths_outside_the_read_root`), `crates/ui-egui/src/tests/automation.rs` (`ui_inspect_script_report_leaves_out_files_outside_the_read_root`). - Scripts: `alert`, `confirm` and `prompt` open dialogs during a run, each with a Stop button that ends the run and puts every document back. In the app the run waits at the call for the person's answer; a run over MCP or the command line takes its answers in order from `script.run`'s `answers`, and the report lists each dialog with its answer. `crates/engine/src/tests/script_dialogs.rs`, `crates/ui-egui/src/tests/script_dialogs.rs`. - Parameter keys: the engine refuses a key that a command's params description doesn't name before the command runs, in every build and for every caller, including the app's own calls, the commands a command runs and the steps of `command.batch` and `action.batch`. An action recorded by an older version still plays from the Actions panel and the Batch dialog (`Session::replay`). `crates/engine/tests/it/param_keys.rs`. + - Parameter key lookups: the engine reads the params description of each built-in command, with the descriptions its `…` entries name, once per process, and answers the key check and the `ids` and `id` questions of each later command from that reading. A plug-in command's description, and a description whose `…` entries name a plug-in command, are still read each time. The accepted keys, the answers and the error messages are the same. In a release build on a one-object document, `object.move` with `ids` and `dx` takes 48 µs of thread CPU time per command instead of 61 µs, and `select.set` with `ids` 2.3 µs instead of 3.2 µs (medians of 7 alternating runs of 20,000 commands in one process, measured while other builds were running; `tests::params_cache::bench_params_keys_once`). The time is saved per command, in scripts, batches and MCP or plug-in call loops, and does not grow with the size of the document. `crates/engine/src/tests/params_cache.rs` compares every built-in command's answers with those of a fresh parse. - Effect parameter types: `effect.apply`, `appearance.addEffect` and `effect.setParams` refuse an effect parameter of another type than the effect reads, for keys only the params text names too (the earlier 3D `perspective`, `lightAzimuth` and `lightElevation`, Scribble's `variation`, Outline Stroke's `width`, Gaussian Blur's `linear`), a Crop Marks `style` other than `roman` or `japanese`, and an installed plug-in effect's parameter of another type than its manifest gives it, in a `command.batch` step too, with the document and undo history unchanged; a replayed action still plays. `effect.setParams` checks the parameters against a Warp's new style, and refuses a `visible` that is not true or false, in a replayed action too. `crates/engine/src/tests/params.rs` (`an_effect_parameter_without_a_default_is_held_to_its_type`, `effect_commands_refuse_an_undefaulted_parameter_of_the_wrong_type`), `crates/engine/src/tests/plugins.rs` (`live_effect_plugins_reshape_editable_art_and_expand`), `crates/engine/src/cmd/effectcmd/tests.rs` (`set_params_refuses_a_visible_that_is_not_true_or_false`, `set_params_checks_the_effect_it_leaves`). - MCP server with 33 tools (drawing, text, effects, Pathfinder, transforms, graphs, text wrap, export, screenshots, undo/redo, UI inspect/screenshot aliases, any command), attached to the running app or headless. Headless and remote `command_list` include desktop `UI_COMMANDS` (`ui: true`); a UI-only id still needs `--connect` to run. Eight prompts (poster, icon-set, recolor, trace-and-style, export-set, check-spelling, variables-bind, path-tools). Effect ids are not command ids. Prefer a CLI built from the checkout when a release binary lags (#6460). `vectorcraft://commands/reference` serves the API reference. Tool descriptions and replies agree with the engine: format lists come from its format table, `save_file` says it keeps the document's own format, `inspect_document` reports the paint type's characters show, and selection exports report the encoder's warnings. `--automation-read-root` / `--automation-write-root` (on `vectorcraft-cli mcp` and on `vectorcraft --control`) confine the files commands read and write to chosen folders, links followed, with the flags PhotoCraft takes (#832); each flag may be given more than once, a path inside any of its folders being allowed (#3546, `file_access::tests::several_roots_of_a_kind_each_grant_their_access`, `cli::mcp_automation_roots_take_several_folders`). A long export can be cancelled (`notifications/cancelled` stops it at the next page or group and writes nothing), reports page progress to a client that sent a progress token, and does not make other requests wait: engine-free ones answer at once, the rest are refused as busy after two seconds (#2165, #2171, #2172). - MCP window captures from an app that does not send the image back go through a file in a new folder inside the system's temporary folder, which only the user can open on Unix, instead of a fixed name in the shared folder; the folder is removed after the read, also when the capture or the read fails (`tests::conventions::an_old_app_captures_the_window_in_a_new_private_folder`). @@ -1001,6 +1020,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - A layer whose Layer Options › Print is off shows its name italic in the Layers panel, and while its row is dragged, as the reference application shows non-printing layers (#5739); a printing layer stays upright and ticking Print again restores the upright name (`panels::layers` test `a_layer_that_does_not_print_has_its_name_italic`). - In the Layers panel only the primary mouse button drags. A drag with the right or middle button on a row, a guide row, the selection square, the eye or lock column or a target circle moves, copies, hides, locks and transfers nothing and records no undo step, and a right-click still opens the row's menu (`panels::layers` test `only_the_primary_button_drags_rows_guides_art_columns_and_appearances`). - Rows or the selection square dragged over the Layers panel's list show the copy cursor while Alt is held, as the drop then copies, and the grabbing hand otherwise; the cursor follows Alt pressed or released mid-drag. The copy cursor is the panels' add cursor (#8241): on Windows and X11, which have no system copy cursor winit can show, the white arrow with a plus. Over the trash and New Layer, which delete or duplicate with or without Alt, the hand stays, and guide rows keep their own cursor (#8217; `panels::layers` tests `alt_shows_the_copy_cursor_while_rows_are_dragged` and `drag_cursor_shows_a_copy_only_where_the_drop_copies`). + - An Alt-drag in the Layers panel copies rows above or below one of their own rows (`layer.move` with `copy` and that row as the target), and the bottom layer Alt-dragged into the empty space under the list is copied below itself. So the top layer dragged up, the bottom layer dragged down and a document's only layer are copied, as any other row is. A move onto its own place, and a copy inside itself, still change nothing (#8237; `panels::layers` tests `alt_dragging_the_top_layer_up_or_the_bottom_layer_down_copies_it` and `a_lone_layer_alt_dragged_up_or_down_is_copied`; engine test `a_copy_goes_above_or_below_a_row_it_copies`). - Rows dragged in the Layers panel and held within 28 points of the list's top or bottom edge scroll a long list that way, faster nearer the edge (60 points a second at the band's inner side, 340 at the edge, at every frame rate), and keep scrolling while the pointer stays still, so a row out of view can take the drop (a move, or a copy with Alt); the Libraries panel's list scrolls by the same rule. In a list view shorter than 56 points each band is half the view, so a pointer in the top half scrolls up, one in the bottom half scrolls down, and a pointer just outside the view does not scroll it toward the far edge. A pointer beside the list, a drag of the eye or lock column and a release stop the scrolling, and scrolling changes nothing in the document. The band and speeds are VectorCraft's own (`panels::layers` tests `rows_held_near_the_bottom_or_top_edge_scroll_the_list_to_a_row_out_of_view`, `a_held_row_scrolls_the_list_as_far_in_the_same_time_at_any_frame_rate` and `the_list_scrolls_only_for_rows_held_over_it`; `panels` test `drag_scrolling_in_a_short_list_goes_toward_the_nearer_edge`). - The other panels' item drags start only with the primary mouse button too: swatches and color groups, brushes, symbols, graphic styles, library items and groups, character and paragraph styles, Appearance rows and its thumbnail, the Fill and Stroke squares, Recent Colors and the Gradient panel's thumbnail. A right or middle drag on one carries nothing, moves, copies, deletes and applies nothing and records no undo step; right-click menus and the Graphic Styles panel's held right-button preview stay as they were (`panels::swatches` test `only_a_primary_drag_moves_swatches_and_groups`, `panels::text_styles` test `only_a_primary_drag_carries_a_style_row`, `panels::tests_symbol_libraries` test `only_a_primary_drag_carries_a_library_symbol_out`, `panels::tests_effectedit` test `only_a_primary_drag_carries_the_thumbnail_or_a_row`). - Panels undock (#495): a dock tab, a panel icon or a popped-out panel's title dragged out of the dock floats that panel (in an OS window of its own on the desktop, #4135), and the strip right of the dock's tabs floats the whole tabbed group. A floating group moves by its title bar, a tab dragged out of it floats on its own, and dropped on another group's title bar or tabs it stacks with that group; dropped on a dock group's tabs, which light up under the pointer, its panels join that group, and on the group's upper or lower half they make a new group above or below it (`window.panel.dock {anchor, zone}`); dropped on the icon column they become icons there, the tabbed group's panels too (`window.panel.dock {icon: true}`); dropped anywhere else on the dock, which lights up, they go back where they live (the tabbed group or the icon column), as its × and the panel menus' Float Panel / Dock Panel do (`window.panel.float`, `window.panel.dock`). The Tools panel floats by its title bar and docks again on the window's left edge. Floating groups stack into sets: dropped on the upper or lower half of another group (a line shows where), a group joins it right above or below it, and the set's groups stack top to bottom, each showing one panel, moving together by the top group's title bar, whose × docks them all; a group dragged by its tab strip leaves the set (`window.panel.float {below, above}`). A double-click on a tab collapses a floating group to its tabs (`collapsed`), and a dock group too, a group below it moving up into the room; a second double-click, or a click on another of its tabs, expands it (`window.panel.collapse`, kept with the preferences and in saved workspaces). Sets dropped on the left edge of the icon column or of another dock column dock as dock columns (a multi-column dock, `window.panel.dock {column}`), whose groups stack, tab and tear out as a floating set's do, and whose top strip floats the column again. Floating panels, their sets and the Tools panel's position are kept with the preferences and in user workspaces, and clamped into a smaller window. Not done: panels in separate OS windows, reordering tabs by dragging, collapsing a set or dock column to icons, dock columns right of the default dock, resizing floating panels and the groups of a set. @@ -1030,10 +1050,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`). @@ -1061,7 +1083,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The History panel menu has Step Backward and Step Forward, which run Edit › Undo and Edit › Redo and are disabled when there is no step to undo or redo, and Set History Limit…, which opens Preferences at Performance, where History States is set. - The History panel menu's Clear History (`edit.clearHistory`) removes every step to undo and to redo and leaves the document as it is; it is not an undo step itself, and it is disabled when there is no step to clear. - The New Document from State button at the bottom of the History panel (`edit.newDocumentFromState`) makes a new document, which becomes active, from the state the panel has selected ([public source](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/undo-edits-and-manage-design-history.html)). VectorCraft's own rules: the new document takes the next Untitled-N name, is marked unsaved, has nothing selected and has no steps to undo or redo, and the source document and its steps stay as they are. - - The Transform panel menu's Transform Object Only, Transform Pattern Only and Transform Both (`transformPanelPatterns`) choose whether the fields, flips and menu flips of the Transform panel and the Properties panel's Transform section move the object and leave its pattern tiles, move the tiles alone, or both (until a choice they follow General › Transform Pattern Tiles, as before); Use Registration Point for Symbol (`useRegistrationPointForSymbol`) measures and transforms one selected symbol instance from its symbol's registration point, where the instance's flips, rotations and shears put it ([Transform panel overview](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/transform-panel-overview.html); `panels::transform::tests::the_menu_chooses_whether_the_object_its_pattern_or_both_transform`, `use_registration_point_for_symbol_measures_an_instance_from_its_registration_point`, `use_registration_point_for_symbol_follows_a_transformed_instance`, `tests_prefs::transform_panel_patterns_defaults_to_following_the_general_preference`). + - The Transform panel menu's Transform Object Only, Transform Pattern Only and Transform Both (`transformPanelPatterns`) choose whether the fields, flips and menu flips of the Transform panel and the Properties panel's Transform section, and the Control bar's inline X, Y, W and H, move the object and leave its pattern tiles, move the tiles alone, or both (until a choice they follow General › Transform Pattern Tiles, as before); Use Registration Point for Symbol (`useRegistrationPointForSymbol`) measures and transforms one selected symbol instance from its symbol's registration point, where the instance's flips, rotations and shears put it ([Transform panel overview](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/transform-panel-overview.html); `panels::transform::tests::the_menu_chooses_whether_the_object_its_pattern_or_both_transform`, `use_registration_point_for_symbol_measures_an_instance_from_its_registration_point`, `use_registration_point_for_symbol_follows_a_transformed_instance`, `tests_prefs::transform_panel_patterns_defaults_to_following_the_general_preference`). - The Transform panel's Align to Pixel Grid checkbox (`object.setPixelAligned`) gives paths and compound paths a pixel-aligned property, saved in the native file: their horizontal and vertical straight segments sit on whole points (half points under an odd centered stroke) with whole stroke weights, and every move, scale, rotation, reflection, Transform Each, Align move, Transform panel change, move of direct-selected anchors or of one anchor, move of a compound path's path on its own, artboard move, resize or copy that carries the art, Duplicate or paste that moves a copy, stroke edit and appearance edit that adds, removes, hides, repaints or reweighs a stroke snaps them again, while diagonal segments and curves keep their shape; a compound path made from an aligned path or compound path is aligned and snaps its paths with its own stroke; the box shows a dash for a mixed selection and is unavailable for type, images and groups ([Pixel-aligned property](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/pixel-preview-mode-for-web-graphics.html); `tests::pixelalign::turning_it_on_snaps_the_path_in_one_undo_step`, `it_stays_aligned_through_transforms`, `it_stays_aligned_when_its_artboard_moves`, `diagonal_segments_and_curves_keep_their_shape`, `type_and_images_cannot_be_aligned`, `the_property_is_saved_and_read_back`, `stroke_edits_keep_it_aligned`, `a_compound_path_of_aligned_paths_is_aligned`, `a_compound_path_of_an_aligned_compound_path_is_aligned`, `a_stroke_without_paint_snaps_to_whole_points`, `moving_direct_selected_anchors_keeps_it_aligned`, `moving_one_anchor_keeps_it_aligned`, `moving_a_path_of_an_aligned_compound_path_keeps_it_aligned`, `artboard_options_and_artboard_copies_keep_it_aligned`, `appearance_edits_keep_it_aligned`, `placed_gradients_follow_the_snapped_path`, `duplicates_and_pastes_keep_it_aligned`, `paths_added_to_or_moved_in_an_aligned_compound_path_keep_it_aligned`, `the_art_of_a_linked_opacity_mask_keeps_it_aligned`, `a_linked_opacity_mask_follows_a_snap`, `aligning_direct_selected_anchors_keeps_it_aligned`, `global_edit_keeps_its_members_aligned`, `a_path_with_live_corners_snaps_its_inner_edges`, `geometry_edits_keep_it_aligned`, `other_path_edits_keep_it_aligned`, `panels::transform::tests::align_to_pixel_grid_shows_and_sets_the_property`). - Align New Objects to Pixel Grid (`document.setup {alignNewObjectsToPixelGrid}`, a checkbox in New Document's Advanced Options and a checked item in the Transform panel menu) gives every path and compound path drawn in the document, the paths of a new grid or flare included, the pixel-aligned property, snapped in the step that draws it; it is on in the Mobile and Web presets and off in the others, saved presets and Recent keep it, and the document saves it. Type, images and groups do not take it, and art already in the document, pasted, duplicated or placed keeps its own property (VectorCraft's own rules) ([Pixel-aligned property](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/pixel-preview-mode-for-web-graphics.html); `tests::pixelalign::align_new_objects_makes_new_paths_pixel_aligned`, `align_new_objects_reaches_grids_flares_and_add_on_shapes`, `align_new_objects_is_saved_and_read_back`, `tests::newdoc::align_new_objects_to_pixel_grid_follows_the_preset`, `panels::transform::tests::align_new_objects_menu_item_toggles_the_active_document`, `dialogs::new_document::tests::align_new_objects_checkbox_follows_the_preset_and_reaches_the_document`). - The Transform panel works out its Align to Pixel Grid checkbox once for each document revision and reuses it on later frames, and lists the selected objects' ids only when the box is clicked. The box shows the same state. With Select All of 99,500 objects (100,000 paths, 1,000 of them in 500 compound paths), working the state out on every frame took a median 33.5 ms of thread CPU time per frame in a release build on a loaded machine; the first frame after a change now takes 31.5 ms and later frames take about 1 ns (`panels::transform::tests::align_to_pixel_grid_kept_state_equals_a_full_measure`, `align_to_pixel_grid_state_is_measured_once_per_revision`, `pixel_aligned_state_timing`). @@ -1072,6 +1094,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - After a rotation the Scale and Reflect tools, the Scale and Reflect dialogs, `object.scale`, `object.reflect` with a named axis and the Transform and Properties panels' flips act along the selection's turned bounding box until Reset Bounding Box: the horizontal and vertical scale stretch along its own width and height, and the vertical and horizontal reflection axes are its own. The Reflect tool's default axis and its Shift steps start from the box's axes, and an axis drawn with the tool is the line drawn on the page. `basis: "page"` keeps the page's axes (VectorCraft's own rules; `bboxrotate::scale_and_reflect_follow_the_turned_box`, tools `xform::transform::tests::scale_and_reflect_drags_follow_a_turned_bounding_box`). - Perspective Distort and Free Distort (`object.distort`) turn each warped object's bounding box as the warp turns the object at its own center, the objects inside groups, compound paths and clip groups and the art of linked opacity masks included, so the next Selection or Free Transform drag uses the tilted box; Object › Transform › Reset Bounding Box squares it again, and corners left where they are add no undo step (VectorCraft's own rule; `bboxrotate::distort_turns_an_upright_box_with_the_warp_at_its_center`, `distort_turns_each_member_and_linked_mask_by_its_own_warp`, `mirrored_and_collapsing_distorts_keep_valid_angles`, `distort_angles_undo_redo_and_reopen_together`, `xform::unchanged_distort_records_no_history`). - The Free Transform widget's Constrain works in Free Distort as well as in Free Transform ([the help page](https://helpx.adobe.com/illustrator/using/tool-techniques/free-transform-tool.html)). With Constrain on, or Shift held, a corner dragged in Free Distort moves only along the line through the opposite corner, in the box's own proportions, and the other three corners stay in place; on a turned box the line runs through the box's own corners. The line is VectorCraft's own rule. Cmd/Ctrl+Alt+Shift on a corner still drags in Perspective Distort, where Constrain stays unavailable (tools `xform::free::tests::free_distort_corner_keeps_to_its_diagonal_with_shift_or_constrain`, `shift_pressed_during_a_free_distort_drag_constrains_it`, `a_turned_box_is_constrained_along_its_own_diagonal`, `along_diagonal_of_a_degenerate_box`; engine `xform::free_transform_constrained_distort_keeps_the_corner_on_its_diagonal`; ui-egui `free_transform::tests::the_widget_sets_the_mode_and_a_corner_drag_then_distorts`). + - With Smart Guides › Transform Tools on, a Free Transform shear (Cmd/Ctrl on a side handle) shows its angle next to the pointer, as the Shear tool does, and a handle drag that turns from a scale into a shear and back shows only the current operation's value ([the help page](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/smart-guides-options.html)). The angle's sign and its one decimal place are VectorCraft's own rule, the same as the Shear tool's label (tools `xform::free::tests::shear_drag_shows_its_angle_with_transform_tools_guides`, `a_handle_drag_that_changes_operation_relabels_it`). - Native macOS menu bar, vector tool cursors, a command palette (Help › Search Commands…), middle-button panning with any tool. Native menus explicitly end tracking on command selection, outside window presses and Escape; menu updates wait until tracking ends, and a dismissing press never starts a canvas gesture (M14.8). - Help › Search Commands… is the first item of the Help menu in the window, with its shortcut and a separator after it; in the native macOS menu bar it is the first item below the system's search field. This is VectorCraft's own order and does not raise a score (`menus::tests::help_starts_with_search_commands`, `tests::nativemenu::the_mac_help_menu_starts_with_search_commands`). - A Recent Commands button beside the Help › Search Commands field lists the last five commands, tools, panels and effects picked from the palette, most recent first, with a command picked again moved to the top. Choosing a row closes the palette and runs it as a pick of the same result does; with no picks yet the list shows a dimmed No recent commands row, and a command that is not available now, such as a filter of a plug-in that is not loaded, is left out until it comes back. The ids are saved with the UI state. While the list is open, Up and Down move through its rows, wrapping at the ends, and Escape closes the list before the palette. This is VectorCraft's own addition and does not raise a score (#6376; `palette` tests `recent_commands_*`, `a_recent_command_runs_what_its_pick_runs`, `the_keys_wrap_within_recent_commands`, `escape_closes_recent_commands_before_the_palette`). @@ -1082,6 +1105,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`). @@ -1117,14 +1141,20 @@ 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`. - **Expand of symbol instances:** Object › Expand turns selected symbol instances (without effects, not in perspective, in groups or placed documents too) into their art as Break Link to Symbol places it, one level deep, as one undo step; the Expand dialog's Fill and Stroke reach that art (`object.expand`, `crates/engine/src/tests/expand_symbols.rs`; estimated, score unchanged). - **Reset Transformation** ([Transform symbols](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/transform-symbols.html), [Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html)): the Symbols panel menu's Reset Transformation and the Control bar's Reset, shown while symbol instances are selected, give the selected instances their symbol's own scale again, without rotation or shear, as one undo step (`symbol.instance.resetTransform`); an instance in perspective is left as it is. VectorCraft's own rules: each instance keeps the center of its bounding box in place, reflection is removed too, and the menu item and the button are enabled only while a selected instance would change. Tests: `tests::brushsym::reset_transformation_restores_the_symbols_scale_and_keeps_the_center`, `reset_transformation_keeps_the_center_of_art_away_from_the_origin`, `reset_transformation_ignores_a_stored_size_that_is_not_positive`, `reset_transformation_leaves_unchanged_instances_and_refuses_bad_ids`, `panels::symbols::tests::reset_transformation_is_enabled_for_a_transformed_instance_and_resets_it`. + - **The Symbols and Properties panels find selected symbol instances once per revision:** whether the selection or its groups hold a symbol instance (Break Link to Symbol), one with appearance changes of its own (Reset Symbol Instance and the Properties panel's Reset), or one Reset Transformation would change is worked out in one walk of the selected objects for each document revision, and later frames reuse it. The buttons and menu items are enabled as before. With one selected group of 300,000 paths, the two panels' reads took a median 5.1 to 5.7 ms of thread CPU time per frame; the first read after a change now takes about 3 ms and later frames about 5 ns (Linux, opt-level 3, median of 7 runs). In a small document the difference is too small to notice. Tests: `panels::symbols::tests::instance_flags_are_found_once_per_revision_and_match_a_walk_of_the_selection`, `properties_and_symbols_panels_walk_the_selection_once_per_revision`. - **Expand of dimensions:** Object › Expand, Expand Appearance, Create Outlines and Outline Stroke turn a dimension whose art they change into a plain group of that art, which stays as it is through later moves, scales and edits of what it measured; undo gives the live dimension back (`crates/engine/tests/it/dimensions.rs`; VectorCraft's own rule; estimated, score unchanged). - **Brush libraries** ([public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html)): Window › Brush Libraries, the Brushes panel's Brush Libraries Menu and its menu's Open Brush Library open each library in a library panel of its own, as swatch, graphic style and symbol libraries do. The built-in libraries (Art Ribbons, Ink and Wash, Calligraphic Nibs, Bristle Brushes, Pattern Borders, Scatter Shapes, Game Trails, Energy Beams, Dry Media, Tech Circuit) are original brushes generated in code (`crates/engine/src/cmd/brushlib.rs`); Striped Ribbon's art is filled with the library's own pattern and Sparkles scatters the library's own symbol; Ink and Wash adds ink and wash brushes (the [help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html) lists an Ink brush library of strokes with varied thickness and texture; the names, shapes and opacities are VectorCraft's own): Tapered Ink, an art brush broad near its start that thins to a fine tip; Brush Pen, a calligraphic brush whose size follows the pen pressure; and Soft Wash and Pooling Wash, art brushes of translucent gray layers that take the stroke color as tints; Game Trails adds motion art brushes (Speed Line, Dash Trail, Burst Ray, Zigzag); Energy Beams adds laser and plasma art brushes (Laser Bolt, Plasma Arc, Charge Wave, Spark Trail); Dry Media adds grainy art brushes (Chalk Grain, Graphite Pencil, Wax Crayon, Charcoal Dust). A click on a brush adds it to the document's Brushes as one undo step with every resource its art uses (patterns, symbols, swatches, graphic styles, images), makes it the current brush and, with paths selected, applies it to them in the same step; a brush the document already has is not added again and a different brush of the same name comes in numbered ("Wave 2"). Shift/Cmd-clicks select brushes for Add to Brushes; a brush dragged onto a path is added and applied to it, and one dragged onto the Brushes panel is added. Save Brushes… / the Brushes panel's Save Brush Library… write the document's brushes (or the selected ones) as a `.vectorcraft` library into the `Brushes` folder next to the preferences, listed under User Defined, or to a file; Other Library… reads the brushes of any document VectorCraft opens. Thumbnails, in the library panels, the Brushes panel and Brush Options, render brush art with the patterns and symbols it uses. Copying brushed art now carries the patterns and symbols its brush's art uses too. Tests: `crates/engine/src/tests/brushlib.rs`, `crates/ui-egui/src/panels/tests_brush_libraries.rs`, `panels::brushes::tests::library_brush_previews_show_the_patterns_their_art_uses`, `canvas::tests::a_library_brush_dropped_on_a_path_is_added_and_applied_in_one_step`. - **Bristle Brushes library** ([What's new](https://helpx.adobe.com/illustrator/desktop/new-features/whats-new.html), [About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Bristle Brushes holds ten bristle brushes, one for each tip shape (Fine Liner, Pointed Flat, Stubby Round, Dry Scrub, Soft Dome, Filbert, Angled Round, Angled Flat, Fan Blender, Grass Fan). The brushes, their names and their values are VectorCraft's own, and every value lies inside the range the bristle brush keeps (`brush.libraries`, `brush.addFromLibrary`; `the_bristle_brushes_library_covers_every_tip_shape_within_the_bristle_ranges`). + - **Bristle strokes follow recorded pen input** ([brush documentation](https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=201)): a Bristle brush in VectorCraft widens its strand spread and thickness with pressure along the stroke; pen tilt changes the spread, and bearing and barrel rotation turn it in the path's local frame. Missing pen channels use neutral values, and mouse strokes keep their existing appearance. This is VectorCraft's own rendering model; hardware-specific output has not been verified. `bristle_pen_pressure_changes_its_footprint`, `bristle_pen_pressure_is_sampled_along_the_stroke`, `trimmed_bristle_strands_read_pressure_where_they_begin` and `bristle_pen_orientation_changes_its_footprint` cover the geometry in `crates/brush/src/tests.rs`; `bristle_path_keeps_and_draws_its_pen_pose` covers saving and export in `crates/engine/src/tests/brushsym.rs`; area scores unchanged. - **Tech Circuit library:** Circuit Trace is a chamfered art brush with 45-degree elbows and terminal pads; Bus Lines repeats three parallel conductor lanes; Terminal Nodes repeats solder pads, circular test points and connecting leads. Original vector geometry generated in code, with Tints colorization and continuous pattern tile edges. Evidence: `the_tech_circuit_library_constructs_adds_and_applies_each_brush` in `crates/engine/src/tests/brushlib.rs` covers listing, finite geometry on straight, curved, short and closed paths, add/apply, undo/redo, deduplication and saved-library round trips. G5 remaining estimate 3–13 h (estimated); area scores unchanged. - **Dry Media library** ([help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Dry Media holds four art brushes with textured strokes like dry drawing materials, each 100 pt long: Chalk Grain (about 8 pt high), Graphite Pencil (about 2.3 pt), Wax Crayon (about 5.5 pt) and Charcoal Dust (about 7 pt). The brushes, their names, sizes and art are VectorCraft's own: each is filled vector paths from a fixed seed, at most 80 paths and 500 anchors, stretched along the path with Tints colorization, and the chalk and crayon art has even-odd gaps where the paper shows (`brush.libraries`, `brush.addFromLibrary`; `the_dry_media_library_holds_grainy_art_brushes_with_bounded_art`). - **Brush names in library panels**: a built-in brush library's panel shows its brushes' names in the UI language, in its list rows and tooltips, and its Find field matches the name shown or the English name. This is VectorCraft's own rule. A User Defined or Other Library… library's brushes, and the document's Brushes panel, show names as they are stored. A click, a drag, Add to Brushes and `brush.addFromLibrary` still use the English name, so the brush comes into the document under that name (`built_in_library_brushes_are_listed_in_the_ui_language`, `built_in_library_brush_names_are_in_complete_catalogs`). @@ -1139,6 +1169,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Pixel Snapping Options:** Control bar › Snapping › Pixel Snapping Options… sets whether View › Snap to Pixel snaps drawing, moving and scaling, each on by default (`view.snapToPixel.options`, the `pixelSnap` preference group; [the help page](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/draw-pixel-perfect-art.html)). Tests: `pixel_snapping_options_read_set_and_reset`, `pixel_snapping_options_choose_the_edits_snap_to_pixel_rounds`, `handle_drag_follows_the_while_scaling_option`, `move_follows_the_while_moving_option`, `an_anchor_drag_follows_the_while_moving_option`, `new_ruler_guide_follows_the_while_moving_option` and `the_control_bar_snapping_menu_opens_pixel_snapping_options`. Scores and estimates unchanged. - **Measure tools and Snap to Glyph:** with Snap to Glyph, Smart Guides and Alignment Guides on, and Snap to Grid and Snap to Pixel off, both ends of a Measure or Measure & Inspect drag land within the snapping tolerance on the guides of live type that the Character panel's options allow, except Anchor Point, and a Shift-drag's end slides along its 45° step to them. The guide shows during the drag. This is VectorCraft's own rule (`Targets::for_measure`, `xform::measure::tests::its_ends_land_on_glyph_guides_with_snap_to_glyph`); scores and estimates unchanged. - **Drawing readout without the rubber band:** with Enable Rubber Band for the Pen or Curvature tool off and Measurement Labels on, the Pen, the Smart Pen and the Curvature tool hide the preview segment but still show the D / Angle / dX / dY readout at the snapped pointer before the next click, and the Curvature tool also shows it when going on from the current end of a selected path. Measurement Labels show distance and placement while drawing ([the help page](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/smart-guides-options.html)), and the rubber band preference turns off the path preview ([the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/preview-paths-drawn.html)). Showing the readout with the rubber band off is VectorCraft's own rule (`pen::tests::measurement_label_shows_with_the_rubber_band_off`, and `the_measurement_label_shows_with_the_rubber_band_off` in `draw2::curvature::tests` and `addons::smart_pen::tests`); scores and estimates unchanged. + - **Pen handle drags in the Info panel:** while a Pen drag pulls a handle out of an anchor, the Info panel shows the change in x and y (W, H), the distance (D) and the angle, as the Info panel overview in the [archived user guide](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=76) describes for the Pen. The values run from the anchor being shaped to the end of the handle the drag shapes: the outgoing handle of a new or added anchor or of the last anchor, and the incoming handle of the first anchor when the drag closes the path. Shift gives the constrained handle, Space moves the anchor with its handle, and the readout starts past the 3-pixel drag threshold and ends when the button comes up, the press is dropped or the tool changes. These details are VectorCraft's own rules. Tests: the `info_readout_*` tests in `pen::tests`; scores and estimates unchanged. - The desktop app keeps the Color panel's Show Options or Hide Options between sessions, and `ui.colorPanel` sets its mode and options as its panel menu does. - Preferences that act (#394, in part): Show Tool Tips, Double Click To Isolate, Zoom with Mouse Wheel (the wheel zooms about the pointer, Shift-wheel scrolls up and down, Cmd/Ctrl-wheel sideways; Alt/Option-wheel and a trackpad pinch zoom about the pointer either way), Use Precise Cursors; Selection & Anchor Display › Tolerance (objects, anchors and handles), Object Selection by Path Only, Command Click to Select Objects Behind (cycling down the stack), Zoom to Selection, anchor Size, Highlight anchors on mouse over; Type › Number of Recent Fonts (up to 15); Guides & Grid › guide and grid Color and Style (lines or dots) and Grids In Back. Then Snap to Point (its distance, for moves, drawn points and reference points), Move Locked and Hidden Artwork with Artboard, Enable Rubber Band for the Pen and Curvature tools, Handles style, Show handles when multiple anchors are selected, Hide Corner Widget for angles greater than; General › Transform Pattern Tiles (the transforms' and dialogs' Transform Patterns, Align and Distribute, art moved or duplicated with an artboard, and objects moved whole with direct-selected anchors) and Select Same Tint %; Type › Size/Leading, Tracking and Baseline Shift increments (`type.step`, Cmd+Shift+. and Cmd+Shift+, for the size, the Type tool's Alt+arrows), Enable Missing Glyph Protection and Fill New Type Objects With Placeholder Text. Then Smart Guides › Color, Alignment Guides, Anchor/Path Labels, Measurement Labels, Transform Tools, Object Highlighting (with Smart Guides on) and Snapping Tolerance (4 px by default, for every smart guide snap), then Construction Guides and their Angles (#506: a drawn point near a line at one of those angles through the point it leaves from lands on it). Then Type › Type Object Selection by Path Only (type is picked on the baseline of any of its lines, area type's frame or the path of type on a path, no longer anywhere in its bounds; the Type tools and the Eyedropper still take a click among the characters). Then General › Anti-aliased Artwork (off, the canvas draws the art with hard edges). Then Guides & Grid › Show Pixel Grid (Above 600% Zoom), a line at every document pixel over the art in Pixel Preview, turning with a rotated view as the document grid now does too. Then General › Show The Home Screen When No Documents Are Open (off, closing the last document leaves an empty window; the Home button still opens the screen). Then Units › Numbers Without Units Are Points (on by default: a number typed with no unit into a field in picas is read in points, a typed unit still wins; dimmed unless a unit is Picas). Then User Interface › Auto-Collapse Iconic Panels (off by default: on, a click away from a panel popped out of the icon column puts it away). Then Performance › Animated Zoom (on, with GPU Performance, which it needs and which dims it when off: the Zoom tool dragged sideways zooms about the press, right in and left out, and held still zooms on, Alt out; off, a drag zooms to the area dragged across, now drawn as a marquee), User Interface › Large Tabs (taller document tabs) and Scale Cursor Proportional to UI (off, the tool cursors keep their size whatever the UI Scaling), and File Handling › Display Bitmaps as Anti-aliased Images in Pixel Preview (off by default: Pixel Preview draws images with each pixel taking its nearest image pixel). Type › Auto Size New Area Type works too (new area type gets Auto Size). They reach agents too (`prefs.set`, then `pointer_gesture` or `press_key`; `ui.wheel` on the control channel). Then Smart Guides › Spacing Guides (moves space the selection evenly with its row or column, see Drawing aids). Then Hyphenation › Exceptions (comma-separated words that never break, or break only at their hyphens; `prefs.set` and restore push them into the hyphenator, #394). Then Type › Show Font Names in English (off, font menus label a family by its native-language name when the font has one; documents still use the English family, #394). Then General › Display Print Size at 100% Zoom (off by default: View › Actual Size is one document point per screen point; on, one document inch fills 96 screen points, an inch at the reference density display scaling is set against; `view.actualSize` / `prefs.set`, #394). Then Guides & Grid › Gridline every and Subdivisions (changing either sets the grid of every open document; new and opened documents take that grid too, except a native file and the native document an SVG, PDF, `.ai` or EPS file carries, which open with the grid they were saved with; `file.new`, `document.open`, `file.newFromTemplate`, `file.revert`, #394). Then Appearance of Black › On Screen (Display All Blacks Accurately by default: pure CMYK black shows through the CMYK profile, a dark grey; Display All Blacks as Rich Black shows it on the canvas as RGB black, also in CMYK documents drawn by ink planes, while rich blacks, black tints and images show as before; `RenderOptions::rich_black`, #394). Then Appearance of Black › Printing / Exporting (Output All Blacks Accurately by default; Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB raster exports and Print as Bitmap; CMYK ink exports and the document stay unchanged; `prefs.blackOutput` / `richBlack`, #394). Then Units › Identify Objects By (Object Name by default: Layers, Variables and Layer Options show and edit free names; XML ID shows and edits AI-style XML ids, `_` for a space and `_xHH_` escapes, and `layer.setProps` / rename refuse invalid ids; the document still stores the object name, #394). Then Type › Highlight Alternate Glyphs (off by default; on, pink shows behind OpenType substitutions on screen, such as ligatures and contextual forms; Document Setup's Highlight Substituted Glyphs stays separate; `prefs.set` key `highlightAlternateGlyphs`, #394). Then Units › East Asian Type (the bullet below). Then User Interface › Open Documents As Tabs (see Window › Arrange). Two stored options still do nothing yet: Plug-ins & Scratch Disks › Primary and Secondary, and Clipboard Handling › Legacy vector clipboard (the audit below). - Preferences › General › Scroll Sideways with Cmd/Ctrl + Wheel (on by default; dimmed while Zoom with Mouse Wheel is on): while Zoom with Mouse Wheel is off, Cmd/Ctrl with a mouse wheel's whole notches scrolls the canvas sideways instead of zooming. Alt + Cmd/Ctrl-wheel and a pinch on a Mac trackpad, on a touch screen or in the web build still zoom about the pointer, and once a trackpad gesture holds Alt, it zooms until it ends, also after Alt is let go. Under either wheel preference, Cmd/Ctrl with a touchpad zooms about the pointer. @@ -1160,13 +1191,16 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - A plain step of a number field (Up/Down or a wheel notch) goes to the next whole unit in its direction and a Ctrl/Cmd step goes to the next tenth, so 5.1 mm steps up to 6 mm and down to 5 mm (#2881). A Shift step adds or takes ten and keeps the fraction. - In the number, text and color fields of the panels and the Control bar, Shift+Enter (Shift+Return) applies the value and keeps the field active with its value selected; a text box of several lines takes it as a line break. In a dialog, Shift+Enter applies the value and confirms the dialog, as Enter does. - The Pattern Options panel's Name field and the name fields that a double-click opens in the Layers, Artboards and Asset Export panels take Shift+Enter (Shift+Return) the same way: it applies the name and keeps the field active with the name selected. - - Scrubby labels (#400, beyond Illustrator, as in Photoshop): dragging a numeric field's label left or right (the ↔ cursor shows over it) steps the value one unit every 2 points (Shift: ten, Ctrl/Cmd: a tenth; counts stay whole), in the field's unit and within its limits, applied live as the art follows; the whole drag is one undo step and Escape puts the value back. A click on the label focuses the field; the text box itself never scrubs, and a field with no label doesn't. Text labels before a field (Transform, Properties, Control bar, Stroke, Transparency, form rows in dialogs) and the Character and Paragraph panels' icons act as labels, and so do the links that label a field (the Control bar's Stroke: and Opacity:, the Properties panel's Stroke), which a click still follows to their panel (#4088). Preferences › General › Scrub Numeric Fields by Dragging (on by default) turns it off. + - Scrubby labels (#400, beyond Illustrator, as in Photoshop): dragging a numeric field's label left or right (the ↔ cursor shows over it) steps the value one unit every 2 points (Shift: ten, Ctrl/Cmd: a tenth; counts stay whole), in the field's unit and within its limits, applied live as the art follows; the whole drag is one undo step and Escape puts the value back. A click on the label focuses the field; the text box itself never scrubs, and a field with no label doesn't. Text labels before a field (Transform, Properties, Control bar, Stroke, Transparency, form rows in dialogs) and the Character and Paragraph panels' icons act as labels, and so do the links that label a field (the Control bar's Stroke: and Opacity:, the Properties panel's Stroke), which a click still follows to their panel (#4088), and the Control bar's X:, Y:, W: and H:, which a click follows to the Transform panel. Preferences › General › Scrub Numeric Fields by Dragging (on by default) turns it off. - In the Transform panel, the Properties panel's Transform section and the Control bar, Alt+Enter (Option+Return) applies a value to a copy of the selection and selects the copy, in one undo step. With anchor points selected with Direct Selection it applies the value to them, as Enter does. Ctrl/Cmd+Enter in W or H applies the value and scales the selection proportionally with the link off. With the Artboard tool, it scales the active artboard proportionally. A percentage typed alone in W or H (`50%`) is that share of the size the field shows, and the link and Ctrl/Cmd+Enter keep the proportions as with a length (#2401). - The Control bar's underlined Transform link opens the Transform panel in a popover under it (reference point, X/Y/W/H, Rotate and Shear with their icons and angle presets, flips, shape properties, Scale Corners and Scale Strokes & Effects), as its Stroke link does the Stroke panel; X/Y/W/H also show inline while the bar has room. The reference point locator is nine squares, the outer eight joined around the box. As VectorCraft's own keyboard rule, the locator is one tab stop in the Control bar popover, the Transform panel, the Properties panel and the dialogs, the Arrange Tools dialogs included. While it has the focus it shows an outline, and ←, →, ↑ and ↓ move the reference point one square, stopping at the edges (`the_reference_point_grid_is_one_tab_stop`, `arrow_keys_move_the_reference_point`, `the_reference_point_locator_is_one_tab_stop_and_arrows_move_it`). + - A click on the Control bar's underlined X:, Y:, W: or H: label opens the Transform panel in a popover under that label, as the Transform link does, and a second click, Escape or a click elsewhere closes it; with the Artboard tool the popover shows the artboard's fields. The help page () describes these four labels as another way to bring up the Transform panel. VectorCraft's own rules: the click does not give the field the keyboard, a drag on the label still scrubs the field, and the labels are not tab stops, so Tab still moves from one field to the next and the Transform link stays the keyboard's way to the panel (`the_control_bars_x_y_w_and_h_labels_open_the_transform_panel`, `the_artboard_control_bars_x_y_w_and_h_labels_open_the_transform_panel`). + - The Control bar's inline X and Y show the point of the selection's box that the Transform panel's locator chose, counted from the ruler origin, and a new X or Y moves that point there; a new W or H resizes the selection about it. The help page () describes typing X and Y in the Transform panel or the Control panel after choosing the point on the locator. Use Registration Point for Symbol applies to the inline fields as it does to the panel's. Choosing another point changes only what the fields show; each field edit is one undo step (`panels::transform::tests::the_control_bar_fields_use_the_shared_reference_point`). - In isolation mode the Control bar has an Exit Isolation Mode button (`object.exitIsolation`), except while a pattern is edited. Outside isolation mode, with one group, compound path, path, image, mesh or placed file selected, it has an Isolate Selected Object button (`object.isolate`), which also isolates a path inside a group that Direct Selection selected. - The canvas context menu has Isolate Selected Path (`object.isolate`) when the selection is one path, a path selected inside a group or a compound path included, as the [help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=324) lists it beside Isolate Selected Group. As VectorCraft's own rule, neither item shows for two or more objects, or for an object `object.isolate` refuses: a hidden or locked object, one in a hidden or locked group or layer, a guide while Lock Guides is on, and, while a symbol is edited, an object outside the symbol's art (`single_path_context_item_enters_isolation`, `isolation_context_item_follows_selected_kind`, `isolation_context_item_skips_objects_that_cannot_be_isolated`). - While an opacity mask is edited, Exit Isolation Mode (Esc, the isolation bar's back arrow, the Control bar's button, and the Layers panel menu's and canvas context menu's Exit Isolation Mode) leaves mask editing as Stop Editing Opacity Mask does, in one undo step: the mask keeps the edits, and the masked object is selected. While a pattern is edited, the Exit Isolation Mode item of the Layers panel menu and of the canvas context menu saves the pattern and leaves pattern editing, as Done does. - A click anywhere on the isolation bar, the isolated object's name included, outside its back arrow, the breadcrumbs of the levels above and its buttons leaves isolation mode altogether, nested isolation included, as Exit Isolation Mode does ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=207)). As VectorCraft's own rules, the click stops editing an opacity mask, leaves symbol editing mode even while a group inside the symbol's art is isolated, together with the isolation the mode was entered from, and does nothing while a pattern is edited; a drag across the bar does not leave (`isolation_bar_background_click_exits_nested_isolation`). + - With a sublayer isolated, Exit Isolation Mode (the Layers panel menu item, the isolation bar's back arrow, the Control bar button and `object.exitIsolation`) goes back one layer at a time, isolating the parent layer, and leaves isolation mode from the top-level layer, as the [help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/isolate-objects.html) and an archived [help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=213) describe. As VectorCraft's own rules, Esc and the top-level layer's crumb leave isolation mode from a sublayer at any depth (`object.exitIsolation {all: true}`), a sublayer's crumb isolates that sublayer, a hidden or locked parent layer is not isolated, and a step up records no undo step (`exit_isolation_goes_up_one_layer_from_a_sublayer`, `isolation_bar_back_button_steps_up_through_sublayers`, `escape_leaves_an_isolated_sublayer_in_one_step`). - Numeric spinner arrows keep stepping while held with the mouse past the click timeout and stop on release (#6307; `a_held_spinner_arrow_repeats`). - Object › Vector Halftone keeps the selection box and hides selection marks on the temporary dots during Preview; turning Preview off or cancelling restores the original selection marks (#6369). - Tab shows and hides the panels (in the Type tool it types a tab) without moving the keyboard focus onto a field, so the next shortcut or letter still works; in dialogs and panel fields it moves between fields, one press each — a numeric field's scrub label is not a tab stop of its own, and the Transform panel's, Properties panel's and Control bar's W/H link comes after the fields it sits between (`one_tab_moves_from_a_field_to_the_next`). A field's up/down spinner, the chevron that opens its presets (Stroke Weight, font size, Rotate, Export for Screens' scale) and the Transparency row's opacity slider chevron are not tab stops either. Alt+↓ with no other modifier in a field with presets opens them with the keyboard focus on the chosen one, instead of stepping the field down; Enter picks the focused preset without pressing a dialog's OK, and after a pick or Escape the field has the keyboard focus again (`tab_goes_from_field_to_field_past_the_spinner_and_the_preset_chevron`, `tab_goes_from_the_opacity_field_past_its_slider_chevron`, `alt_down_opens_a_fields_presets_for_the_keyboard`, `escape_closes_a_fields_presets_and_returns_to_the_field`). @@ -1246,6 +1280,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. @@ -1262,7 +1297,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Compound paths:** Make keeps the backmost object's appearance and each contour; selecting a member in Direct Selection reads and changes the compound's fill rule in Attributes. Direction remains a per-member edit. Rendered holes, unchanged contour geometry, no-op history and Undo/Redo are covered by `engine/tests/it/compound_attributes.rs` (#1197). Behaviour reference: [public compound-path documentation](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/create-compound-paths.html). Make Compound Path on a group (such as outlined type) keeps the paint of its backmost path instead of drawing nothing, and compound paths joined into one keep their holes (#1537). - **Saved selections:** Select ▸ Save Selection… asks for a name and keeps the selection in the document (saved with the file, undoable, up to 25); each one is listed at the bottom of the Select menu and a click selects its objects again; Edit Selection… lists them to rename or delete, applied together on OK. A file's saved selections are capped and checked against its objects when it opens. Select ▸ Update Selection replaces the objects of the saved selection last recalled with the selected objects, in one undo step that marks the document changed (`select.update`). After Edit Selection… renames that saved selection, Update Selection replaces it under the new name; after Edit Selection… deletes it, Update Selection is disabled until another saved selection is recalled or the delete is undone. Undo and Redo do not change which saved selection is recalled. - - **Drawing modes:** in Draw Inside, a double-click with a selection tool outside the object being drawn into sets the drawing mode to Draw Normal, as Shift+D does. Pastes follow the drawing mode ([drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html)) (#3705): in Draw Inside, Paste, Paste in Place and Paste on All Artboards put the copies inside the object drawn into, in one undo step, Paste Remembers Layers aside; in Draw Behind, Paste in Place and Paste on All Artboards put them just below the selection; Paste in Front and Paste in Back ignore the mode. Shift+D cycles Draw Normal → Draw Behind → Draw Inside → Draw Normal, skipping Draw Inside unless one path, compound path or type is selected. With the object drawn into isolated (a double-click on it with the Selection tool), art drawn or pasted inside it takes isolation mode into its clip group, so it can be clicked and isn't dimmed, as art added in isolation mode belongs with what is isolated ([isolation mode](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/isolate-objects.html)) (#3705); undo or redo that removes the isolated object ends isolation mode. While Draw Inside lasts, a dotted open rectangle marks the corners of the object drawn into (#4319). + - **Drawing modes:** in Draw Inside, a double-click with a selection tool outside the object being drawn into sets the drawing mode to Draw Normal, as Shift+D does. Pastes follow the drawing mode ([drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html)) (#3705): in Draw Inside, Paste, Paste in Place and Paste on All Artboards put the copies inside the object drawn into, in one undo step, Paste Remembers Layers aside; in Draw Behind, Paste in Place and Paste on All Artboards put them just below the selection; Paste in Front and Paste in Back ignore the mode. Shift+D cycles Draw Normal → Draw Behind → Draw Inside → Draw Normal, skipping Draw Inside unless one path, compound path or type is selected. With the object drawn into isolated (a double-click on it with the Selection tool), art drawn or pasted inside it takes isolation mode into its clip group, so it can be clicked and isn't dimmed, as art added in isolation mode belongs with what is isolated ([isolation mode](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/isolate-objects.html)) (#3705); undo or redo that removes the isolated object ends isolation mode. While Draw Inside lasts, a dotted open rectangle marks the corners of the object drawn into (#4319). In Draw Behind, New Layer (the Layers panel's button, its menu, Ctrl/Cmd+L and the Layer Options dialog) puts the new layer directly below the current layer, at its level, as [the help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=234) describes and [drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html) lists; Ctrl/Cmd-click still puts it on top and Ctrl/Cmd+Alt-click below, and New Sublayer is not affected (VectorCraft's own rule). - **Drawing:** Pen, Curvature, anchor tools, Pencil, Paintbrush, Blob Brush, Smooth, Path Eraser, Join. Direction handles dragged with Direct Selection or the Anchor Point tool snap to smart guides, and Shift keeps them at 45° steps from their anchor. The Pen continues any open path from the end clicked, and while drawing, a click on an end of another open path joins the two into one (#776). The Curvature tool edits any selected path, whatever drew it, keeping its shape except where edited (#798): a click on a point makes it current and a drag moves it, re-curving only its two segments; double-click, or Alt-click on any point but an end of an open path, toggles it smooth or corner and Delete removes it; a click on a segment adds a point without changing the shape; with an end of an open path current, clicks go on from it and its other end closes it (`path.curvatureEdit`). An Alt-click on an end of a selected open path makes that end current without changing it, so the next click goes on from it, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-shapes-with-the-curvature-tool.html) describes for continuing a path; an Alt-click that starts a new path places a corner point, as later Alt-clicks do. Every point a drawing tool places snaps to Smart Guides through one snapper (#506): the Pen's and Curvature tool's anchors, the Pencil's ends, the shape tools' start and dragged corner or radius (Rectangle, Rounded Rectangle, Ellipse, Polygon, Star, Line Segment, Arc, Spiral, the grids), the Type tool's click and frame, a new artboard's corners. A filled Pencil path keeps a stroke of None (#1804, part of #1679). While a Pencil or Paintbrush stroke is drawn back to within Close Paths When Ends Are Within of its start, the cursor shows the closing ring and a release there closes the path, as [Draw straight lines with the Pencil tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-straight-lines-with-the-pencil-tool.html) describes for the Pencil. The [ and ] keys reach the Blob Brush, the Eraser and the Symbolism tools in the app (#1734, part of #1661). Blob Brush and Eraser Tool Options' Size is Fixed or Pressure with a Variation (#4590, #3961): with Pressure a pen stroke is Size − Variation wide where it presses lightest and Size + Variation where it presses hardest, and a mouse stroke keeps the Size. `path.blob` and `path.eraseRegion` refuse a Size outside 0.1 to 1000 pt and a Variation outside 0 to 1000 pt, also with Size set to Fixed, and the drawing commands that read pen values refuse a pressure outside 0 to 1, a tilt outside −90° to 90°, a rotation outside 0° to 360° and a point array of more than six numbers, with an error naming the key; the document, the selection and the undo history stay as they were. The pressure and tilt ranges are those of [Pointer Events](https://www.w3.org/TR/pointerevents3/); the Size, Variation and rotation ranges are VectorCraft's own values (`tests::draw2::pen_values_outside_their_ranges_are_refused`). @@ -1276,6 +1311,8 @@ 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 by 0.1 radian at each drag update in which the pointer's document y grows, and back by as much at each one in which it falls, Shift held keeps their turn, 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 (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}`. @@ -1299,13 +1336,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. @@ -1326,6 +1365,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. @@ -1354,6 +1394,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur As VectorCraft's own rule, a zoom marquee that Cmd+Space starts while the Type tool edits text keeps the marquee's Space rules after Cmd is let go: Space held since the press sizes it, Space pressed again moves it ([the help page](https://helpx.adobe.com/illustrator/using/viewing-artwork.html) describes holding the spacebar to move the marquee), and that Space types no space, nor does it during an animated zoom drag. With no zoom drag, Space types a space. Test: `canvas::tests::space_moves_a_text_edit_zoom_marquee_after_cmd_is_let_go`. - **Swatches panel clicks:** Ctrl/Cmd-clicking New Swatch makes a spot color, and Ctrl/Cmd+Shift-clicking it makes a global process color. - **Panel drag and drop:** art dragged off the canvas onto the Symbols panel becomes a symbol, art dragged onto the Swatches panel becomes a pattern swatch, and art dropped on the Brushes panel opens New Brush for that art; a symbol dragged onto the canvas places an instance where it is dropped, and a brush dragged onto a path is applied to it. + A symbol dragged from one document's Symbols panel and dropped on the canvas after another document became active places the dragged symbol, not a symbol of the same name in the active document (`symbol.placeFromDocument`). VectorCraft's own rules: the symbol, the symbols it nests and the resources they use are added to the active document as a drop of art from the other document adds them, in the same undo step as the instance; a symbol the document already has with the same art and Symbol Options is used, and one with the same name but other art or options is added under a free name ("Leaf 2"); the chip at the pointer shows the dragged symbol; a symbol whose document was closed before the drop places nothing and the status bar shows the error. Tests: `canvas::tests::a_symbol_dragged_from_another_document_places_that_documents_symbol`, `a_symbol_whose_document_closed_places_nothing`, `the_pointer_chip_of_a_dragged_symbol_shows_its_own_documents_symbol`, `tests::symbollib::another_documents_symbol_is_added_and_placed_in_one_step`. New Brush asks for the type of brush first, as the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy) describes. The Brushes panel's New Brush button, its menu's New Brush… and art dropped on the panel open the New Brush dialog, where Scatter Brush, Art Brush and Pattern Brush need selected or dropped art. OK opens that type's Brush Options for the new brush, and their OK makes the brush with the name and options set; Cancel in either dialog adds no brush (`ui.newBrush`). The menu's New Calligraphic Brush, New Bristle Brush and New Art, Scatter and Pattern Brush from Selection items still make a brush at once. - **Panel drag and drop:** art dragged off the canvas onto the Symbols panel becomes a symbol, onto the Swatches panel a pattern swatch and onto the Brushes panel an Art brush; a symbol dragged onto the canvas places an instance where it is dropped, and a brush dragged onto a path is applied to it. In the Brushes panel, a brush dragged onto another brush of its type goes before or after it, by the half of the tile or row the pointer is over, and a bar marks the slot while the brush is held there (`brush.move`); the move is one undo step. Brushes move only within their type, as the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page states: a brush dropped on a brush of another type stays where it is, and the status bar shows "brushes move only within their type". @@ -1377,6 +1418,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Before a press that draws a new path, the Pencil cursor shows a small star, as [Draw freeform paths with the Pencil tool](https://web.archive.org/web/20260926095638/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-freeform-paths-with-the-pencil-tool.html) describes; over a selected path within Edit selected paths' distance, which the press continues from an end or redraws, the star is not shown ([Reshape paths with the Pencil tool](https://web.archive.org/web/20260106004407/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/reshape-paths-with-the-pencil-tool.html)). Keep selected in the Pencil and Paintbrush Tool Options is on by default: while it is on, a stroke selects the path it draws or continues and replaces the earlier selection. While it is off, a new stroke leaves nothing selected, the earlier selection included, as the reference application starts the stroke by dropping it (#5752); a continued or redrawn path is deselected while the rest of the selection stays (`path.freehand` `keepSelected`). With two open paths selected, a Pencil stroke from an end of one that ends within Edit selected paths' distance of an end of the other connects them into one path with the first path's appearance, in one undo step, as [Connect two paths with the Pencil tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/connect-two-paths-with-the-pencil-tool.html) describes (`path.freehand` `connect`). + `path.freehand` and `brush.freehand` refuse a `connect` without `extend` with an error, and check a `connect` given with `extend` before a stroke of one point returns, so a bad one changes neither the path's brush nor the selection. Double-clicking the Shape Builder tool opens Shape Builder Tool Options ([Shape Builder tool options](https://web.archive.org/web/20260105172244/https://helpx.adobe.com/illustrator/using/building-new-shapes-using-shape.html)): with Consider Open Filled Paths as Closed off, a filled open path cuts regions as an unfilled one does; Pick Color From Color Swatches fills merged shapes with the current fill, the Left and Right arrow keys step it through the document's color swatches, and Cursor Swatch Preview shows the current fill and the swatches before and after it above the pointer; Selection Straight Line merges what the line from a drag's first point to its last crosses ([Setting Illustrator's Shape Builder Options](https://web.archive.org/web/20260615204453/https://creativepro.com/setting-illustrators-shape-builder-options/)); with Highlight Fill off, merge mode shades no regions (`shapeBuilder.merge` `openFilledAsClosed` and `pickColorFrom`). As VectorCraft's own rule, Consider Open Filled Paths as Closed counts an open path as filled when any of its fill rows draws (shown, painted and above 0% opacity), whichever row is on top, as the canvas paints it: a painted fill under an unpainted top fill closes the path, and a painted fill that is hidden or at 0% opacity does not. The region map, merges, erasing and Clicking Stroke Splits the Path follow that rule, and the Shape Builder takes the faces and edges of a Live Paint group that one of their fill or stroke rows draws and whose own opacity is above 0. Regression tests: `tests::build::shape_builder_closes_open_paths_by_the_fill_rows_that_draw`, `tests::build::shape_builder_stroke_split_closes_open_paths_by_the_fill_rows_that_draw` and `tests::build::shape_builder_takes_the_live_paint_faces_and_edges_that_draw`. With In Merge Mode, Clicking Stroke Splits the Path on in the same dialog, a click on a stroke in merge mode splits its path into the run of stroke under the pointer and the rest of the path, as the [Shape Builder tool options](https://web.archive.org/web/20260105172244/https://helpx.adobe.com/illustrator/using/building-new-shapes-using-shape.html) page describes; the run goes from the anchor or crossing point before the pointer to the one after it, and the pointer shows scissors over it. Highlight Stroke When Editable draws that run in the color chosen in its Color list (Red by default), and with Pick Color From Color Swatches the run takes the current fill as its stroke (`shapeBuilder.merge` `splitStroke`). @@ -1385,10 +1427,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`). @@ -1405,8 +1449,13 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Command Palette leaves out the engine commands that Edit › Keyboard Shortcuts marks as needing a value: a query with no default key and no menu bar item (Document JSON, Select All Unused in the Brushes panel), and a command that needs a value no menu item gives (Window › Transparency's `transparency.set`, Document Setup's units). Of those, it still lists the ones whose pick does something without params: Stop Script, Clear Script Console, Clear Plug-in Cache, Reset Preferences, Forget Import Matches, Begin Undo Group and End Undo Group, the six Save … Preset commands, Delete Gradient Preset, Pixel Snapping Options…, the Asset Export commands, New Symbol, Gradient Vector, Define Perspective Grid and Select Slice. Each panel is a result under Window › Show Panel, whose pick shows the panel and leaves one already showing as it is, and each Effect menu item is a result, named as the menu names it, whose pick runs what its menu item runs; while the item is dimmed, no dialog opens and the status line says why. A query of "layers" shows the Layers panel first. The search field's hint and the app bar's search tooltip say "Search commands, tools, panels and effects" (`palette` tests `the_palette_leaves_out_the_commands_a_pick_cannot_run`, `a_pick_of_a_session_command_runs_it`, `a_panel_is_a_result_whose_pick_shows_it`, `an_effect_is_a_result_whose_pick_runs_its_menu_item`; `shortcut_editor` test `a_command_given_a_key_that_needs_a_value_is_no_pick`). The Command Palette shows each result as a 20-point row, with no gap between rows, and shows 12 rows at a time in a list that scrolls; a short window shows fewer. A name too long for its row ends with "…". The list holds up to 50 results, and the line under it says how many matched ("14 results", "50 of 120 results. Keep typing to narrow them." or "No commands match"). Up and Down move the highlight and wrap at the ends, Page Up and Page Down move it by the rows shown and stop at the ends, and the highlighted row scrolls into view; after a scroll with the wheel, the highlight moves to the nearest row in view. A click anywhere on a row runs it. Screen readers stay on the search field, whose description names the highlighted result and its place among every match ("2 of 14: …", or "2 of 120: …" when the list holds 50); the rows are list items, the highlighted one selected, and the keyboard focus goes back to where it was when the palette closes, unless a pick opened a dialog (`palette` tests `results_are_compact_rows_that_touch`, `the_footer_counts_the_results`, `with_no_match_enter_runs_nothing`, `the_sixteenth_result_is_reached_by_keyboard_and_runs`, `page_keys_move_by_a_page_without_wrapping`, `a_wheel_scroll_keeps_the_highlight_in_view`, `the_row_under_the_pointer_is_the_one_highlighted`, `a_long_name_ends_with_an_ellipsis`, `the_popup_stays_inside_a_short_window`, `a_click_anywhere_on_a_row_runs_it`, `screen_readers_hear_the_highlighted_result_and_the_count`, `closing_gives_the_focus_back`). A press of any pointer button outside the Command Palette closes it: a click, a right-click or the start of a drag. While the palette is open, the canvas, the toolbars, the docked panels and the app bar under it do not respond to the pointer, so the press that closes the palette does not press a tool button or another control there. A window drawn above them, such as a progress window, still gets its click, and that click also closes the palette (`palette` tests `a_click_on_the_canvas_closes_the_palette`, `a_click_on_another_control_closes_the_palette_without_pressing_it`, `a_right_click_or_a_drag_outside_closes_the_palette`, `a_click_on_a_window_above_closes_the_palette_and_reaches_it`, `the_click_that_opens_the_palette_does_not_close_it`). + 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. @@ -1416,6 +1465,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Layer Options for several highlighted rows shows the first row's settings, and OK changes only the settings set in the dialog: each row keeps its own color, Template, Lock, Show, Print, Preview and Dim Images otherwise (`crates/ui-egui/src/dialogs/layer_options.rs` tests). As VectorCraft's own rule, a layer color (`layer.setProps`, `layer.new`, `layer.newSublayer`) or a Live Paint Gap Preview Color (`livePaint.gapOptions`) given as a hex color with an alpha part (`#rrggbbaa` or `#rgba`) is an error and changes nothing, instead of being set without its alpha. Regression tests: `a_layer_color_with_an_alpha_part_is_refused` in `crates/engine/src/tests/layers.rs` and `a_gap_color_with_an_alpha_part_is_refused` in `crates/engine/src/tests/build.rs`. Panel Options › Locate Selected Objects (beyond Illustrator, off by default): when the last selected object changes on the canvas or by a command, the panel opens the layers and groups around it and scrolls to its row, as Locate Object does, without highlighting the row; when Show Layers Only, a search or the filter leaves the object without a row, the panel opens no rows for it and scrolls as with the option off. + With Panel Options › Show Layers Only on, Locate Object is named Locate Layer and highlights the layer that holds the selected object instead of the object's own row, which that mode does not list (help page: https://helpx.adobe.com/illustrator/desktop/manage-layers/create-and-organize-layers/locate-objects-in-the-layers-panel.html). As VectorCraft's own rules, the bottom bar's button and a row's menu are renamed too, the innermost sublayer holding the object is the one highlighted, a layer row locates itself, and the panel opens the layers around it. Locate Object or Locate Layer run again on the row it already highlighted opens the layers around that row again and scrolls to it, VectorCraft's own rule (`locate_layer_highlights_the_layer_holding_the_object` in `crates/engine/src/tests/layers.rs`, `with_show_layers_only_locate_object_becomes_locate_layer` and `a_repeated_locate_reveals_the_row_it_already_highlighted` in `crates/ui-egui/src/panels/layers/tests.rs`). - **Drawing aids:** Smart Guides and snapping (moving, with the Selection, Group Selection or Direct Selection tool, and resizing by the bounding-box handles with the Selection or Free Transform tool, Shift and Alt too: the dragged corner or side lands on the other objects' anchors and centres ("anchor", "center") or lines up with their edges and centres (a line and "align"); with Smart Guides › Spacing Guides, a moved selection that lines up with nothing along an axis lands as far from its neighbour as two other objects of its row or column are apart, or halfway between its two neighbours, the equal gaps marked; with View › Snap to Grid on, a moved selection lands on the grid instead, by whichever of its edges is nearest a gridline on each axis (the center does not snap), #740, #1816; the Rotate, Scale, Shear and Reflect tools drag from the anchor they grab and snap the pointer the same way, so a corner dragged onto another object's anchor scales exactly onto it, #482; anchors dragged with Direct Selection: the one pressed on lands on other anchors, its own path's that stay put among them, on path segments or in line with them, the others following, Shift keeps 45° steps, and with Smart Guides off Snap to Point pulls it onto anchors; the Artboard tool snaps artboards, and their bleed, to other artboards, bleeds and art, the grid or whole pixels while moving, copying and resizing them, and the Transform panel shows and edits the active artboard's X/Y/W/H; drawn points, #506: hovering shows where the press goes, the point lands on the other objects' anchors, centres and paths ("anchor", "center", "path") or lines up with their anchors, edges and centres ("align"), the Pen's on the path being drawn too, near a construction guide through the anchor before it on that guide (Preferences › Smart Guides › Construction Guides and Angles), and with Shift kept to its 45° step or a square's diagonal it slides along that way into line; the targets are gathered once per document state, from the art in the window, and the anchors, centres and lines near the pointer are found by bisection, so hovering never rescans the document), guides dragged out of the rulers (#451: they snap as moved guides do, Shift to the ruler's ticks; with the Artboard tool they are artboard guides, which run across their artboard only and move, copy and delete with it, `guide.add {artboard}`) that the Selection, Direct Selection and Group Selection tools then pick and drag (#414: the selected guides highlight and move together, Alt copies them, Shift snaps the dragged one to the ticks, otherwise it snaps to pixels, the grid or the edges, centres (so the sides' midpoints) and anchors of the art and the artboards, or with Smart Guides off Snap to Point pulls it onto anchors; Shift-clicked they join the selected art, and Shift-added art keeps them, so guides and art are selected together in either order, Delete then deleting both in one step; the arrow keys nudge them, Delete deletes them, dragging one back onto its ruler deletes it, Lock Guides and Hide Guides leave them alone; `guide.list`, `guide.select`, `guide.move` and `guide.remove` reach agents), a right-click on either ruler or the origin box to pick the document's units (the current one checked; `document.setUnits`, one undo step, #528), and Draw Normal / Behind / Inside modes. Smart Guides: a point drawn with the Pen or a shape tool, and an anchor dragged with Direct Selection, snaps to where paths and ruler guides cross, labelled "intersect" (#1658, part of #1602; a moved selection's own anchors don't, except the anchor the Selection tool grabbed it by). A selection the Selection tool grabs by one of its anchors snaps that anchor onto the other objects' paths ("path"), and where a path crosses another path or a ruler guide ("intersect"), in the order Direct Selection uses for a dragged anchor; when the anchor lands on a path, the selection's bounds do not also line up with other objects (#7411). The archived 2007 [user guide](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=55) (page 49) says Smart Guides align the pointer of a moved object to existing paths. Snapping onto paths only when the selection was grabbed by an anchor is VectorCraft's own rule; a selection grabbed anywhere else still lines its bounds up. Tests: `select::tests::a_move_grabbed_by_an_anchor_lands_it_on_another_path`, `a_move_grabbed_by_an_anchor_lands_it_where_paths_cross` and `a_move_grabbed_by_an_anchor_lands_it_where_a_path_crosses_a_ruler_guide`. With Smart Guides › Measurement Labels on, the Line Segment tool labels the segment being drawn with its distance, angle and X and Y offsets (`D`, `Angle`, `dX`, `dY`), and the Pen, Curvature and Smart Pen tools label their rubber band the same way when Enable Rubber Band is on (#2983). A move that Shift keeps level, upright or diagonal stays on that line when it snaps, with the Selection, Group Selection or Direct Selection tool. It slides along the line until the selection lands on the grid or on whole pixels, lines up with the other objects or is spaced evenly with them, or until the line passes an anchor or crosses a ruler guide near the point the selection was grabbed by. A level or upright move snaps along its own axis only. Snap to Last Location: with Smart Guides on and Preferences › Smart Guides › Snap to Last Location on (off by default, VectorCraft's own choice), a selection moved by dragging with the Selection, Group Selection or Direct Selection tool, Shift too, goes back to where the move began while it is within Snapping Tolerance of it, labeled "last location"; an Alt copy is not pulled back onto its original, and with View › Snap to Grid or Snap to Pixel on the move snaps to the grid or to whole pixels instead (`prefs.set` key `snapToLastLocation`). The public [Smart Guides options](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/smart-guides-options.html) page lists the option as snapping objects back to their previous position; the distance, the label, the copy rule and the grid and pixel rule are VectorCraft's own. Tests: `select::tests::snap_to_last_location_puts_a_move_back_where_it_began`, `select::tests::snap_to_pixel_wins_over_snap_to_last_location`, `direct::tests::snap_to_last_location_puts_a_path_moved_by_its_anchor_back`, `direct::tests::snap_to_pixel_wins_over_snap_to_last_location_for_a_path_moved_by_its_anchor`, `tests_prefs::snap_to_last_location_puts_a_dragged_square_back`. @@ -1496,6 +1546,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`). @@ -1539,6 +1590,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Manual kerning on inline graphics:** a manual kerning value on an inline graphic's character spaces it from the next character in reading order by the same distance as on a letter of its run's size, in left-to-right, right-to-left and vertical type; Auto and Optical kerning still apply no font pairs to it. This is VectorCraft's own rule. Test: `manual_kerning_on_an_inline_graphic_spaces_it_like_a_letter`. - **Inline graphics in symbol art follow their symbols:** when a symbol changes, type with an inline graphic of it is laid out again wherever the type is: in the layers, in the art of other symbols, graph designs and pattern tiles, and in opacity masks. A symbol's type is laid out before the type that shows that symbol inline, so a symbol whose art holds an inline graphic, its instances and the inline graphics that show it take its new size. Opening and reverting a document and Refresh Font List resolve them in the same order. An inline graphic of a symbol whose art shows that symbol inline, directly or through other symbols, is an empty slot. This is VectorCraft's own rule. Tests: `inline_graphics_in_symbol_art_follow_their_symbol`, `inline_graphics_in_masks_and_pattern_tiles_follow_their_symbol`, `symbols_are_resolved_after_the_symbols_they_show_inline`, `a_symbol_that_shows_itself_inline_is_an_empty_slot` in `crates/engine/src/tests/inline.rs`. - **Inline graphics of symbols that hold other symbols:** an inline graphic of a symbol whose art holds an instance of another symbol is sized by that symbol's own art, placed by the instance, and follows it when that symbol changes. A symbol's type is laid out after the type in the art of the symbols its instances show. An inline graphic of a symbol whose art reaches that symbol through an instance and an inline graphic is an empty slot; an instance that does not size the art, such as one a clipping path hides, does not count. An instance of a missing symbol, of a symbol without art, of a symbol that holds an instance of itself, or of a symbol whose art nests symbols 32 deep is measured by the 20 × 20 square. This is VectorCraft's own rule. Tests: `an_inline_graphic_follows_the_art_of_a_symbol_nested_in_its_symbol`, `symbols_are_resolved_after_the_symbols_their_instances_show`, `a_symbol_that_shows_itself_through_an_instance_is_an_empty_slot` in `crates/engine/src/tests/inline.rs`; `a_symbol_nested_in_symbol_art_is_measured_by_its_own_art`, `nested_instances_without_art_of_their_own_are_measured_by_the_square`, `only_instances_that_size_a_symbols_art_make_it_depend_on_their_symbol` in `crates/doc/src/inline.rs`. +- **Inline graphics after an edit, in large documents:** after an edit, a document with symbols checks its type's inline graphics again only in the layer trees that differ from the document the last check left, as long as the symbols, graph designs, pattern tiles and the symbols' natural sizes and 9-slice guides are unchanged and each symbol the type shows measures as before; otherwise every tree is checked, as before. The document and the texts laid out again are the same either way. Measured in one process (thread CPU time, median of 7 runs, 100 groups, three symbols, one inline graphic, one rectangle moved): the check went from 1.0 ms to under 0.05 ms at 50,000 rectangles and from 5.7 ms to under 0.05 ms at 200,000, and a whole `object.move` from 1.55 ms to 0.7 ms and from 11.9 ms to 6.2 ms; the rest of an edit still walks the document. Tests: `refreshing_only_changed_trees_matches_the_full_pass` in `crates/engine/src/tests/inline.rs`; `a_pass_after_an_edit_checks_only_the_trees_the_edit_changed`, `changed_symbols_or_symbol_sizes_take_the_full_pass` in `crates/doc/src/inline.rs`; timings: `inline_refresh_perf` (ignored). - **Recent font pickers (#3515):** The shared Character, Properties, Glyphs and Find Font family picker lists recently applied families first, once each, in most-recent order and limited by Preferences › Type › Number of Recent Fonts. Search and filters apply to both sections; unavailable families are omitted. Section headings cannot be selected or previewed. Confirmed character-range font edits update the same saved history; previews and failed edits do not. Requirement: [issue #3515](https://github.com/storytold/vectorcraft/issues/3515). - **Show samples on white (a VectorCraft addition):** Preferences › Type › Show samples on white (`fontSamplesOnWhite`, off by default) draws each family's sample in every font menu, and in Type → Font in the in-window menu bar, in dark type on a white area in every interface brightness. A highlighted row's color shows above and below the white area, and the names and the rest of the menu keep the interface's colors. The checkbox is dimmed while Enable in-menu font previews is off. Tests: `crates/ui-egui/src/tests/font_menu.rs`, `crates/ui-egui/src/font_menu/tests.rs`, `crates/ui-egui/src/prefs_dialog/tests.rs`. - **Show Similar Fonts: families without numbers come last:** in a font menu's Show Similar Fonts list and `text.similarFonts`, a family whose faces give none of the numbers the list compares (PANOSE, weight, width, heights, average width, italic angle) in common with the chosen family comes after every family of its script group that shares one, instead of right after the chosen family as an exact match. This is VectorCraft's own rule; the help page (https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/font-options-overview.html) describes the list only as fonts that look like the chosen one. Regression tests: `a_family_without_numbers_comes_after_the_measured_ones` and `likeness_is_a_distance` in `crates/text/src/tests/similar.rs`. @@ -1546,8 +1598,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`). @@ -1566,6 +1619,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With a Type tool and exactly one character selected, the canvas shows that character's alternate glyphs in a row beside it, and a click on one replaces the character's glyph, as [Replace characters with alternate glyphs](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/replace-characters-with-alternate-glyphs.html) describes ("Replace a character with on-canvas alternate glyphs"). The row shows at most five alternates, and an arrow at its end opens the Glyphs panel on Alternates for Current Selection when the character has more, as the [reference manual](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=479) describes. A click runs the command the panel's double-click runs, as one undo step, so a letter of an Arabic word keeps the word joined. These rules are VectorCraft's own: the row leaves out the glyph the character is drawn with and puts the default glyph first for a character drawn with an alternate; it stands under a character of horizontal type and on the right of a character of vertical type, or on the other side when the canvas ends there or the Contextual Task Bar is there; Preferences › Type › Show Character Alternates (`showCharacterAlternates`, on by default) turns it off. Tests: `canvas::alternates_bar::tests`, `tests::prefs::show_character_alternates_preference_is_on_by_default_and_saved`. With an OpenType font in the Glyphs panel, the Show menu and the panel menu list the font's glyph categories after Alternates for Current Selection, and choosing one restricts the grid to the glyphs of that kind, as the [Glyphs panel overview](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/glyphs-panel-overview.html) describes. The categories are Ligatures, Swash, Stylistic Alternates, each stylistic set by the font's name for it (else Set N), Small Caps, Ornaments, Fractions and Figures, each listed only when the font's `GSUB` features give it glyphs; which features make up each category and their order are VectorCraft's own. A font without the chosen category shows Entire Font. `text.glyphCategories` lists them for agents. Tests: `fontdb::gsub::tests` in the text crate, `panels::glyphs::tests::the_show_menu_lists_the_fonts_opentype_categories`, `tests::fontlist::glyph_categories_list_the_glyphs_of_each_kind_of_feature`. The OpenType panel's Stylistic Sets menu offers `ss01`–`ss20` sets present in the selected text's font, using the font's custom labels when available and numbered labels otherwise. Sets can be combined and deselected individually. With mixed fonts, the menu shows the first selected character's font's sets and applies the feature tag to all selected text; a font without that set draws unchanged. The mixed-font rule is a VectorCraft design choice. Behavior reference: [Add stylistic sets to selected text](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/add-stylistic-sets-to-selected-text.html) and the [OpenType specification](https://learn.microsoft.com/en-us/typography/opentype/spec/features_pt). + The OpenType panel menu has a Stylistic Sets submenu after Reset OpenType Features, with the same sets, labels and checks as the panel's Stylistic Sets button; a set chosen there turns on or off for the characters the panel acts on in one undo step, keeping their other features, and the submenu is disabled with no text selected or when the font offers no sets. The 2019 user guide ([the help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf)) has stylistic sets chosen from the OpenType panel menu. The submenu's place in the menu is VectorCraft's own. Tests: `panels::opentype::tests::the_panel_menu_stylistic_sets_submenu_turns_sets_on_and_off`. With Show East Asian Options on, the OpenType panel menu has H or V Style and Roman Italics, as [Format East Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html) describes. H or V Style sets the feature tag `hkna`, which draws kana with the forms the font makes for horizontal type, and with `vkna` for vertical type in vertical type; Roman Italics sets `ital`, the font's italic forms of half-width alphanumerics ([OpenType feature list](https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist)). Each is checked when every selected character has it and turns it on or off for all of them in one undo step; character styles carry both in OpenType Features. Tests: `panels::opentype::tests::kana_style_and_roman_italics_turn_on_and_off`, `features::tests::kana_style_and_roman_italics_are_kept_and_shaped`. `text.setStyle {stroke, strokeWidth}` sets the character stroke's color and weight of the selected type or of a range of its characters (the weight in document points, as `stroke.set` sets it), in the same undo step as the command's other changes. Tests: `tests::textedit::set_style_sets_the_character_stroke`. - **Paragraph alignment:** the shared Paragraph/Properties alignment row leaves every button unselected when the paragraphs it acts on differ. Auto resolves per paragraph; choosing an alignment uses the existing command. Headless paragraph_mixed_alignment_* regressions exercise mixed → Center → Undo, caret/uniform states, Unicode range boundaries, Auto/direction, split runs and grouped text. These regressions and full integration CI pass. Original captures confirm mixed → Center → Undo in the existing alignment-button layout. The [public Paragraph panel guide](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/paragraph-panel-overview.html) lists the seven controls, but does not specify mixed-state rendering. Other paragraph fields remain outside this change; scores and hours unchanged. @@ -1750,6 +1804,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`. @@ -1763,10 +1818,12 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Swatches:** names follow the colour model and are unique; Swatch Options (process/spot, Global, Gray/RGB/HSB/CMYK/Web, live preview); editing a global or spot swatch recolours every linked fill, stroke and text run in one undo step; multi-select and delete with confirmation; New Swatch and New Color Group dialogs (a group from the selected artwork's colours); swatches in colour groups convert, separate and count like any other. The Swatches panel selects ranges and whole groups, has a find field, and drags swatches to reorder, regroup or paint art; Add Used Colors, Select All Unused, Merge, Ungroup and Sort by Kind; a CMYK document keeps applied colours in CMYK. Swatch libraries: nine generated colour libraries, seven gradient libraries (among them Organic Fades, soft perceptually mixed multi-stop fades that thin out to transparent, and Holographic, seven opaque linear foils of narrow pastel and pearl bands and seven radial glows that fade out to a clear edge) and three pattern libraries (Geometric Patterns; Grit Textures with eight seamless grain, speckle, stipple, scratch and fleck tiles; and Optical Effects with eight of VectorCraft's own seamless wave, ring, warped-check, stripe, chevron and lens tiles; their swatches bring their patterns) in a library panel, saved as `.vcswatches`, `.gpl`, swatch exchange (`.ase`) or CSS, and loaded from `.vcswatches`, `.gpl` and `.ase` files (`.ase` both ways: RGB, CMYK, Lab and Gray; global, spot and process; groups) and from color books (`.acb`, read only: the RGB, CMYK or Lab colors of a book such as a Pantone book a user owns, named with its prefix and suffix, spot unless it says process, #831); `swatch.library.copyToUser` copies a loaded library into the User Defined folder without replacing a file, and a file with the same extension and bytes as a User Defined library opens as that library. Tints of global and spot colours ("Name 40%") stay linked and separate as a percentage of their plate. Spot colours can be defined in Lab (Spot Colors options). A built-in [Registration] swatch prints on every plate. Right-clicking a swatch in either list or thumbnail view selects it without applying paint and offers Swatch Options…, Duplicate Swatch and Delete Swatch for that item. None, [Registration] and missing swatches disable these actions. Existing active-item multiselection is retained; actions still target only the clicked item. Evidence: `panels::swatches::tests::context_menu` harness tests cover all five views, selection, dialog dispatch, duplicate/delete and Undo. All 39 Swatches tests pass; the regression fails with the menu hooks removed. Rendered headless list and thumbnail menus were inspected, and a fresh local deep CodeRabbit review reported zero findings. Full workspace CI passed on Linux/WSL on the merged branch (all 13 gates), including the test-helper correction for the upstream compile error tracked in #7727; native Windows full CI has two unchanged engine-test failures. Scores and estimates unchanged. Validation on 2026-11-15: native Windows formatting, workspace Clippy and all 39 focused Swatches tests passed. Windows full CI stopped at unchanged engine tests `tests::package::a_confined_package_names_files_outside_the_read_root_by_name` (slash-sensitive report assertion) and `tests::plugins::plugin_storage_behind_a_link_is_left_alone` (storage-link setup returned AlreadyExists). Both cases pass in the Linux/WSL full CI run, which passed all 13 gates. No engine or CI workflow changes are included. + The panel's Delete Swatch and Swatch Options (footer buttons and panel menu), New Color Group and Save Swatch Library treat only None and [Registration] as reserved, so a user swatch or color group whose name starts with `[` can be deleted, edited, grouped and saved; selected names the document no longer holds are left out (`panels::swatches::tests::bracketed_user_swatches_and_groups_can_be_deleted_and_edited`). Dragging swatches onto Delete Swatch deletes them ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=136), Replace, merge, or delete swatches section, lists this drag as one of the ways to delete the selected swatches): a swatch or color group dragged from the Swatches panel, in any view, and released on the Delete Swatch button is deleted through `swatch.delete`, even while nothing was selected and the button is disabled for clicks. A swatch that is part of the selection carries the other selected swatches of its kind with it. VectorCraft's own rules: the drop asks first as a plain click does, and Alt does not skip the question; Cancel keeps everything, and OK deletes them in one undo step; None and [Registration] are never taken; the button is enabled while swatches are selected or while a swatch or group of the active document is being dragged, and it is outlined only while such a swatch or group is held over it, so a paint from another panel, art and a swatch dragged from another document delete nothing. Tests: `panels::swatches::tests::swatches_dropped_on_delete_swatch_are_deleted_after_asking`, `delete_swatch_ignores_other_drags`. Editing, renaming, deleting or merging a global swatch also changes the colors linked to it in graph designs, the art of brushes and the tile that pattern editing's Cancel puts back, in the same undo step as the rest of the art; Default Swatches with replace unlinks them there too. A swatch step in `command.batch` (Delete, Swatch Options, Merge, Edit Color Group) changes the fill and stroke for new art as the command run on its own does, so art drawn later in the batch or after it takes the same paint; a batch that fails, and a canceled batch preview, put back the paints it started with, and a canceled Swatch Options preview leaves them as they were. These swatch commands also change the fills and strokes of the appearance new art takes, and Undo and Redo of the command or the batch put the paints for new art back with the swatches. Spot Colors options (`swatch.spotOptions`) and Default Swatches with replace (`swatch.resetDefaults {replace: true}`) as `command.batch` steps also change the fill and stroke for new art as each command run on its own does: a fill or stroke linked to a Lab spot swatch keeps its link and tint and takes the Lab values or their CMYK equivalent, and one linked to a swatch the replace removes keeps its color and loses the link. Evidence: `swatch_steps_in_a_batch_change_the_new_art_paints_as_commands_do`, `spot_colors_options_in_a_batch_change_the_new_art_paints_as_the_command_does`, `default_swatches_replace_in_a_batch_unlinks_the_new_art_paints_as_the_command_does`, `undo_and_redo_of_a_swatch_edit_put_back_the_new_art_paints`, `swatch_edits_reach_the_paints_of_the_new_art_template`, `a_failed_batch_puts_back_the_new_art_paints_a_swatch_step_changed` and `canceling_a_swatch_options_preview_keeps_the_new_art_paints` in `crates/engine/src/tests/swatches.rs`. Add Used Colors (`swatch.addUsedColors`) and Select All Unused (`swatch.unused`) look colors, swatch names, links, tints and gradients up in hash sets instead of searching every swatch and color for each color or linked paint (New Color Group from artwork too), and New Swatch with several colors (`swatch.new`), New Color Group (`swatch.newGroup`) and Edit Color Group (`swatch.editGroup`) name their new swatches from one set of the names already taken. The new swatches keep their names, order and links, and Select All Unused lists the same swatches. Evidence: `add_used_colors_adds_each_new_color_once_with_free_names`, `add_used_colors_global_links_every_paint_of_a_new_color`, `unused_matches_links_tints_colors_gradients_and_patterns_exactly`, `new_swatches_from_colors_are_numbered_after_names_already_taken`, `new_color_group_numbers_its_colors_after_the_group_and_its_moved_swatches`, `new_color_group_from_artwork_lists_each_color_once_with_free_names` and `edit_color_group_numbers_extra_colors_after_the_names_it_keeps` in `crates/engine/src/tests/swatchcmds.rs`; `free_swatch_names_match_naming_each_swatch_as_it_is_added` and `free_swatch_names_match_new_swatch_names_as_swatches_are_added` in `crates/doc/src/swatches.rs`. + When Add Used Colors and New Color Group link the selected art's paints to global swatches, they look each selected object's groups and layer up in a set of the selected ids instead of searching the whole selection for each one, so linking 20,000 selected rectangles takes 16 ms of CPU time instead of 128 ms (`cargo run --release -p vectorcraft-engine --example link_colors_bench`). The same paints are linked, in the same order. Evidence: `mapping_within_ids_matches_a_search_of_the_ids` in `crates/doc/src/swatches.rs`. - **Colorized images (#1466):** a fill color applied to a selected grayscale or 1-bit image (`paint.setFill`) colorizes it with black, white, a process color or a spot color, and refuses a process color when the image has an alpha channel ([Convert color modes](https://web.archive.org/web/20251220223850/https://helpx.adobe.com/illustrator/desktop/manage-colors/select-and-adjust-colors/convert-color-modes.html), "Colorize Grayscale or 1-bit images"); black and white are accepted there too. The canvas draws each pixel in the color as far as the pixel is dark, with white pixels transparent; PDF export writes the image in the color (a spot color as its ink, Registration in every ink) with the image as its soft mask; Separations Preview and printed separations show it on its color's plates; native files keep the color. SVG writes the fill color through a coverage mask (or a colorized PNG in Tiny 1.2); EPS writes binary coverage as an image mask in the color's ink, and a grayscale image as ink samples scaled by coverage, with white pixels left out at Level 3 and gray midtones written over white. The prompt for deleting several swatches and groups uses the interface language's plural form for the count. Evidence: `deleting_several_swatches_uses_each_count_form` in `crates/ui-egui/src/panels/swatches/tests.rs`. - **Colorized images (#1466):** a fill color applied to a selected grayscale or 1-bit image (`paint.setFill`) colorizes it with black, white, a process color or a spot color, and refuses a process color when the image has an alpha channel ([Convert color modes](https://web.archive.org/web/20251220223850/https://helpx.adobe.com/illustrator/desktop/manage-colors/select-and-adjust-colors/convert-color-modes.html), "Colorize Grayscale or 1-bit images"); black and white are accepted there too. The canvas draws each pixel in the color as far as the pixel is dark, with white pixels transparent; PDF export writes the image in the color (a spot color as its ink, Registration in every ink) with the image as its soft mask; Separations Preview and printed separations show it on its color's plates; native files keep the color. EPS and SVG write the image's own pixels. @@ -1784,6 +1841,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`). @@ -1804,8 +1862,11 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Eyedropper sources (#1251):** ordinary and Shift clicks, Shift+Alt appearance append, raster pixels and gradient-stop sampling can read visible locked/template art and sources outside isolation. Sampling leaves the source and selection intact; Alt reverse still uses editable hits, and hidden art stays excluded. Engine/tool/hit regressions cover the editing boundary, color models and one-step Undo/Redo. The general object/image workflow is described in [public HelpX](https://helpx.adobe.com/illustrator/using/tool-techniques/eyedropper-tool.html); the lock/isolation expectations come from the user report and these regressions, without a new full-parity measurement. - **Eyedropper colors in a CMYK document (#2276):** a CMYK image (a four-component JPEG, or an 8- or 16-bit chunky CMYK TIFF) gives its ink amounts as they are, and an RGB image's pixel or an RGB color given to `paint.setFill`, `paint.setStroke`, `paint.sampleColor` or `swatch.new {color}` (hex input and gradient stops included) is separated through the color settings' CMYK working space and intent, as Document Color Mode converts it. With the default Generic CMYK, RGB 83/170/223 separates to C62 M19 Y0 K0, where the profile-free formula gave C63 M24 Y0 K13. - **RGB input to other commands in a CMYK document:** type colors (`text.create`, `text.setStyle`, `text.setRangeStyle`), a Shape Builder hex fill, `paint.editGradient` stops, freeform gradient points, gradient mesh points (the Mesh tool gives a new point the fill's color in its own model), the Symbol Stainer's color and the swatch commands (`swatch.new {colors}`, `swatch.newGroup`, `swatch.editGroup`, `swatch.edit`) separate RGB through the color settings as `paint.setFill` does: with Generic CMYK, `text.setStyle {fill: "#53aadf"}` gives C62 M19 Y0 K0. A color a swatch already has keeps its model, and a swatch color given with `mode` is converted into that mode only. - - **Generic CMYK (SWOP-like):** each ink's 40% and 50% tints gain as [CGATS TR 001](https://registry.color.org/cmyk-registry/cgats_tr_001) gives for SWOP printing, and separations stay within SWOP's [300% total ink limit](https://en.wikipedia.org/wiki/Specifications_for_Web_Offset_Publications). The paper, solid and overprint colors, the black-generation curve and the black point are VectorCraft's own values: RGB black separates to 90% black under neutral cyan, magenta and yellow that fill the ink limit (C75 M68 Y67 K90). + - **Generic CMYK (SWOP-like):** each ink's 40% and 50% tints gain as [CGATS TR 001](https://registry.color.org/cmyk-registry/cgats_tr_001) gives for SWOP printing, and separations stay within SWOP's [300% total ink limit](https://en.wikipedia.org/wiki/Specifications_for_Web_Offset_Publications). The paper, solid and overprint colors, the black-generation curve and the black point are VectorCraft's own values: RGB black separates to 90% black under neutral cyan, magenta and yellow that fill the ink limit (C75 M68 Y67 K90). The ICC profile written for it (embedded in exports) gives the paper as its media white point, and its colorimetric Lab → CMYK table is the inverse of its CMYK → Lab table, without black-point compensation; the perceptual and saturation tables keep compensation. - **Swatches made from a shown color in a CMYK document:** the Color panel menu's Create New Swatch, an Alt-click on the Swatches panel's New Swatch button, the New Swatch dialog for a gradient, a Fill or Stroke proxy or the Gradient panel's thumbnail dropped on the Swatches panel (or Alt-dropped on a swatch of its kind), and the Gradient panel's Add to Swatches and Save to Swatches keep each color's model, as the Color Guide's and Color Themes' saved colors do: an RGB object's color gives an RGB swatch, and a gradient's RGB stops stay RGB. + - **Color Themes Set Active Color:** a button on the Color Themes panel's Create tab makes the selected theme color the current color, the action the [help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=222) describes for creating a color theme. VectorCraft's own rules: the color goes to the proxy in front (Fill or Stroke), on the selection and the default for new art, in its own color model, through `paint.setFill` or `paint.setStroke`; with characters selected with the Type tool, only those characters take it and the default for new art stays as it was, as with a swatch click; a click is one undo step, a click that changes no art adds none, and the button is off without a document. Tests: `set_active_color_*` in `crates/ui-egui/src/panels/color_themes.rs`. + - **Color Themes find field:** on the Color Themes panel's My Themes tab, Show Find Field in the panel menu shows a Find field that lists only the saved themes whose names hold its text; the [help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=255) describes looking up a saved theme by its name this way (printed page 249). VectorCraft's own rules: the menu item is checked while the field shows and is off in a new session; a name matches when it holds the text anywhere, in any letter case, with spaces at either end of the text ignored; colors are not searched; the list keeps its saved order and shows No matches. when nothing matches; a picked theme the field hides stays picked, but Edit Theme, Add to Swatches and Delete Theme are off until the list shows it again; turning the field off lists every theme, and turning it on again in the same session restores its text. The field does not change the saved themes or `colorTheme.list`. Tests: `show_find_field_toggles_the_find_field_on_my_themes`, `the_find_field_lists_themes_whose_names_hold_its_text`, `no_saved_themes_is_not_no_matches`, `a_theme_the_find_field_hides_is_not_acted_on` and `footer_buttons_are_off_for_a_hidden_pick` in `crates/ui-egui/src/panels/color_themes.rs`. + - **Color Themes sliders:** on the Color Themes panel's Create tab, a Color Mode menu (CMYK, RGB, Lab and HSB) shows a rail and a number field for each component of the selected theme color, beside its hex field; the [help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=221) describes changing the selected color's values in these color systems or as hex while making a theme. VectorCraft's own rules: the menu starts in the selected color's own model (HSB for a gray) and keeps the mode picked while the app runs; picking a mode changes no color; the ranges and whole-number steps are the Color panel's (Lab a and b from -128 to 127), a number past the range sets its end and text that is not a number changes nothing; a CMYK edit keeps the color CMYK and a Lab edit keeps it Lab, while RGB and HSB edits make it RGB, and the theme saves and goes to Swatches in those models; an edit works as a hex edit does: with a harmony rule the edited color becomes the theme's base and is selected, and in Custom only the selected color changes. Tests: `the_create_tab_offers_cmyk_rgb_lab_and_hsb_sliders`, `a_slider_edit_changes_only_the_selected_custom_color`, `the_sliders_keep_the_numbers_they_set`, `with_a_rule_a_slider_edit_rebuilds_the_theme_from_the_edited_color` and `cmyk_and_lab_slider_edits_keep_their_models` in `crates/ui-egui/src/panels/color_themes.rs`. - **Sample Color from Screen:** an eyedropper button in the Color Picker and `ui.sampleScreenColor` (which can be given a key in Keyboard Shortcuts) pick a color anywhere on the screen with the system's sampler: `NSColorSampler` on macOS, the XDG desktop portal's [PickColor](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Screenshot.html) on Linux, a still copy of every monitor under a crosshair on Windows, and the EyeDropper API in browsers that have it. The color becomes the fill or the stroke as one undo step, or the Color Picker's color, converted from display sRGB into the working RGB space. On Linux, a session without a portal that has PickColor, a portal that does not return from the call within 25 seconds (VectorCraft's own limit) or leaves the bus before it answers, and a portal that ends the request another way each show a status message and end the wait. On Windows, the copy is read as sRGB, so the colors of HDR and wide-gamut displays are not converted; Escape, a click of another mouse button or switching to another window cancels (VectorCraft's own rules). The BSDs and other browsers have no sampler yet; the button is gray there. - **Color Guide color groups:** with variation cells selected, the Color Guide's Save Color Group to Swatches button saves those cells as one swatch group, and with none selected it saves the harmony colors, as the [help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf) describes saving several selected variations together (printed page 135). The group takes the cells in grid order (row by row, left to right, each cell once), is named after the harmony rule and is one undo step; these are VectorCraft's own rules. A selection lasts until the base, the Color Guide Options, the variation mode, the harmony rule, the library limit or the colors the grid shows (for example after a new swatch while the guide is limited to the document's swatches) change. - **Color Guide colors dragged to Swatches:** a variation cell dragged from the Color Guide onto the Swatches panel's list becomes a swatch of that color, as the [help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf) describes for saving variations as individual swatches (printed page 135). In VectorCraft a harmony strip color drags the same way, a drag carries only the grabbed color (the selected cells stay selected and the selection is not saved), it carries the color the cell shows (snapped to the Limit to Library colors), keeps the color's model and does not paint the selected art; the swatch follows the panel's rules for a dropped color (`swatch.new`, one undo step, a color that is already a swatch is added again under another name, a drop on a color group joins it). These are VectorCraft's own rules. Tests: `a_dragged_guide_color_carries_its_color_and_applies_nothing` and `a_guide_color_dragged_onto_the_swatches_panel_becomes_a_swatch` in `crates/ui-egui/src/panels/color_guide.rs`. @@ -1830,6 +1891,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. @@ -1858,14 +1920,17 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The [About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html) page describes up to five Pattern brush tiles: sides, inner corner, outer corner, beginning and end. The archived [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page says to add pattern tiles to the Swatches panel and select a swatch from the scroll list for each tile. Pattern Brush Options offers document pattern swatches in all five tile menus, including swatches named like built-in choices. The brush copies each swatch's whole art and tile frame. Side requires art; explicit None on a corner prevents fallback to the other corner's art. After a swatch is deleted, the brush keeps drawing its copied art and shows it as Original. The cited pages do not describe copying the whole art, requiring Side, suppressing corner fallback after explicit None, or showing deleted swatch art as Original. `brush.options` accepts swatch names and an object form for names that match built-in choices, and rejects unknown patterns before editing. Evidence: `tests::brushsym::pattern_tile_choices_copy_whole_swatch_art_and_reject_invalid_side` and `tests::brushsym::pattern_tile_object_selects_reserved_swatch_names` (vectorcraft-engine), `tests::pattern_corner_source_none_leaves_that_kind_of_corner_empty` (vectorcraft-brush), and `dialogs::brush_options::tests::pattern_tile_menus_use_document_patterns_and_side_none_keeps_dialog_open`, `dialogs::brush_options::tests::pattern_options_borrowed_swatch_corner_keeps_its_frame`, and `dialogs::brush_options::tests::pattern_options_selects_swatches_with_reserved_names` (vectorcraft-ui-egui). - **Appearance:** the Appearance panel's selected row drives every paint, stroke, gradient and transparency edit (`item` on the commands); effects apply to one fill or stroke; per-item Opacity popups, whose blend-mode list and opacity slider stay open inside them (#430; the Control bar's Stroke popover too); Mixed Appearances, Layers target dots and basic-appearance rules. Effects can be reordered, moved between items and copied by dragging; Show All Hidden Attributes; clicking an effect edits it in place; the object thumbnail drags onto art; effects render on type, images, symbols, blends, envelopes, meshes and repeats, and per-item raster effects export. Groups, layers and type have their own fills, strokes and effects (Contents and Characters rows); the Layers panel's target circles target layers, groups and objects; Expand Appearance turns fills, strokes, effects and brushes into objects. Fill and stroke paint (Fill, Stroke, None, Apply Last Color and Apply Last Gradient, also on characters selected with the Type tool), the Stroke panel's options, gradient and freeform point edits, Swap Fill and Stroke, Default Fill and Stroke, the Eyedropper, and the Appearance panel's item edits, Clear Appearance, Reduce to Basic Appearance, Remove Item, item reordering and Move Appearance record no undo step when they change nothing. + A Stroke panel edit (`stroke.set` with no `item`) checks each object it collects against a set of the objects already listed, so collecting its targets takes time in step with the number of objects, and the list and its order are the same as before. With 20,000 paths in one group, collecting the targets takes 0.66 ms of thread CPU time on Linux, against 55 ms when each object is looked up in the list, and the whole command takes 60 ms (`crates/engine/examples/stroke_targets_bench.rs`; `cmd::stroke::tests::stroke_targets_match_the_listed_merge`). A Layers panel target circle dropped on the panel's Delete Selection button reduces that layer, group or object to basic appearance (`appearance.reduceToBasic`) in one undo step and deletes nothing, as the [Appearance attributes](https://helpx.adobe.com/illustrator/using/appearance-attributes.html) help page describes for that drag. Which fill and stroke stay (the topmost visible ones), that a layer or group keeps only the rows it had, and that the object's opacity and blend mode stay are VectorCraft's own rules (`panels::layers` test `dropping_a_target_circle_on_the_trash_reduces_it_to_basic_appearance`). The Add New Effect popup (Appearance panel, Properties), the Appearance panel's swatch picker, the Gradient panel's gradient swatches menu and the Image Trace button's list of presets stop at the bottom of a short window, and the mouse wheel or the scroll bar reaches their last rows. A list that fits does not scroll (`a_long_swatch_picker_scrolls_inside_a_short_window`). An image's own fills and strokes draw the shape that a Convert to Shape or Outline Object effect on them gives them (the image's box, or the outline of the image's opaque area or its frame, reshaped by the effects after it), under or over the image as its Contents row says, on the canvas, in exports and through Expand Appearance; new fills and strokes on an image go under it. Without one of those effects they draw nothing, and Use Preview Bounds then measures an image by its frame. 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 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). When an export bakes a symbol instance with geometry effects inside the art of another such instance, it counts the art the inner instance bakes to, the copies its symbol's effects make included, against the 262,144 objects of symbol art one export bakes that way; it counted only the symbol's art before its effects. An instance whose baked art would pass that count stays an instance with its effects, and the art baked for it still counts against the instances after it. These are VectorCraft's own limits (effects `bake::nested_reshape_counts_baked_art`, `nested_reshape_refusal_keeps_its_work_counted`, `nested_reshape_refused_siblings_bake_once`, `nested_reshape_counts_successful_descendants_once`). A raster effect (Drop Shadow, Outer Glow, Gaussian Blur and the other effects that paint pixels) on a symbol instance's topmost fill draws on each filled shape of the symbol's art, and one on its topmost stroke draws on each stroked shape, after any geometry effects listed before it, under the same rules as geometry effects: only a visible fill or stroke with an opacity above 0 counts, a group's own fills and strokes in the art take the effect, and an instance inside the art passes it on. Each shape gets its own shadow or glow, which is VectorCraft's own rule. The canvas, Use Preview Bounds and the drawn bounds, SVG and PDF export draw it, and Object › Expand Appearance is enabled for such an instance and makes the effect an image at the document's raster effects resolution, in one undo step (engine `expand::a_symbol_instance_fill_shadow_shadows_its_filled_art`, `a_symbol_instance_stroke_shadow_shadows_only_its_stroked_art`, `a_symbol_instance_fill_shadow_follows_the_fill_offset_before_it`, `a_nested_symbol_instance_takes_the_outer_fill_shadow`, `export_draws_a_symbol_instance_fill_shadow`). Existing documents with a raster effect on a symbol instance's fill or stroke draw differently: before, the effect drew nothing. Object › Expand Appearance turns a symbol instance whose topmost fill or stroke has only raster effects into its art as well, with the effect's image under the art (a shadow or glow) or in its place (a blur, feather or inner glow). A symbol instance inside the art whose topmost fill or stroke has a geometry or raster effect, its own or one the outer instance passes on, becomes its art and image the same way, and so do the instances in that art, within the nesting and symbol art limits; an instance of a missing symbol stays an instance. One Expand Appearance makes at most 1,024 images of raster effects, holding 256 megapixels in all (VectorCraft's own limits); an object or instance whose image would go past them stays as it is, with its raster effects, and the result reports how many with `rasterLeft` and a warning. Within those limits no live instance or raster effect is left from those effects, so the result no longer changes with the symbols; an instance left by the image limits still follows its symbol. The help page describes Expand Appearance turning appearance attributes into objects, and the help page describes expanding an effect into permanent raster data; expanding nested instances this way is VectorCraft's own rule (engine `expand::a_nested_instance_fill_shadow_becomes_an_image_when_the_outer_art_expands`, `an_outer_fill_shadow_expands_the_instance_and_reaches_the_nested_art`, `a_nested_instance_fill_blur_becomes_an_image_when_the_outer_art_expands`, `a_hidden_nested_instance_fill_shadow_makes_no_image`, `a_nested_instance_of_a_missing_symbol_stays_an_instance`, `nested_instance_raster_effects_stop_at_the_image_limit`). Before, an instance whose fill or stroke had only a shadow or glow stayed an instance over the image, and a raster effect on an instance in the art stayed live. @@ -1874,7 +1939,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Object › Expand Appearance keeps each stroke of a path a stroke (weight, caps, joins, dashes, arrowheads, alignment and width profile) on a copy of the path with the geometry effects baked in, and Object › Expand… is dimmed, with a tooltip, while the selection has appearance attributes, so a stroked line with Zig Zag becomes a stroked zig-zag line and only Expand then outlines it, the two steps the [Expand objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/expand-objects.html) help page describes (#3089). Brushed strokes still become their brush art; `object.expand` still bakes and outlines in one step for agents. - **Masks and clipping:** opacity-mask controls work while the mask is being edited; transparency commands take ids and work without a selection; clipping sets clip by compound paths, even-odd paths, text and groups on screen and in raster export, matching SVG/PDF. Alt-click shows only the mask; SVG masks keep Clip and Invert; the transparency grid is per-document state; a clipping path's own fill and stroke paint behind and over the clipped art; layers can be clipping masks. - **Masks and clipping:** opacity-mask controls work while the mask is being edited; transparency commands take ids and work without a selection; clipping sets clip by compound paths, even-odd paths, text and groups on screen and in raster export, matching SVG/PDF. Alt-click shows only the mask; SVG masks keep Clip and Invert; the transparency grid is per-document view state saved in native files (#1968); a clipping path's own fill and stroke paint behind and over the clipped art; layers can be clipping masks. - The geometry effects of a clipping path (Roughen, Transform and the other effects that reshape a path), of its fills and strokes, and of the members of a group used as one, shape the area it clips to on the canvas and in raster export, as in SVG and PDF export: a roughened clipping path clips by its roughened outline. They apply before the geometry effects of the clip group or of a group around it, on the canvas and in every export, also when the clipping path paints a fill or stroke of its own: that fill and stroke draw the shapes their effects give them. Type used as a clipping path keeps its geometry effects when a group's effect outlines it. Raster effects such as Gaussian Blur leave that area as it is. `effects::tests::clipfx` and the renderer's `tests::clip` cover it. + The geometry effects of a clipping path (Roughen, Transform and the other effects that reshape a path), of its fills and strokes, and of the members of a group used as one, shape the area it clips to on the canvas and in raster export, as in SVG and PDF export: a roughened clipping path clips by its roughened outline. They apply before the geometry effects of the clip group or of a group around it, on the canvas and in every export, also when the clipping path paints a fill or stroke of its own: that fill and stroke draw the shapes their effects give them. Type used as a clipping path keeps its geometry effects when a group's effect outlines it, and keeps the fill and stroke it was given after the mask was made ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/edit-clipping-masks.html)): its fill still paints behind the clipped art inside the clip and its stroke over it, reshaped with the clip, on the canvas and in SVG and PDF export (the `painted_clipping_type_exports_with_group_effect` tests in `vectorcraft-svg` and `vectorcraft-pdf`). Raster effects such as Gaussian Blur leave that area as it is. `effects::tests::clipfx` and the renderer's `tests::clip` cover it. Clicks, Select Behind, the Unlock submenu, marquees and the Enclosing Lasso inside a clip group or a clipping layer follow that area too: the clipped art is found where the effects moved it and not where they took it away. The clipping path itself is still found by its own outline and anchors. A hidden member of a group used as a clipping path does not clip, and a geometry effect on it does not change where clicks land. Outline view and layers with Preview off draw the plain clipping path, and clicks and marquees there count it. Direct Selection picks and outlines an object of a dynamic symbol's art by the same rules. `doc::hit::tests` and the engine's `tests::clip` cover it. - **Transparency:** three-state Knockout Group (on, neutral, off), Opacity & Mask Define Knockout Shape, Page Isolated Blending and Page Knockout Group, on screen and in SVG/PDF. SVG export writes a knockout group of opaque art plainly, without masks, so shapes meeting edge to edge leave no seam; translucent, blended, masked or brushed art knocks out through masks. Blend modes match the standard formulas on screen, in SVG and in PDF, and non-isolated groups blend with the art below. Flatten Transparency with presets, a dialog and a Flattener Preview panel. Flattening for files without transparency (PDF/X-1a, PDF/X-3) in a CMYK document keeps the inks where it rasterizes, as under an image with see-through pixels: the images it makes hold ink amounts, not screen colours the file would separate again, so a C100 M6 Y41 K3 panel stays C100 M6 Y41 K3 there (#2160, `engine/src/cmd/fileio/tests_pdfx.rs`). On the canvas, the renderer no longer draws the picture of the art below back as an image each time it copies the backdrop of a non-isolated group that blends: it keeps that picture and draws the art that follows over it. At 2880 × 1800, 50 translucent groups with Multiply members take 65 ms a frame instead of 299 ms on 8 threads (`vectorcraft-cli bench`), and the frames have the same pixels. @@ -1887,6 +1952,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur In the Graphic Styles panel, Shift-click selects a range of styles and Ctrl/Cmd-click adds or removes one. 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). @@ -1926,8 +1993,9 @@ 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`). A font family removed while the app runs leaves the font menus when the app scans the font folders again (when its window comes to the front after a font folder changed, or Refresh Font List), also when type had used it: that type then draws in the fallback font and Find Font lists the font as missing, until the font is installed again and the folders are scanned. - **Files (M4):** @@ -1958,8 +2026,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Save as Template writes a PDF-compatible `.ait` as well as a `.vctemplate`, which stays the default: the save panel and the web build's Save as Template dialog list both, and New from Template opens the `.ait` as an untitled document with its layers and art (`file.saveAsTemplate {format: "ait"}`, or a path ending in `.ait`). Save as Template always writes a file named with its template type's extension: `file.saveAsTemplate` saves a path ending in another format's extension (`card.png`) as `card.vctemplate` (or `card.ait`), the desktop save panel does the same with a Save As format's extension typed in it (`card.pdf` is saved as `card.vctemplate`), and `file.saveAs` and `document.save` refuse `ait` with an error that names `file.saveAsTemplate`. A `.ait` is PDF-compatible only: `aiVersion: "7"` is an error for it, and the web build's dialog shows no Version row for it. Exports refuse a `.ait` with an error that names `file.saveAsTemplate`, and `vectorcraft-cli convert in.pdf out.ait` and `run --export out.ait` write the template as `file.saveAsTemplate` does. - - SVG/SVGZ in and out with SVG Options, Preserve Editing, symbols, filters, rich text and physical units (SVG type under a transform or `viewBox` scale opens at the size it draws at, the scale moved into its size, leading, baseline shift and strokes, a stretch, skew or rotation kept as its transform: #396; a top-level group with a clip path, such as a clipped Inkscape layer, opens as a layer with a clipping mask, its name kept: #420; hidden objects written hidden on Save and `convert`, and `data-*` attributes kept as the objects' own data: #522; top-level groups open as layers named from `data-name`, else the id, also when one more group (a transform on all the art, a ``) wraps them, hidden ones hidden, and a file whose art sits loose under a root `` with an id (or `data-name`), as one-layer exports write it, opens with its one layer named from it; nested groups stay groups, except the sublayers VectorCraft writes, marked `data-vc-layer`, and Inkscape sublayers, which open as sublayers in their layer's colour: #372); PDF and PDF-compatible `.ai` in and out (layers, with hidden ones kept hidden with their art and nested ones as sublayers, on pages of up to 64 million operators, art whose layer can't be told going to a hidden, non-printing layer rather than showing or printing: #419; strokes kept live, a fill and a stroke of one outline as one object; a type object's stroke written as each glyph's outline stroked back on the type, so it stays one editable object; lines wrapped in a frame (each wrapped line ending in a space, one left edge, leading and font) back as one area type object, left aligned or justified with its paragraph spacing, where laying it out breaks the lines where the file does; glyphs set apart by gaps wider than a space (a barcode's digit groups) keeping their places; layers stacked as the pages mark them even when one first paints on a later page, art ending a layer's marked content or a clip closing in a later layer kept in its own layer, and layers with no art kept empty: #508; art reaching past a plain PDF's page clipped to its crop box, as PDF viewers show it, each such object in a clip group of its own (a PDF-compatible `.ai` opens whole: #675); a `.ai` on its trim boxes with the bleed boxes round them as the document's bleed, as Crop To › Trim opens a PDF (#1266); masks, editable text with type set along a curve coming back as type on a path, each artboard's art on its own page only, an `.ai`'s white page under its layers left out rather than coming in as art, spot colours, presets, security, marks and bleed, ICC output intents, raster effects, subset fonts, PDF/X, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3). CMYK images keep their ink amounts from PDF import (and from placed CMYK TIFFs) to PDF export: a CMYK JPEG passes through unchanged, others stay CMYK (DeviceCMYK, or ICC-based CMYK in PDF/X-3/X-4) unless the Output settings convert them; the canvas shows them through the working CMYK profile (#320). Overprint is kept from PDF import (opened, the PDF part of an `.ai`, placed) to PDF export: the graphics state's `/OP` and `/op` become the overprint of fills, strokes and type, so a spot colour over a process colour still overprints; a page whose overprint can't be read for certain knocks out with a note, as does `/OPM 0` being read as nonzero overprint (#1388; hand-written fixtures, `pdf/src/tests/import_overprint.rs`). A masked CMYK image (`/SMask`, `/Mask` or a colour key) keeps its inks too, its alpha coming in as a greyscale opacity mask. - - SVG/SVGZ in and out with SVG Options, Preserve Editing, symbols, filters, rich text and physical units (SVG type under a transform or `viewBox` scale opens at the size it draws at, the scale moved into its size, leading, baseline shift and strokes, a stretch, skew or rotation kept as its transform: #396; a top-level group with a clip path, such as a clipped Inkscape layer, opens as a layer with a clipping mask, its name kept: #420; hidden objects written hidden on Save and `convert`, and `data-*` attributes kept as the objects' own data: #522; top-level groups open as layers named from `data-name`, else the id, also when one more group (a transform on all the art, a ``) wraps them, hidden ones hidden, and a file whose art sits loose under a root `` with an id (or `data-name`), as one-layer exports write it, opens with its one layer named from it; nested groups stay groups, except the sublayers VectorCraft writes, marked `data-vc-layer`, and Inkscape sublayers, which open as sublayers in their layer's colour: #372); PDF and PDF-compatible `.ai` in and out (layers, with hidden ones kept hidden with their art and nested ones as sublayers, on pages of up to 64 million operators, art whose layer can't be told going to a hidden, non-printing layer rather than showing or printing: #419; strokes kept live, a fill and a stroke of one outline as one object; a type object's stroke written as each glyph's outline stroked back on the type, so it stays one editable object; lines wrapped in a frame (each wrapped line ending in a space, one left edge, leading and font) back as one area type object, left aligned or justified with its paragraph spacing, where laying it out breaks the lines where the file does; glyphs set apart by gaps wider than a space (a barcode's digit groups) keeping their places; layers stacked as the pages mark them even when one first paints on a later page, art ending a layer's marked content or a clip closing in a later layer kept in its own layer, and layers with no art kept empty: #508; art reaching past a plain PDF's page clipped to its crop box, as PDF viewers show it, each such object in a clip group of its own (a PDF-compatible `.ai` opens whole: #675); a `.ai` on its trim boxes with the bleed boxes round them as the document's bleed, as Crop To › Trim opens a PDF (#1266); masks, editable text with type set along a curve coming back as type on a path, each artboard's art on its own page only, an `.ai`'s white page under its layers left out rather than coming in as art, spot colours, presets, security, marks and bleed, ICC output intents, raster effects, subset fonts, PDF/X, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3). CMYK images keep their ink amounts from PDF import (and from placed CMYK TIFFs and the images in an `.ai` or EPS file's editing data, an alpha channel coming in as a grayscale opacity mask) to PDF export: a CMYK JPEG passes through unchanged, others stay CMYK (DeviceCMYK, or ICC-based CMYK in PDF/X-3/X-4) unless the Output settings convert them; the canvas shows them through the working CMYK profile (#320). Overprint is kept from PDF import (opened, the PDF part of an `.ai`, placed) to PDF export: the graphics state's `/OP` and `/op` become the overprint of fills, strokes and type, so a spot colour over a process colour still overprints; a page whose overprint can't be read for certain knocks out with a note, as does `/OPM 0` being read as nonzero overprint (#1388; hand-written fixtures, `pdf/src/tests/import_overprint.rs`). A masked CMYK image (`/SMask`, `/Mask` or a colour key) keeps its inks too, its alpha coming in as a greyscale opacity mask. + - SVG/SVGZ in and out with SVG Options, Preserve Editing, symbols, filters, rich text and physical units (SVG type under a transform or `viewBox` scale opens at the size it draws at, the scale moved into its size, leading, baseline shift and strokes, a stretch, skew or rotation kept as its transform: #396; a top-level group with a clip path, such as a clipped Inkscape layer, opens as a layer with a clipping mask, its name kept: #420; hidden objects written hidden on Save and `convert`, and `data-*` attributes kept as the objects' own data: #522; top-level groups open as layers named from `data-name`, else the id, also when one more group (a transform on all the art, a ``) wraps them, hidden ones hidden, and a file whose art sits loose under a root `` with an id (or `data-name`), as one-layer exports write it, opens with its one layer named from it; nested groups stay groups, except the sublayers VectorCraft writes, marked `data-vc-layer`, and Inkscape sublayers, which open as sublayers in their layer's colour: #372); PDF and PDF-compatible `.ai` in and out (layers, with hidden ones kept hidden with their art and nested ones as sublayers, on pages of up to 64 million operators, art whose layer can't be told going to a hidden, non-printing layer rather than showing or printing: #419; strokes kept live, a fill and a stroke of one outline as one object; a type object's stroke written as each glyph's outline stroked back on the type, so it stays one editable object; lines wrapped in a frame (each wrapped line ending in a space, one left edge, leading and font) back as one area type object, left aligned or justified with its paragraph spacing, where laying it out breaks the lines where the file does; glyphs set apart by gaps wider than a space (a barcode's digit groups) keeping their places; layers stacked as the pages mark them even when one first paints on a later page, art ending a layer's marked content or a clip closing in a later layer kept in its own layer, and layers with no art kept empty: #508; art reaching past a plain PDF's page clipped to its crop box, as PDF viewers show it, each such object in a clip group of its own (a PDF-compatible `.ai` opens whole: #675); a `.ai` on its trim boxes with the bleed boxes round them as the document's bleed, as Crop To › Trim opens a PDF (#1266); masks, editable text with type set along a curve coming back as type on a path, each artboard's art on its own page only, an `.ai`'s white page under its layers left out rather than coming in as art, spot colours, presets, security, marks and bleed, ICC output intents, raster effects, subset fonts, PDF/X, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3). CMYK images keep their ink amounts from PDF import (and from placed CMYK TIFFs and the images in an `.ai` or EPS file's editing data, an alpha channel coming in as a grayscale opacity mask) to PDF export: a CMYK JPEG passes through with its compressed samples unchanged (its `ICC_PROFILE` segments are removed when `output.profiles` is `none` (except in PDF/A, and in PDF/X-3 and PDF/X-4 files that do not write CMYK colors as DeviceCMYK) and in PDF/X-3 and PDF/X-4 when they are the CMYK output intent's profile and CMYK colors are DeviceCMYK), others stay CMYK (DeviceCMYK, or ICC-based CMYK in PDF/X-3/X-4 when not in the output intent's profile) unless the Output settings convert them; the canvas shows them through the working CMYK profile (#320). Overprint is kept from PDF import (opened, the PDF part of an `.ai`, placed) to PDF export: the graphics state's `/OP` and `/op` become the overprint of fills, strokes and type, so a spot colour over a process colour still overprints; a page whose overprint can't be read for certain knocks out with a note, as does `/OPM 0` being read as nonzero overprint (#1388; hand-written fixtures, `pdf/src/tests/import_overprint.rs`). A masked CMYK image (`/SMask`, `/Mask` or a colour key) keeps its inks too, its alpha coming in as a greyscale opacity mask. In imported PDF type, a space glyph the file draws between two words also keeps the next word where the file has it when the gap beside the space is wide, as VectorCraft's own export draws a tracked space: the space gets tracking of its own, and the wrapped lines of a justified paragraph still come back as one area type object when the word gaps on each line are alike (part of #2384). Letter-spaced PDF type, whether set with character spacing (`Tc`) or glyph by glyph, keeps its word spaces and gains none between its letters: the spacing a line's letters share is taken off each gap before a gap reads as a space. That holds on a line that also shows where its words break, with spaces the file draws or gaps wider than the rest; evenly spaced glyphs alone, which could be words of one letter, keep every gap as a space, as do glyphs set more than half an em apart, such as figures in columns. A function-based PDF shading (type 1) whose colour changes along one axis only, as a browser writes a repeating linear gradient, comes in as a linear gradient over its domain, each hard colour change two stops at one offset; one whose colour changes in two directions comes in as its average colour, with a warning. Either paints only over the shading's domain. Both came in as a flat grey that wasn't in the file (#3621). Each such shading is read once per import, and all of them within one budget of 200,000 function evaluations, so a file filling thousands of paths with long functions still opens in about a second (it took minutes); past the budget they come in as their average colour, then grey, with a warning. @@ -2005,6 +2072,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur `.ai` and EPS editing-data import reads a text document whose keys are written by name, as files saved for version 11 write them, and the keys that later files write by name among the numbered ones (a font record's version, a paragraph's direction). The type of such a file comes from its text document, so type outside the artboards opens and each text object keeps its own story A run that names its paragraph or character style by the style's number takes that style (`a_text_document_with_named_keys_gives_type_off_the_page_too`, `a_text_document_with_named_keys_takes_a_runs_style_by_its_number`, `crates/eps/src/import/ate/names.rs`). In SVG export without Fewer `` Elements, each character of live type that justification or Mojikumi moves (the letter gaps of a Justify All line without word spaces, the gaps between the characters of a justified Japanese line, closed-up punctuation, the space between Japanese and Latin letters) starts its own positioned ``, and type scaled horizontally on a justified line is stretched to its own width (`crates/svg/tests/it/text_layout.rs`). To find those characters, SVG export lays a type object out a second time only when the second layout can differ from the first: point type with Line-end Punctuation Half Width and no Japanese punctuation or letters, the setting new type gets, is laid out once. Exporting 5,000 such objects takes a median of 109.4 ms instead of 171.5 ms on Windows 11, with the same SVG (`crates/svg/src/export/text/tests.rs`). + SVG export lays each type object out once for all of its writers and draws that one layout in each of them (live text, type on a path, outlines, and inside or outside character strokes). Two checks still lay out a changed copy of the type: the check for glyphs hanging outside the brackets of type on a path with Optical Margin Alignment or Roman Hanging Punctuation on, and the advances a reader gives live text when they differ from the drawn layout. The export also groups the glyphs of type written as outlines or with such strokes by run in one pass, with the same SVG. Exporting 1,000 objects of type on a path, 1,000 of bidirectional type and 300 with an outside character stroke lays type out 2,300 times instead of 4,900 and takes a median of 665 ms of CPU time instead of 893 ms over seven runs each, alternating, on Linux; grouping the glyphs of 300 texts of 1,000 runs by run takes 10 ms instead of 190 ms (`crates/svg/src/export/text/tests.rs`). SVG export (live text), legacy `.ai` saves (text objects), DXF export (`TEXT` entities) and the CSS Properties panel write area type that Shrink Text to Fit scales down at the size it draws at, and scale its tracking, kerning, leading and baseline shifts the same way where the format holds them. Legacy `.ai` saves (version 7) write type with rotated characters (Character Rotation, Touch Type turns) as its outlines, with a warning that it is no longer editable text (unless `outlineText` already asks for every type object as outlines): a version 7 text object has no character rotation ([Adobe Illustrator File Format Specification 7.0](https://www.nationalarchives.gov.uk/PRONOM/fmt/423), §15), and the outlines keep each character's rotation, baseline shift and scale (`legacy_ai::tests::type_with_rotated_characters_is_outlines_that_keep_the_rotation`). Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), its discretionary hyphens (`T+`, `T-`) as soft hyphens and its hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` ([file format specification, version 7](https://web.archive.org/web/20050126105313/https://partners.adobe.com/public/developer/en/illustrator/sdk/AI7FileFormat.pdf), §15.4.6.1, §15.4.10.1 and §22.6). A file whose type sets a line breaking value (`TG`) or Japanese layout rules (`Xu`, `Tu`), which VectorCraft doesn't keep, opens with a warning for each (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_line_breaking_and_japanese_layout_rules_are_warned_once`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`). @@ -2020,6 +2088,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur In a `.ai` opened from its editing data, an object in a pattern's art or a brush's art with an art style VectorCraft reads opens as itself with its effects live, as an object on a layer does, and an object in a pattern's art keeps the id of a graphic style in the file's list (`crates/eps/src/import/ai/tests.rs`). A graph in a `.ai` whose records have the shape and values the published version 7 specification gives ([the specification](https://13thmonkey.org/documentation/fonts/AI7FileFormat.pdf), printed pp. 109–112 and 146–158) opens as a live grouped column, stacked column, line or area graph with its saved art, table, axes and settings, and Graph Data edits it ([the help page](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/visualize-data/add-graph-data.html)); other graphs keep their art as plain objects with a note. Saving to `.ai` writes these records for a graph that reads back as the same graph, and warns that any other graph's data and settings aren't written (`crates/eps/src/import/ai/tests.rs`, `crates/engine/src/cmd/graph/tests.rs`). A line graph drawn with Draw Filled Lines, which draws thicker filled lines when the points are connected ([the help page](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/visualize-data/format-columns-bars-and-lines.html)), opens and saves live with its Line Width through the style record's `drawLinesAsShapes` and `lineShapeWidth` (the specification, printed pp. 147–148: points from 0 to 100, ignored when the lines aren't drawn); widths from 0.01 to 100 pt are kept, and a graph with a wider Line Width is saved as its art with the warning. Blends and envelopes in the definitions of a `.ai`'s symbols, patterns and brushes' art count against the same per-file limits on blend layout and envelope checks as the layers' art, so a file with many definitions does not get those limits again for each one (`crates/eps/src/import/ai/read/directives.rs`). + In a `.ai` or EPS opened from its editing data, a Scatter brush's art comes in turned over from its section, as an Art brush's does: each copy draws the side of the section with y up down the page before the copy's rotation. The `.ai` writer writes Scatter art back the same way (`crates/eps/src/import/ai/tests.rs`, `crates/eps/src/ai_editing/tests.rs`). A `.ai` or EPS whose editing data has brushes opens with the file's Calligraphic, Scatter, Art and Bristle brushes in the Brushes panel in place of the default ones, in the file's order: the Calligraphic size, roundness and angle with their variation, the Scatter size, spacing, scatter and rotation, the Bristle settings, and the Scatter and Art brushes' art (Art brushes in the older and newer forms of their objects). A brush library `.ai` (brushes and no layers) opens from its PDF part with its brushes, so Other Library lists them. An Art brush in None or Tints keeps that colorization, and one in the newer form also keeps its fixed width, Flip Along and Flip Across, and Scale Proportionately, Stretch to Fit Stroke Length or Stretch Between Guides with its guides ([Art brush options](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf), printed page 193). Pattern brushes and brushes that can't be read are left out with a note. Paths with a Calligraphic brush, and paths with an Art brush in the newer form that bends art of solid-filled paths with those options, open as the path with the brush on its stroke, except paths whose brush scales its art proportionately. Paths with an Art brush in the older form, and other brushed paths, still come in as their drawn look (part of #372 and #637; `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). In a `.ai` opened from its editing data, a path or type object with Offset Path, Outline Object or Outline Stroke on the whole object opens as itself with those effects live, in their order and shown or hidden; on a fill or stroke of type they stay on that fill or stroke. Offset Path keeps its Offset, Joins and Miter Limit, and Outline Stroke takes its width from the stroke. An Offset Path with a setting missing, out of range or not read keeps the drawn art, as does a path with a Path effect on one fill or stroke (`crates/eps/src/import/ai/style/tests.rs`, `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). In a `.ai` or EPS opened from its editing data, a Scatter brush whose last 15 numbers start with 1 comes into the Brushes panel in Tints, and each brush art section is read without its frame, an unnamed, unpainted rectangle with no settings of its own at the art's bounds (within 1/1000 pt). A wider frame stays in the art, and an art group with a state or look of its own (hidden, locked, isolated, knockout, an opacity, a blend mode, a name, a mask, a note or an appearance) stays a group (`crates/eps/src/import/ai/tests.rs`). @@ -2039,6 +2108,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur In a `.ai` opened from its editing data, Convert to Shape on a whole path or type object opens as a live Rectangle, Rounded Rectangle or Ellipse effect with its Absolute or Relative size, its corner radius, its place among the object's effects and whether it is hidden. A relative size in the file is added to each side. A relative Ellipse, or a setting VectorCraft doesn't read, keeps the drawn art (`crates/eps/src/import/ai/style/tests.rs`, `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). In a `.ai` opened from its editing data, Bas Relief in an art style takes its Detail, Smoothness and Light direction from the style's settings block, and an object other than type with it opens as itself with the live effect. A settings block that VectorCraft can't read (malformed, another effect's, a value out of range or a key it doesn't know) keeps the object's drawn look (part of #637; [raster effects reference](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/raster-effects-reference.html), [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), [scripting the filter gallery](https://community.adobe.com/questions-712/scripting-support-for-the-filter-gallery-1064646); `crates/eps/src/import/ai/style/tests.rs`, `crates/eps/src/import/ai/tests.rs`). PDF export and `.ai` saves write a page with a side longer than 14,400 pt with a `UserUnit` (PDF 1.6), its longer side divided by 14,400 and rounded up to the next thousandth, so that no side is longer than 14,400 units (ISO 32000-1, Annex C.2); a PDF 1.5 file with such a page is written as PDF 1.6 with PDF 1.5's encryption, PDF/X files and PDF 1.3 and 1.4 files write it in points (in PDF 1.3 and 1.4, a page past 32,767 pt that needs a real number past 32,767 is refused with an error naming it), a page whose short side is 3 pt or longer but would be under 3 units at that `UserUnit` gets a smaller one that keeps the short side at 3 units, and the export's warnings give each such page's size and how it is written (#6382). The Save PDF dialog's "Write pages longer than 200 in at full size in points" (`longPagesInPoints`, on by default; `.ai` saves leave it off) writes such pages in points without a `UserUnit` at every PDF version, in files without a PDF/X or PDF/A standard, so readers that ignore `UserUnit` show them at full size. + Raster export dialogs retain supplied values for their controls, including PNG resolution, background, anti-aliasing and interlacing, and JPEG quality. Omitted values use the dialog defaults; a nonpositive resolution is rejected on confirmation (#8324; `crates/ui-egui/src/dialogs/tests_raster_supplied_options.rs`). Export As PDF with Use Artboards off also opens the Save PDF dialog, without its Artboards section, and writes one page of the visible art's bounds with the dialog's options (`document.exportPdf {useArtboards: false}`; `crates/ui-egui/src/dialogs/tests_export.rs`, `crates/engine/src/cmd/fileio/tests_pdf.rs`). While Alt (Option on macOS) is held, the Save PDF dialog's Cancel button reads Reset, which puts every option back to the chosen preset's settings, passwords included, and leaves the dialog open; letting the key go shows Cancel again (`ui.dialogReset`). [The help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=283) says that holding Alt or Option and clicking Reset returns the options to their defaults. Resetting to the chosen preset's settings, and keeping the preset, path, artboard range and section, are VectorCraft's own rules (`crates/ui-egui/src/dialogs/save_pdf/tests.rs`, `crates/ui-egui/src/dialogs/tests.rs`). `document.exportSelection` run without params (a shortcut) takes the same route after its save panel: a picked PDF opens the Save PDF dialog without its Artboards section, and SVG, the raster formats, EPS, DXF, text and exporter plug-ins with parameters open their options, whose OK writes the selection alone, cropped to it, with the chosen options (`crates/ui-egui/src/dialogs/tests_export_selection.rs`). @@ -2102,19 +2172,22 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - DXF control-point SPLINE import honors its closed flag (#1299 follow-up after #1320 fixed export), including rational curves; open curves whose endpoints meet stay open. Own-fixture regressions cover controls/knots, fit-point fallback and all export versions (`crates/cad/src/import/tests.rs`, `crates/cad/src/tests.rs`); native save/read checked. Circular cubic paths export as native CIRCLE/ARC where stroke semantics permit; R12 weighted strokes remain POLYLINE; a closed four-cubic ellipse, or a circle scaled out of proportion, exports as a native ELLIPSE in R13 and later (an ellipse whose minor-to-major ratio is below 1e-6 is still written as a polyline or spline), and R12 keeps the existing fallback (`crates/cad/src/tests.rs`); an open path of one straight segment exports as a LINE (R12 to R14 strokes with a weight stay polylines, which carry the width) and reads back as the same segment (`crates/cad/src/tests.rs`, `crates/cad/src/import/tests.rs`); DXF Options' Preset menu and `document.exportDxf`'s `dxfPreset: "cnc"` set the CNC / CAM options (version 2000, 1 mm = 1 unit, 256 colors, Maximize Editability with Alter Paths off, Outline Text, placed images and fill hatches left out), and the menu shows Custom once a field changes (`the_cnc_preset_writes_version_2000_in_millimeters_with_type_as_paths_and_strokes_as_lines`, `the_cnc_preset_sets_the_options_that_are_not_given`, `the_cnc_cam_preset_sets_the_fields_and_a_change_shows_custom`); VCarve QA remains pending. - DXF export's Include Placed Images and Include Fill Hatches (`includeImages`, `includeHatches`; VectorCraft's own options, on by default and off in CNC / CAM) leave out placed images with their linked files, without decoding them, and the solid hatch after each filled area's outlines, each on its own, with one note in `warnings` when something was left out; R12 keeps its own notes. An open path's fill outline is closed, as the fill is, in every version (`an_open_path_s_fill_outline_keeps_its_closing_edge`, `fills_without_hatches_keep_their_outlines`, `images_can_be_left_out_with_their_files`, `images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_both`, `placed_images_and_fill_hatches_can_be_left_out`, `include_placed_images_and_fill_hatches_follow_the_preset_and_a_change_shows_custom`). - DXF export writes a path of straight segments and circular arcs (a slot, a D shape, a rounded rectangle, a pie) as one polyline whose vertices carry a bulge (group 42) for each arc: an LWPOLYLINE in R14 and later, a POLYLINE with VERTEX entities in R12 and R13, closed when the path is closed, and it reads back as the same outline (#1299, `crates/cad/src/tests.rs`). Such a path was written as one SPLINE (a flattened polyline in R12); a path with any other curve still is. A shallow curve becomes an ARC or a bulge only when it lies on the circle within 5e-4 of its own extent as well as of the radius, and the drawing extents (`$EXTMIN`, `$EXTMAX`) reach the furthest points of every ARC and bulge. + - DXF export with Use Artboards applies live effects and places symbols' art once for all the artboards' drawings instead of once for each drawing; each drawing's bytes, linked images, warnings and notes are the same as before (`drawings_apply_the_live_effects_once_and_match_drawings_written_alone`, `each_artboard_s_drawing_is_the_drawing_of_that_artboard_alone`). - Affinity documents in (AF.1–AF.4): `.af` (Affinity 3) and `.afdesign`/`.afphoto`/`.afpub` (Affinity 1 and 2, container versions 8–12) open and place as editable art: layers and sublayers, groups (pass-through or isolated), artboards (with their names and backgrounds) and Publisher pages side by side, curves with live corners, parametric shapes (rectangles with corner radii, ellipses, polygons, stars, pies, triangles, trapezoids), compound shapes, solid/linear/elliptical gradient fills and strokes (weight, dashes, alignment, scale-with-object), clipping by nesting, vector and pixel masks, artistic and frame text with fonts, sizes, tracking, leading and alignment, placed images (their original JPEG/PNG) and pixel layers (8/16-bit RGB, CMYK), opacity, visibility, locking and blend modes, at the document's resolution in points. Effects, adjustments, brushes and pressure profiles, transparency gradients, master pages, symbol instances (imported as their cached picture), special shapes (cloud, heart, cog…, imported as ellipses) and Affinity-only blend modes are named in the import warning. A file whose native data can't be read opens as its embedded preview with the reason, and that preview can't be placed. Save never writes back over the Affinity file and there is no Affinity export. AF.5 (from DesignCraft's import, storytold/designcraft#291) adds master pages (on a locked layer behind the pages that show them), tables (area type per cell and a line per edge), each paragraph's alignment, indents, spacing and leading, horizontal text scale, outlined text, frame text sized by its text scale, drop shadows and outer glows as live effects (inner shadows as inner glows), outline effects as strokes, colour and gradient overlays baked into the paint, embedded Affinity documents as editable content (their artboards don't become artboards), pixel layers over 64 MP at a reduced resolution and HEIC photos from their stored pixels; automatic leading (size plus the font's line gap) fitted on thumbnails; underlines and strikethrough; strokes whose style is None (every shape stores one) left out, which also brings 6 public files closer to their thumbnails; line breaks inside a paragraph; table cell text centred as Affinity centres it, also where it is taller than its cell; CMYK pixel layers converted through the document's embedded CMYK profile (relative colorimetric with black-point compensation, as each layer's colour settings name), or kept as CMYK images when there is none; outline effects on stroked shapes around their stroke; artistic text whose paragraphs align differently aligned within its longest line, a frame's first baseline at cap height, and frames whose last lines' descenders hang out made tall enough to show them (all measured on a local document's own PDF export: baselines match to 0.1 pt); a local 56-artboard document's mean thumbnail difference went from 16.2 to 11.4, and its pages' mean difference from the owner's PDF export from 12.9 to 9.3. AF.4 adds Affinity 3 artboard recognition and actual-outline clipping, source-backed JPEG/PNG raster tiles, Unicode text-run recovery, stored fallback/exact installed fonts, OpenType feature flags and compound-geometry limits. 51 public CC0/MIT/Apache-2.0 files (33 current `.af`), pinned and sha256-verified (`cargo xtask corpus --affinity`), test native retention and every-board native/SVG/PDF/PSD output for current files; selected files compare their saved thumbnails. No Affinity reopen or independent paired PSD oracle was available; [source audit and complex-font gaps](affinity-validation.md); [scope, provenance and limits](../crates/affinity/README.md). - Placed documents: File › Place of a `.vectorcraft` file links to it by default (`file.place`'s `link`): one locked object showing an artboard of the document (or its art's bounds), read the way placing it without Link reads it, its symbols, patterns and images kept apart from the document's; without Link (or from bytes, not a file) it is an editable copy as before. It stays vectors in every output (SVG, PDF, EPS, EMF, DXF), and so do placed documents inside it, read from their own files up to 8 levels deep (documents that place each other stop there). On screen they draw from bitmaps cached per file and zoom step, shared by every copy and made in the background (a placeholder until ready), so a sheet of them redraws in about a millisecond; exports and prints draw them exactly. Like linked images, a save keeps only a preview of each (JPEG when opaque) unless Include Linked Files; output, and zooming past the preview, read the file again, falling back to the preview with a warning when it is gone or changed. Saves for older versions write them as plain art. Links check, update, relink, Update Links on open, Link Info (the artboard's size), Placement Options, Break Link (also Embed, Object › Expand: the editable copy placing without Link gives, its resources joining the document), Edit Original (the document in a new tab) and the Links panel cover them; saving a document updates the open documents that place it. The native format (v4) keeps data of 8 KB or more after the JSON instead of base64 in it. - Placed documents' bitmaps on screen: when a bitmap made in the background is ready, the desktop app renders the canvas again only where the objects that show its file are, when the frame shown was rendered on the UI thread and that part is at most half the canvas. Bitmaps drawn or made since a frame began are kept for that frame past the 512 MiB budget, up to 2 GiB, so a view showing more than the budget does not make them again in every frame. A bitmap that would take them past 2 GiB is not kept, and its file draws exactly at that zoom. A bitmap that can't be made (the file can't be read and there is no preview) shows the light placeholder and is not asked for again. Each ready bitmap used to render the whole canvas again, and bitmaps past the budget and bitmaps that could not be made were asked for again in every frame (`crates/render/src/tests/placed_document.rs`). - Linked PDF and `.ai` pages: File › Place with Link (the default) places a page of a PDF, `.ai` or `.ait` file read as PDF pages as a placed document, as it links an image, the page and its box (`crop`) kept with the link: Links check, update and relink it, Break Link and Object › Expand give the group placing it without Link gives, every output draws the page's vectors, and Package copies the file. Without Link, or with a password or `textAs: "outlines"`, the page is embedded. An EPS file, a PostScript file or a PostScript `.ai` placed from a file with Link is a placed document the same way, showing the art placing it without Link gives (clipped to its bounding box, or its art's bounds with `crop: "bounding"`); Links lists it as `EPS` or `PostScript`, and a save, Package, Break Link and Object › Expand treat it as they treat a placed PDF page. Package also copies the files that the native document of an EPS file written by VectorCraft links, beside the EPS file's copy, which finds them there by name. Placing one keeps the file linked rather than embedding it, as [the help page](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-other-file-types/eps-and-dcs-file-import-in-illustrator.html) describes; a DCS file stays a linked image (`crates/engine/src/tests/placed_document.rs`, `crates/engine/src/tests/package.rs`). + - File › Open's Import PDF dialog checks Import PDF pages as links when All is picked and clears it when Range is picked: every page of a PDF opened from its file opens linked unless the box is cleared, and a range of pages opens as art unless the box is checked ([the help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=444)). A box checked or cleared by hand keeps that state until the other of All and Range is picked; picking the one already picked, or editing the range, does not change it, and `ui.dialog.set` of `allPages` changes it as the buttons do (VectorCraft's own rules). A file opened without its path, with a password or over the 256 MB that linked pages take still opens its pages as art. The box used to start cleared for All as well (`crates/ui-egui/src/dialogs/tests_import_pdf.rs`). - The place cursor keeps an encrypted PDF, `.ai` or `.ait` file, at a letter page's size (VectorCraft's own size) and without a thumbnail, and a click or drag on it asks for its password, with the Place dialog's Show Import Options on or off; such a file was left out of the cursor before (`crates/engine/src/tests/place.rs`, `crates/ui-egui/src/tests/place.rs`). - File › Place with Bounding Box (`file.place {crop: "bounding"}`) measures the art that shows, with its strokes and effects, as an export does: hidden objects, guides and template layers do not count, a group whose only part on the page or artboard is hidden is not placed, and symbol instances are measured by their art, for `at`, `rect`, the place cursor and `file.place.info` (`crates/engine/src/tests/place.rs`). - The Place dialog has a Show Import Options checkbox after Link, Template and Replace ([Place multiple files in a document](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-other-file-types/place-multiple-files-in-a-document.html)). On (VectorCraft's default, saved with the preferences), each PDF, DXF or text file asks for its import options before it is placed, also in the place cursor; off (`file.place {showImportOptions: false}`), it is placed with the options last confirmed for its format, and only an encrypted PDF asks, for its password. Text Import Options now starts from the options confirmed last (`crates/ui-egui/src/tests/place.rs`). - Text Import Options' Character Set offers Shift JIS, GB2312, Chinese Big 5, Cyrillic, GB18030, Greek, Turkish, Baltic and Central European beside Unicode and ANSI, the plain-text encodings [the help page](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-other-file-types/import-and-export-text.html) lists for placed text. `file.place {text: {characterSet}}` decodes each with its WHATWG Encoding Standard decoder. The mapping is VectorCraft's own: GB2312 reads as GBK, Cyrillic as windows-1251 (x-mac-cyrillic with `platform: "mac"`), and Greek, Turkish, Baltic and Central European as windows-1253, 1254, 1257 and 1250 on both platforms. A byte-order mark is read as ordinary bytes, a malformed sequence as U+FFFD, and the last set confirmed is remembered (`crates/engine/src/tests/textimport.rs`, `crates/ui-egui/src/dialogs/text_import.rs`). - A Shift-click with the loaded place cursor opens the current file's import options (text, DXF, PDF page or embedded PSD) and OK places it at the click, with Show Import Options on or off and for a cursor loaded by `file.place.queue` ([Place multiple files](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf)). VectorCraft's own rules: a file without such a dialog places as a click does, Cancel leaves the file unplaced, a Shift-drag places at the dragged size, and headless the Shift-click places as a click (`crates/tools/src/place.rs`, `crates/engine/src/tests/place.rs`, `crates/ui-egui/src/tests/place.rs`). - Separations Preview shows placed and embedded raster images on the visible plates, as it shows vector art (#4153): an RGB image's pixels are separated into process inks with the proof setup's intent, a CMYK image shows its own inks, a hidden plate's ink leaves the image, and with one plate visible the image shows that plate's ink as a grey. Raster images carry no spot ink, so a spot plate shown alone shows them as paper; a colorized image shows its color's plates. Emoji and other bitmap glyphs follow the same rule. The plate-filtered pixels and their reduced-size copies are kept apart from the image's own pixels, for each set of visible plates, proof setup and color settings, and with the preview off nothing changes. Evidence: `tests::colorize::separations_preview_shows_an_rgb_images_process_inks`, `separations_preview_shows_a_cmyk_images_own_inks`, `separations_preview_keeps_an_images_pixels_per_plate_set`. Print preview fidelity remains the open gap, so scores and hours are unchanged. + - In the Separations Preview panel, an Alt-click (Option-click on macOS) on the eye of the plate shown alone shows every plate again, spot plates included, as [the help page](https://helpx.adobe.com/illustrator/using/printing-color-separations.html) describes for a second modified click on the eye (`view.separationsPreview {soloToggle: plate}`); an Alt-click on a plate shown among others shows only that plate, as the help page describes for the first one. VectorCraft's own rules: an Alt-click on a hidden plate, on another plate while one shows alone or while no plate is shown shows only that plate, and `only` still shows just the named plate when repeated (`crates/engine/src/tests/colormgmt.rs`, `crates/ui-egui/src/panels/separations.rs`). - Desktop print transport uses `craft-print` for CUPS and modern Windows. Sheet composition, copies, separations and colour management remain in VectorCraft. The Print dialog's Media list also carries the Japanese papers — JIS B4 257 × 364 mm, JIS B5 182 × 257 mm and JIS B6 128 × 182 mm beside the ISO B4/B5 (250 × 353 and 176 × 250 mm, kept so settings and presets saved before them keep their paper), and はがき 100 × 148 mm, 往復はがき 148 × 200 mm, 封筒 長形3号 120 × 235 mm, 長形4号 90 × 225 mm, 角形2号 240 × 332 mm, 角形3号 216 × 277 mm and 四六判 127 × 188 mm; the JSON id or the dialog label names a paper, any case and spacing (`B5 (JIS)` or `b5jis`) (`crates/pdf/src/print/settings.rs`, `crates/pdf/src/tests/print.rs`). The print-preview and physical-device fidelity gaps remain, so print scores and hours are unchanged. - The Print dialog's Document Ink Options list shows an icon before each spot ink's name, and a click on it prints that one ink as process inks (on the Cyan, Magenta, Yellow and Black plates, with no plate of its own) or as a spot ink again, as [the help page](https://helpx.adobe.com/illustrator/using/printing-color-separations.html) describes for single spot colors. Other spot inks keep their plates, and spot gradient stops and DCS images' spot plates follow each ink's choice (`print.setup {settings: {output: {inks: [{name, convertToProcess: true}]}}}`, kept with the document and in print presets; `print.preview` lists every ink as `documentInks`). These are VectorCraft's own rules: Convert All Spot Colors to Process converts every spot ink and dims the icons while keeping each ink's own choice, a converted ink's Print, Frequency and Angle are dimmed and kept, and process inks and Registration have no icon. Evidence: `print::one_spot_ink_converts_to_process_and_the_others_keep_their_plates`, `print::converting_every_spot_ink_overrides_and_keeps_each_inks_own_choice`, `print::a_spot_gradient_stop_prints_its_process_plates`, `cmykimages::a_dcs_image_converts_only_the_spot_ink_chosen`, `tests::print::a_spot_ink_converted_to_process_is_saved_and_listed_without_a_plate`, `dialogs::tests_print::a_spot_inks_icon_converts_it_to_process_and_back`. Print scores and hours are unchanged. - - The Print dialog's Output section has Overprint Black under Convert All Spot Colors to Process, off by default and available with Separations ([Print color separations](https://helpx.adobe.com/illustrator/using/printing-color-separations.html) lists it among the separation options): black art then leaves the inks under it on the other plates (`print.setup {settings: {output: {overprintBlack: true}}}`, kept with the document and in print presets). Solid 100% K or 100% gray fills, strokes and characters (to within half a percent, as Edit › Edit Colors › Overprint Black counts them), and gradients whose every stop (every color point of a freeform gradient) is, overprint; rich, RGB, Lab, spot-linked and lighter blacks are not marked, paints already set to overprint keep that setting, and only the printed copy is marked. These limits are VectorCraft's own rules. Characters set to overprint now also leave the inks below them on printed PDF plates, a type object's own fill in a PDF is drawn with its blending mode, and Edit › Edit Colors › Overprint Black counts a gradient with a stop linked to a spot swatch as a spot black, as it counts a solid one, and a freeform gradient by the color points it draws from. On a plate, an overprinting paint that puts none of that plate's ink down is drawn as nothing; on PostScript plates so is up to half a percent of another ink in a color that counts as black, and any other faint ink stays on the plate. Evidence: `print::overprint_black_keeps_the_inks_under_solid_black_on_separations`, `print::overprint_black_keeps_the_cyan_under_near_and_freeform_blacks_on_postscript_plates`, `print::overprinting_paints_keep_their_faint_ink_on_postscript_plates`, `print::overprinting_type_leaves_the_inks_below_on_separations`, `print::a_type_objects_own_black_fill_overprints_on_separations`, `tests::print::overprint_black_is_saved_with_the_setup_and_in_presets`, `overprint::tests::a_gradient_with_a_spot_linked_stop_is_black_only_with_spot`, `overprint::tests::a_freeform_gradient_is_black_when_every_point_is`. Print scores and hours are unchanged. + - The Print dialog's Output section has Overprint Black under Convert All Spot Colors to Process, off by default and available with Separations ([Print color separations](https://helpx.adobe.com/illustrator/using/printing-color-separations.html) lists it among the separation options): black art then leaves the inks under it on the other plates (`print.setup {settings: {output: {overprintBlack: true}}}`, kept with the document and in print presets). Solid 100% K or 100% gray fills, strokes and characters (to within half a percent, as Edit › Edit Colors › Overprint Black counts them), and gradients whose every stop (every color point of a freeform gradient) is, overprint; rich, RGB, Lab, spot-linked and lighter blacks are not marked, paints already set to overprint keep that setting, and only the printed copy is marked. These limits are VectorCraft's own rules. Characters set to overprint now also leave the inks below them on printed PDF plates, a type object's own fill in a PDF is drawn with its blending mode, and Edit › Edit Colors › Overprint Black counts a gradient with a stop linked to a spot swatch as a spot black, as it counts a solid one, and a freeform gradient by the color points it draws from. On a plate, an overprinting paint that puts none of that plate's ink down is drawn as nothing; on PostScript plates so is up to half a percent of another ink in a color that counts as black, and any other faint ink stays on the plate. A black linked to a swatch the document lacks separates from its own values, so on PostScript plates it counts as an unlinked black (VectorCraft's own rule). Evidence: `print::overprint_black_keeps_the_inks_under_solid_black_on_separations`, `print::overprint_black_keeps_the_cyan_under_near_and_freeform_blacks_on_postscript_plates`, `print::overprint_black_keeps_the_cyan_under_a_near_black_linked_to_a_missing_swatch_on_postscript_plates`, `print::overprinting_near_blacks_linked_to_a_missing_swatch_keep_the_cyan_on_postscript_plates`, `print::overprinting_paints_keep_their_faint_ink_on_postscript_plates`, `print::overprinting_type_leaves_the_inks_below_on_separations`, `print::a_type_objects_own_black_fill_overprints_on_separations`, `tests::print::overprint_black_is_saved_with_the_setup_and_in_presets`, `overprint::tests::a_gradient_with_a_spot_linked_stop_is_black_only_with_spot`, `overprint::tests::a_freeform_gradient_is_black_when_every_point_is`. Print scores and hours are unchanged. - The Print dialog's General section (and the print preset editor) has a link button after Scale W and H, as the Custom scale has one on [the help page](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/print-documents-in-illustrator.html), where turning it off scales the width and height apart. While it is on, typing either percentage sets the other, and turning it on sets H to W. It is on for new settings, dimmed with the fields unless Scaling is Custom or a tiling choice, toggled with a click, Space or Enter, and named with its on or off state for screen readers. W and H take 1–1000% in the fields. The link is kept with the document's print settings and in print presets (`print.setup {settings: {scale: {linked}}}`); settings saved without it read it as off, so they print as before. Its default, the tiling choices and the agent rules are VectorCraft's own. Evidence: `print::the_scale_link_is_on_for_new_settings_and_off_for_a_saved_scale_without_it`, `tests::print::the_scale_link_keeps_width_and_height_equal`, `tests::print::a_scale_saved_without_the_link_keeps_its_width_and_height`, `dialogs::tests_print::the_scale_link_keeps_scale_width_and_height_equal`, `dialogs::tests_print::a_print_preset_keeps_the_scale_link`. Print scores and hours are unchanged. - A PDF, PDF-compatible `.ai` or `.ait` opened from its pages or its editing copy opens with the File Info that its XMP packet and its document information dictionary give: the title (`dc:title`, its `x-default` item first, else Info `Title`), the author, description, keywords, copyright status, notice and URL, and the created and modified dates, the XMP packet's value where both give one (`crates/pdf/src/tests/file_info.rs`, `crates/engine/src/tests/fileinfo.rs`). An SVG opens with the title of its root ``. The title is File Info's alone (`DocMetadata::title`): the document's name stays the file's name with its extension, a file that gives no title leaves File Info with that name, and exports (PDF, SVG, PNG, EPS, `.ai`) and native saves carry it; changing the title in File Info sets the document's name as before (#3626). - PDF export and PDF-compatible `.ai` and `.ait` saves write the document's File Info created date as the file's creation date, or the time of writing when the document has none, and the time of writing as its modification date; the page information mark still prints the time of writing (`crates/engine/src/tests/fileinfo.rs`, `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/marks.rs`). @@ -2138,7 +2211,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - File › Revert also drops what was started for the content it discards: a file being read for Place, for the place cursor or dropped on the canvas, a bitmap being read for Paste, and a paste waiting at its Swatch Conflict dialog are not placed or pasted in the reverted document, and the status bar says the document was reverted. Edits made while a file is read, a Revert that fails or that a batch rolls back, and a Revert of another document leave the read to finish as before (`crates/ui-egui/src/placing/tests.rs`). - The pixels of a PNG, JPEG, GIF or WebP file that Place decodes to check them are kept in the image store the renderers share, so the canvas's first frame with the placed image draws them without decoding the file again on the UI thread: File › Place, a file dropped on the canvas, a click or drag of the place cursor, `file.place`, and Paste of such an image. A CMYK JPEG is still decoded when it is first drawn (`crates/ui-egui/src/placing.rs`, `crates/render/src/tests.rs`). - A photo whose EXIF orientation turns or flips it (a camera held upright or upside down) is placed and opened upright, as it was taken; the image is stored as it is seen (#4284). A quarter turn swaps the resolution's axes, so the image keeps its physical size. TIFFs read without the image decoder (grayscale with extra channels, CCITT Group 3, CMYK with one plane per ink) follow their Orientation tag too, and a turned CMYK JPEG or TIFF keeps its inks, at the 8 or 16 bits the file has, as a CMYK TIFF. - - PDF export writes a CMYK image that keeps its numbers in an `ICCBased` color space holding, byte for byte, the CMYK profile the image carries (a CMYK TIFF's tag 34675, or a CMYK JPEG's `ICC_PROFILE` APP2 segments) when `output.profiles` is `all` or `taggedSource`, and in PDF/A-2b, PDF/X-3 and PDF/X-4 unless it is `destination` ([the help page](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/pdf-marks-bleeds-and-color-output-options.html)). This covers a CMYK JPEG embedded as it is, one the Compression settings resample or compress again, a TIFF written again, and an image written with its mask as its soft mask. With `none`, and in PDF/X-1a, the image is DeviceCMYK and a JPEG's own profile is left out, so PDF/X-1a export writes a CMYK JPEG that carries a profile. Pixels the Output settings convert are never tagged with the profile of their old numbers. A profile tags an image only when its size, signature, class, CMYK color space and tag table are well formed and it is at most 16 MiB (VectorCraft's own limit). Transparency in a tagged CMYK document blends in the document's CMYK profile; when the file holds no space of that profile it blends in DeviceCMYK, or keeps its RGB space in PDF/A, and never in an image's own profile (`crates/pdf/src/tests/cmykimages.rs`, `export::writer::tests`). + - PDF export writes a CMYK image that keeps its numbers in an `ICCBased` color space holding, byte for byte, the CMYK profile the image carries (a CMYK TIFF's tag 34675, or a CMYK JPEG's `ICC_PROFILE` APP2 segments) when `output.profiles` is `all` or `taggedSource`, and in PDF/A-2b, PDF/X-3 and PDF/X-4 unless it is `destination`, except in PDF/X-3 and PDF/X-4 when that profile is the CMYK output intent's, or when `none` makes every CMYK color DeviceCMYK, which it does only without a CMYK destination of another profile (#1954) ([the help page](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/pdf-marks-bleeds-and-color-output-options.html)). This covers a CMYK JPEG embedded as it is, one the Compression settings resample or compress again, a TIFF written again, and an image written with its mask as its soft mask. With `none`, and in PDF/X-1a, the image is DeviceCMYK and a JPEG's own profile is left out, so PDF/X-1a export writes a CMYK JPEG that carries a profile. In PDF/X-3 and PDF/X-4 with `none` and a CMYK destination of another profile, a CMYK image that keeps its numbers keeps its own profile, and one the conversion changes is untagged. Pixels the Output settings convert are never tagged with the profile of their old numbers. A profile tags an image only when its size, signature, class, CMYK color space and tag table are well formed and it is at most 16 MiB (VectorCraft's own limit). Transparency in a tagged CMYK document blends in the document's CMYK profile; when the file holds no space of that profile it blends in DeviceCMYK, or keeps its RGB space in PDF/A, and never in an image's own profile (`crates/pdf/src/tests/cmykimages.rs`, `export::writer::tests`). - When the Output settings convert an image's colors ([the help page](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/pdf-marks-bleeds-and-color-output-options.html)), PDF export leaves out an image whose pixels can't be decoded or written in the destination's colors, with the warning "an image couldn't be converted to the Output destination and is missing from the picture", in every standard, instead of writing it in its own colors. This covers a CMYK image with more than 2^26 pixels, the most VectorCraft reads CMYK inks for, and a color image that could be embedded as it is but is more than VectorCraft decodes. A color image whose pixel data can't be read is left out with the warning "an image couldn't be decoded and is missing from the picture", as without a conversion. Gray images, whose pixels are not converted, images in a file that converts no colors, and a gray or RGB image that an sRGB destination would convert from its ICC profile (it keeps the profile, with a warning) are written as before, and an image that can't be written at all still gets the warning that it couldn't be decoded (`crates/pdf/src/tests/cmykimages.rs`, `crates/pdf/src/tests/compression.rs`). - PDF export with `output.profiles` set to `none` (Don't Include Profiles) writes no image with the ICC profile it carries, as [the help page](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/pdf-marks-bleeds-and-color-output-options.html) describes for that setting: gray and RGB PNG, JPEG and TIFF images embedded as they are, resampled or compressed again, and CMYK JPEG images. A JPEG kept as it is loses its `ICC_PROFILE` APP2 segments, its other segments and compressed samples unchanged. PDF/A-2b, PDF/X-3 and PDF/X-4 files keep the profiles they tag images with. Left unset (the default, `"default"`, listed as Default in Save PDF), the setting writes device colors while gray and RGB images keep their profiles, as before; that default is VectorCraft's own rule (`a_set_dont_include_profiles_removes_image_profiles`, `a_set_dont_include_profiles_takes_a_cmyk_jpegs_profile_out`). - PDF import keeps the CMYK profile of an image in a four-component `ICCBased` color space, whose stream holds the profile ([ISO 32000-1, §8.6.5.5](https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/PDF32000_2008.pdf#page=157)), byte for byte with the image's ink amounts, so PDF export can write the image in it again. A CMYK TIFF carries it as tag 34675, whatever the image's Decode array and bit depth ([ICC.1:2010, Annex B](https://www.color.org/specification/ICC1v43_2010-12.pdf)). A CMYK JPEG kept as it is carries it in `ICC_PROFILE` APP2 segments in place of a profile of its own, with its compressed samples unchanged, and one whose segments can't hold it is stored as a CMYK TIFF carrying it. A profile that isn't well formed, isn't of CMYK colors or is over 16 MiB (VectorCraft's own limit) leaves the image's inks as they are, untagged. DeviceCMYK and DeviceN images carry no profile, and a CMYK TIFF's tag 34675 is read up to 16 MiB. EPS and PostScript import does not keep one: PostScript defines no `ICCBased` profile stream (`crates/pdf/src/tests/cmykimages.rs`, `cmyk::tests`). @@ -2152,6 +2225,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - An image that SVG import stores again as PNG keeps the ICC profile its TIFF, PNG, JPEG or WebP file carries, as Open and Place keep it, as a PNG `iCCP` chunk, when the profile's color space is the stored samples': gray for gray samples, RGB for RGB ones (). By default, SVG reads an image's colors in the profile built into the image (). A profile of another color space, one too short to be a profile, and the profile of a TIFF whose pixels its own reader converts to RGBA (one with an alpha or other extra channel, or CCITT Group 3) are left out, and the image is still imported (`a_raster_written_again_as_png_keeps_its_icc_profile` in `crates/svg/tests/it/image_orientation.rs`). - SVG import leaves out an SVG shown as an image that it can't read (text that isn't XML, an SVG without a size) and goes on with the images after it, as SVG 2's error processing describes (). Only images that decode count toward the 256 nested SVG images an SVG may show, so an image after many broken ones is imported. Every nested SVG image read, decoded or not, counts toward VectorCraft's own limits of 1,024 reads and 512 MB of text per import; past them, nested SVG images are left out with a warning (`crates/svg/tests/it/import_details.rs`). - SVG import decodes each image data URL (RFC 2397, ) of an `` or `` once, in the imported SVG and in the SVGs shown as its images, however many `` elements, filters or SVG images show it; every use gets the same image. The data URLs of one import decode to at most 512 MB together, VectorCraft's own limit: decoding stops where a URL would pass it, and that image is left out with a warning (`crates/svg/src/import/files.rs`, `crates/svg/tests/it/import_details.rs`). + - SVG import hashes the bytes of each raster image for its image key once per import, however many `` elements or `` elements with the same data URL or linked file show them; the other images get the same key, and the keys, stored images and links are the same as before. With one 3.4 MB PNG data URL shown by 500 `` elements, importing took a median 1,883 ms of thread CPU time when every image was hashed and 28 ms with the keys kept, on Linux with other builds running (`crates/svg/src/import/importer.rs`). - SVG import measures what an SVG expands to before the SVG reader builds it: every copy a `` shows (), chains of ``s included, and the style values each copy gets from its `style` attribute and from the style sheet rules that match it. An SVG that expands to more than 999,999 elements (500,000 on the web) or to more than 64 MB of copied style values is refused with an error, and so is a loop of `` references that would be copied without end. The declarations the import's own style cascade keeps count toward the 64 MB too, once for each element a rule matches, including those of rules the reader drops, such as ones with `:not()`. Matching the style sheets' selectors against those elements may take at most 50,000,000 tests; past that the SVG is refused, so a selector that never matches can't keep the import busy. These limits are VectorCraft's own. An SVG shown as an image, from a data URL or a linked SVG file, counts toward the same limits as the SVG showing it, and one past any of them refuses the whole import (`crates/svg/src/import/budget.rs`, `crates/svg/tests/it/import_details.rs`). - SVG import reads the files that a linked SVG file's own `` elements link to, relative paths from that file's folder (), as it reads the imported SVG's links: a raster stays linked, an SVG file imports as vector art, and one that can't be read gets the placeholder, its link and a warning. SVG 2 tells a viewer not to load these links (); reading them is VectorCraft's own rule. The same href in SVG files of two folders names two files. A link that leads back to an SVG file showing it gets the placeholder and a warning, and reading the links of linked SVG files stops at the nesting depth cap and at 1,024 reads and 512 MB per import, the same limits decoded nested SVG images have, counted separately from them. The text of every linked SVG file read counts, and so does every file read for the links of a linked SVG file, raster or SVG; rasters the imported SVG links to don't. Once either limit is passed, no file linked from a linked SVG file is read and its image is left out with a warning, and an SVG file the imported SVG links to is still shown, without the files its own links name, with a warning. Another href to an SVG file already read, spelled differently or in another SVG file, does not read it again, unless a link back or the depth cap changes what it shows there (`crates/svg/tests/it/import_details.rs`, `crates/svg/src/import/files.rs`). - File › Place and a file dropped on the canvas refuse a PNG, JPEG, GIF or WebP file whose pixels can't be read, such as one cut short by a download or a sync still running, and the status bar shows "Couldn't place : the image's pixels can't be read". Paste and Relink refuse such an image too, and Update Links, or Open when it reads the file again, counts it as missing. A JPEG cut short still places when its pixels can be decoded (`file.place`, `crates/engine/src/tests_place.rs`). @@ -2189,6 +2263,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). @@ -2230,14 +2305,17 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A subpath keeps its anchors in chunks of up to 256 anchors, and the versions of a path share the chunks they have not changed. Editing one anchor copies only the chunk that holds it, so its undo step keeps that chunk instead of a copy of every anchor; adding or deleting an anchor copies the chunk it is in and rebuilds the subpath's table of chunks. When the renderer looks for the anchors that moved, it compares only the chunks the edit copied. Moving one anchor of a selected open path of 10,000 or 200,000 anchors (`path.moveAnchor`, `path.setHandle`, `path.moveAnchors` or a nudge) keeps at most 48 KiB in the undo step and in the redo step, where it kept a copy of every anchor at 56 bytes each (counted in the engine's tests). Files are written and read as before, each subpath's anchors as one list. Opening a document keeps the layouts it makes for its type objects, up to 128 MiB, and the first frame uses them instead of laying those objects out again. It does not keep a layout with bitmap or color glyphs or a text object with a gradient. The frame uses a layout only for a text object equal to the one laid out, and only while the fonts and the hyphenation exceptions have not changed. It uses each layout once. The renderer drops the rest when a frame that used one ends, and all of them after eight frames that use none. The frames of a threaded story are laid out while the file is read, and the first frame lays them out again. The pixels are the same. On Windows at 1600 × 1200, in medians of seven interleaved rounds of a local example, counted in the main thread's CPU cycles because other builds were running: with 5,000 point type objects in view the first frame takes 409 million cycles instead of 894 million and the open 816 million instead of 665 million, so the two together take 1,225 million instead of 1,559 million; with one area type object of 500 paragraphs the first frame takes 697 million instead of 1,193 million and the open 535 million instead of 568 million. Type › Show Hidden Characters keeps the marks it places on each text object from one frame to the next. The canvas lays a text object out again when an edit changes it or its threaded story, or when the last frame that showed the marks did not draw it, and it lays out all type in view again when the fonts or the hyphenation exceptions change. With 1,000 two-line labels in view, drawing the marks takes 0.8 ms per frame in a release build instead of 19.7 ms. + With a Type tool active, the in and out ports of the selected area type and type on a path, and the highlight of a selected story's other frames after Select All, use each frame's layout from the last frame instead of laying the frame out again. A frame is laid out again when its text object changes, or when the fonts or the hyphenation exceptions change. With 200 selected area type frames of about 400 characters, one of them being edited, the Type tool's overlays take 0.27 ms per frame instead of 121 ms; with a 5-frame story selected they take 0.016 ms instead of 2.0 ms (release build on Linux, medians of seven runs, measured while other builds were running). A selection with more than 100,000 points to outline shows its bounds instead of each object's outline and anchors. Paths count their anchors. Area type and type on a path count the anchors of their frame or path, and point type counts six: its box's corners and the ends of its baseline marker. Images, symbol instances, placed documents, and area type or type on a path in perspective count the four corners of their box, and gradient meshes and envelopes count their points and the ends of their mesh lines. The hover highlight leaves out an object past that count, and such an object shows its bounds as the key object. With 32,768 type objects, images, symbol instances, gradient meshes or envelopes selected, the selection's outlines and anchors add fewer than 100 vertices to the canvas's mesh (#2460). The canvas keeps the selected objects' outlines, anchors and handles from one frame to the next as one mesh. It builds an object's marks again when the object, its layer color or its selected anchors change. A pan moves the kept outlines and handles and places the anchor squares again. Each subpath and handle gets its triangles the first time it is in view. A frame with a new zoom or rotation draws the marks one shape at a time and keeps nothing, and the next frame at that view builds them. The pixels are the same, apart from two small differences: a kept outline's corner of exactly 90 degrees in a rotated view can keep its miter or cut corner after a pan, and kept vertices can move by rounding errors. On Windows at 1440 × 900, in a release build, with 2,000 selected circles of 50 anchors each in 10 fill colors, an idle frame takes 12.8 ms instead of 59.9 ms with the Selection tool and 29.8 ms instead of 192.1 ms with Direct Selection (medians of five runs). A frame during a zoom takes about what it did: 86.7 ms instead of 80.0 ms with the Selection tool. Delete, Cut, Group, Ungroup, Make and Release Compound Path, Make Clipping Mask, Send to Current Layer, Duplicate, Copy in the Move, Rotate, Scale, Reflect and Shear dialogs, Transform Each with Copy and each move of an Alt-drag take time in proportion to the size of the document (#1429). Cut, and Clear with `ids`, take the removed objects out of the selection in one pass over the selected objects. With 50,000 objects selected and all of them cut, that step takes 5.07 to 5.91 ms instead of 544 to 630 ms, with 20,000 it takes 1.75 to 1.87 ms instead of 91.7 to 97.2 ms, and with 2,000 it takes 0.120 to 0.148 ms instead of 0.940 to 0.955 ms (release build, 7 wall-clock runs of each, measured while other builds were running). + Cut with direct-selected anchors or segments removes the objects selected whole and the paths it leaves with no segment in one pass over each layer or group that holds them, and then removes the compound paths left with no members, instead of removing each one on its own. The document, the selection, the clipboard and the undo step are the same as before. With 2,000 of 10,000 squares on one layer selected whole and two anchors of another picked, Cut walked the document's tree 10,005 times and now walks it 8 times, and takes a median of 11 ms of CPU time instead of 573 ms (release build on Linux, seven alternating runs of each in one process, `cargo test --release -p vectorcraft-engine --lib -- --ignored --nocapture direct_selection_cut_timing`). Tests: `cmd::edit::tests` in `crates/engine/src/cmd/edit/tests.rs`. In the web build the status bar's render and UI times are measured with the browser's `performance.now()`, and the Layers panel stops rendering row thumbnails in a frame once they have taken 8 ms. On the desktop, the Layers panel renders a row's thumbnail on its thumbnail thread when the row's paths, and the paths of its opacity masks that are not disabled, hold more than 2,000 anchors in all. It already did this for the first thumbnail of a row of more than 200 objects. Until its first thumbnail is ready, the row shows boxes at the bounds of up to 41 of its paths, each in its path's solid fill or stroke color or in gray, when its own paths, without its opacity masks, hold at most 2,000 anchors in all, and an empty white box otherwise. With one path of 200,000 anchors, the first frame after the panel opens takes 2.4 ms instead of 393 ms (release build, median of three runs). The same 2,000-anchor limit counts each glyph of type as 4 anchors, each point of a gradient mesh as 1 and every 100 pixels of an image as 1, and a symbol instance or a placed document counts the objects and anchors of the art it shows. A placed document whose file has not been read yet, or a symbol nested more than 8 deep (one that holds an instance of itself, for example), gets its first thumbnail on the thumbnail thread, and so does a row whose art takes more than 20,000 steps to count (each object, subpath, text run and symbol looked at is one step). The first frame after the panel opens takes 2.4 ms instead of 19.8 ms with 5,000 glyphs of point type, 1.8 ms instead of 343 ms with one instance of a symbol of a 200,000-anchor path, 2.0 ms instead of 11.0 ms with a 100 × 100 mesh, and 2.1 ms instead of 274 ms with a placed document of a 200,000-anchor path (release build, median of three runs). When the Layers or Links panel shows another document's rows, the thumbnail thread drops the row thumbnails it has not started for the documents not shown, and it drops all of them when the Layers or Links panel is open after the last document closes. Those rows ask for their thumbnails again when their document shows again, and the thumbnails already made are kept. With 150 rows of 20,000-anchor paths waiting for another document, the 8 rows of such paths of the document shown get their thumbnails in 153 ms instead of 3,265 ms (debug test build, median of three runs). + The Links panel keeps its `links.list` rows and Link Info in one shared cache, and a frame that fetches nothing new reads that cache without copying the rows. The cache is replaced when the document or its revision changes, the Show, Sort or Show DCS Transparency Interactions option changes, or the files are looked at again every 2 seconds, and, while an image is selected, when Link Info opens or closes or the first selected image changes. With 2,001 images a frame's cache step takes 0.2 µs instead of 1.79 ms, and with 10,001 images 0.2 µs instead of 12.2 ms (test build, median of 7 wall-clock runs of 1,000 frames, measured while other builds were running). In the web build, while a pan, zoom or rotation changes the view of a document whose last canvas render took more than 8 ms, the canvas draws the last frame moved with the view, and it renders the art again once the view has been still for 0.2 s. An Alt-drag with the Selection, Direct Selection, Group Selection, Rotate, Scale, Reflect or Shear tool copies the selection on its first move, and the moves after it transform those copies; the previews of the Move, Rotate, Scale, Reflect and Shear dialogs with Copy and Preview on copy the selection once in the same way (#1429). An Alt-drag of objects in perspective with the Perspective Selection tool, and an Alt-drag of a plane widget with that tool or the Perspective Grid tool, copy the objects on the first move, and the moves after it move those copies (#1429). @@ -2354,6 +2432,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. @@ -2706,6 +2785,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. @@ -2841,6 +2924,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | Date | Change | Summary | |---|---|---| +| 2026-11-16 | minor | Layers panel: an Alt-drag copies a row above or below its own place (`layer.move` with `copy` and that row as the target), so the top layer dragged up, the bottom layer dragged down and a document's only layer are copied (#8237). Scores and estimates unchanged. | | 2026-11-16 | minor | Layers panel: rows or the selected-art square dragged over the list show the copy cursor while Alt is held, as the drop then copies, and the grabbing hand otherwise (#8217). Scores and estimates unchanged. | | 2026-11-16 | minor | Gradient panel: the strip under the ramp, where a click adds a stop, shows the white arrow with a plus on Windows and X11, where the system copy cursor showed as the plain arrow (#8241). Scores and estimates unchanged. | | 2026-11-16 | minor | Properties panel: while the Type tool edits text, the Character section shows the font family and style and the Variable Font button of the first selected character (or of the character before the caret), not those of the text object's first run (#8189). Evidence: `panels::properties::tests::character_section_shows_the_type_tool_selections_style`. Scores and estimates unchanged. | @@ -2860,6 +2944,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | 2026-11-12 | minor | `.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; `.ai` import evidence updated (#6824); scores and estimates unchanged. | | 2026-11-12 | minor | Explicit editing-data import keeps a single artboard beyond a capped 14,400 pt PDF page (#6865), with a warning; automatic mode stays unchanged. Scores and estimates unchanged. | | 2026-11-12 | minor | Glyphs review (#6084): Entire Font uses the selection's version and variable axes for previews and alternate applicability. The default cell can reset an unlisted glyph choice when GSUB lists no alternates. Encoded Latin and other ordinary characters insert unchanged even if their glyph also has Arabic positional provenance; Arabic presentation forms retain base-letter insertion. Remove a redundant charmap scan from unlisted-glyph checks. Scores and estimates unchanged. | +| 2026-11-12 | minor | #6625 cap/join follow-up: hidden-fill and no-fill stroke hits must respect their cap/join geometry; focused CPU regressions passed. Existing fill-stack evidence, scores and estimates unchanged. | | 2026-11-09 | minor | Glyphs review (#6084): positional alternates with no supported feature are accepted as glyph choices in both panel views; Entire Font's unlisted-glyph and name-ownership behavior is retained. OpenType style options keep only a valid last on-value when enabling a set. Contradictory old glyph-choice evidence corrected; scores and estimates unchanged. | | 2026-11-07 | minor | Type core: the Glyphs panel's Alternates for Current Selection applies the OpenType feature that draws a variant to the selected letter alone, so an Arabic word stays joined (`salt=2`; the style commands take `tag=N`), and Show › Entire Font lists the glyphs no character maps (#5514; [Replace characters with alternate glyphs](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/replace-characters-with-alternate-glyphs.html)); evidence added; scores unchanged. | | 2026-11-12 | minor | UI chrome: a numeric-field focus click released more than 1 pt from its press keeps the caret; a tap within 1 pt still selects the whole value (#6659, follow-up to #1326); scores and hours unchanged. | @@ -2879,6 +2964,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | 2026-11-14 | minor | Symbols panel context menu: right-click on a symbol in thumbnail or list view displays a context menu (Place Symbol Instance, Edit Symbol, Duplicate Symbol, Delete Symbol, Break Link to Symbol, Select All Instances), selecting the symbol first if unselected; scores and estimates unchanged. | | 2026-11-11 | minor | Bundled content: built-in Inventory Icons symbol library (Sword, Shield, Potion, Key, Gem); symbol libraries evidence updated; ~38% → ~40%; more built-in symbol libraries remain. | | 2026-11-11 | minor | Guides and snapping: a Shift move slides the selection along its line onto a ruler guide by its edges and centre, as a move without Shift does (#4312); a guide a nearly parallel line only reaches a long way off pulls nothing. Score and hours unchanged (estimated). | +| 2026-11-11 | minor | #6625: path and compound-path interior hits follow enabled non-None fill rows, including lower fills beneath a top None row; hidden-only interiors miss; zero-opacity fills remain selectable. Scores and estimates unchanged. | | 2026-11-10 | minor | Automation: MCP tool count 33; headless `command_list` lists `UI_COMMANDS` (`ui: true`); eight prompts; effect-id vs command-id clarified (#6460); scores and hours unchanged. | | 2026-11-10 | minor | Type advanced: the Edit Custom Dictionary dialog, #4936; evidence added; the Check Spelling dialog remains; scores and hours unchanged. | | 2026-11-10 | minor | File formats: in a `.ai` or EPS opened from its editing data, an envelope of type opens live where it draws as its drawn art and the layers with it draw as the page (the envelope weighed as the art it draws); elsewhere, and where a text or visibility variable binds its type, it keeps its drawn art, with a note (#3179); evidence updated; scores and hours unchanged. | diff --git a/docs/three-d.md b/docs/three-d.md index 4f8d4003b5..4826df3552 100644 --- a/docs/three-d.md +++ b/docs/three-d.md @@ -469,8 +469,8 @@ 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), and the swept side of Revolve, which the -public page's example of a label on a bottle describes. +Extrude & Bevel's front and back caps and its side (its walls and bevels), the plane of the Plane type (Rotate), and +the swept side of Revolve, which the public page's example of a label on a bottle describes. - 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 +479,9 @@ public page's example of a label on a bottle describes. - 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; 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; 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 @@ -522,6 +522,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 @@ -530,15 +544,16 @@ 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 the type to Inflate drops the graphics, and - changing between Extrude, Plane and Revolve keeps them, except that Plane and Revolve drop the graphics on the - back cap; on Revolve the front's graphics go on its side. +- 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 the type to Inflate drops the + graphics, and changing between Extrude, Plane and Revolve keeps them, except that Plane and Revolve drop the + graphics on the back cap and on Extrude & Bevel's side; on Revolve the front's graphics go on its side. - `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 @@ -553,7 +568,7 @@ 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` and `threeD.revolve` 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 +with `symbol` (the name of a document symbol), `face` (`front`, `back` or `side`, 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, 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 @@ -567,11 +582,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 Inflate and 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 and Revolve's side only - ([Graphics](#graphics)). +- **Materials** (base and Adobe Substance), graphics on Inflate, shadows of lights after the first, and + **ray-traced rendering** are not built: shading uses directional lights, in the paint of the fill or stroke the + solid is built for ([Fills and strokes](#fills-and-strokes)), and only the first light casts a shadow + ([Shadows](#shadows)). Graphics map onto planar faces, Extrude & Bevel's side as one surface unrolled flat, and + Revolve's side only ([Graphics](#graphics)). - The bevel shapes and their names are our own; custom 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 8ddaf7c662..e44a28165c 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,9 +1,11 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** minor (Layers panel: Alt over the list shows the copy cursor while rows or the selected-art square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **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: Layers panel: Alt over the list shows the copy cursor while rows or the selected-art square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). > +> 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. +> > Vector Halftone preview update (2026-11-10): temporary dot selection marks are hidden, and the bounding box stays available (#6369). > > Numeric spinner update (2026-11-10): held mouse arrows repeat past the click timeout; scores and estimates unchanged (#6307). @@ -58,6 +60,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | 2026-11-09 | minor | Document Setup and Character panel Language lists: Nepali, Konkani and Sindhi complete #4943; Assamese and Sanskrit are already present from #5946. Names in all 27 catalogs come from [CLDR locale language-name data](https://github.com/unicode-org/cldr/tree/main/common/main). The public [language assignment documentation](https://helpx.adobe.com/illustrator/using/spelling-language-dictionaries.html) describes the Character panel Language menu, but does not establish that these five languages are listed there; inclusion and a single Sindhi entry remain maintainer decisions. Scores unchanged | | 2026-11-14 | minor | G5: Tech Circuit adds three original procedural brushes (Circuit Trace, Bus Lines, Terminal Nodes); ten built-in brush libraries. G5 remaining estimate 3–13 h (estimated); parity scores and headline totals unchanged. | | 2026-11-14 | minor | Layers panel: right-clicking a layer/group/object row shows a context menu with Options…, Duplicate, Delete, Lock/Hide Others, Locate Object, and Collect for Export — matching standard desktop layer panel conventions. Scores unchanged. | +| 2026-11-16 | minor | Layers panel: an Alt-drag copies a row above or below its own place, so the top layer dragged up, the bottom layer dragged down and a document's only layer are copied (#8237). Scores and estimates unchanged. | | 2026-11-16 | minor | Layers panel: rows or the selected-art square dragged over the list show the copy cursor while Alt is held, as the drop then copies, and the grabbing hand otherwise (#8217). Scores and estimates unchanged. | | 2026-11-16 | minor | Gradient panel: the strip under the ramp, where a click adds a stop, shows the white arrow with a plus on Windows and X11, where the system copy cursor showed as the plain arrow (#8241). Scores and estimates unchanged. | | 2026-11-13 | minor | Pencil cursors: the continuation cursor (a short rising line) shows over an open end of a selected path before any press, freehand too, and while a continuing stroke nears another selected path's open end it connects to; the straight-line cursor is a short level line; a continued path, a straight line too, shows the closing cursor and closes within Close Paths When Ends Are Within of its other end, and with Alt at the release. Scores and estimates unchanged. | @@ -190,6 +193,7 @@ tools, never checked side by side) isn't captured row by row. | Layers panel: a layer whose Layer Options › Print is off shows its name italic (#5739) | done | the panel row and its drag ghost; a printing layer stays upright, and Print on again restores it; `panels::layers` test `a_layer_that_does_not_print_has_its_name_italic` | | Layers panel: Alt-drag shows the copy cursor (#8217) | done | rows and the selected-art square dragged over the list show the copy cursor while Alt is held and the grabbing hand otherwise, following Alt mid-drag; on Windows and X11 the copy cursor is the white arrow with a plus (the panels' add cursor, #8241); over the trash and New Layer, which ignore Alt, the hand stays; guide rows keep theirs; `alt_shows_the_copy_cursor_while_rows_are_dragged`, `drag_cursor_shows_a_copy_only_where_the_drop_copies` | | Gradient panel: add-stop cursor under the ramp (#8241) | done | the white arrow with a plus (the Group Selection glyph) over the strip under the ramp, handed to the OS on Windows and X11 (winit shows the plain arrow for the system copy cursor there), the system copy cursor elsewhere; over the ramp itself the arrow stays; `panels::gradient` test `the_strip_under_the_ramp_shows_the_add_cursor` | +| Layers panel: Alt-drag copies a row beside itself (#8237) | done | with Alt, rows held over one of their own rows copy above or below it, and the bottom layer dropped in the empty space under the list copies below itself, so the top layer dragged up, the bottom one dragged down and a document's only layer are copied; a move onto its own place, or a copy inside itself, still does nothing; `panels::layers` tests `alt_dragging_the_top_layer_up_or_the_bottom_layer_down_copies_it`, `a_lone_layer_alt_dragged_up_or_down_is_copied`; engine test `a_copy_goes_above_or_below_a_row_it_copies` | | Blend spine Anchor Point conversion and handle editing (#2544) | implemented | symmetric handles, independent drag/retraction, visible-handle policy and selection/stacking covered by tool and engine regressions; Windows native canvas checks and screenshots reviewed in PR #2643 | | Several blend spine points picked and dragged together (#5285) | done | with Direct Selection, Shift-click picks more points of a selected blend's spine or takes one away, as on a path; dragging any picked point moves them all, and the key objects on them, in one undo step (`object.blend.spine.moveAnchor {with}`); a marquee picks the spine points inside it on the topmost selected blend, and with Shift adds or takes them away | | Add/Delete/Anchor Point tools; Anchor Point tool drags segments to reshape | done | #2267: a click on a handle end retracts that handle and leaves the anchor a corner with the other one; Shift held at the press on an anchor moves it, handles and all (Shift kept down: at 45° steps) instead of pulling out handles | @@ -211,6 +215,7 @@ tools, never checked side by side) isn't captured row by row. | Behaviour | Status | Notes | |---|---|---| +| Path and compound-path interior selection follows enabled non-None fill rows | done | #6625; lower visible fill beneath a top None row stays selectable; hidden-only/None interiors miss; zero-opacity, edge, Outline/path-only and hole controls in `crates/engine/tests/path_fill_hits.rs`; hidden-fill and no-fill stroke cap/join CPU regressions passed | | Deleting segments or anchors that disconnect an ordinary path creates independent selected objects | done | #3380, deletion only: first piece retains its ID, styles and transforms carry over in sibling order, bounds-fitted gradients keep their original placement, and one Undo restores the original. Existing multi-subpath paths and compound members stay intact. `delete_path_pieces` covers transformed/styled rectangles, cubic handles and Undo/Redo. Endpoint highlighting remains open. | | Click/Shift-click anchors; marquee toggles with Shift | done | #483 | | Align selected anchors to their bounds or the artboard; repeating an alignment that moves nothing keeps Undo, Redo and saved state | done | #1180 follow-up; engine regressions include rounding-only moves and unchanged handles; #1641 (fixes #1636): Align and Distribute act on the anchors selected with Direct Selection, the points of one path aligning to each other and Distribute spacing them | @@ -403,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) | @@ -448,7 +454,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Control bar: Paragraph: link and Align left/center/right while type is selected (#5372) | done | After the Character controls, as the public documentation has the Control panel format paragraphs ([Paragraph panel overview](https://helpx.adobe.com/illustrator/using/formatting-paragraphs.html), [Align text](https://helpx.adobe.com/illustrator/using/align-text.html)); the link opens the Paragraph panel in a popover, as Character: does with the Character panel. The bar trims from its right end: X/Y/W/H, Distribute, Align, area type vertical alignment, then these buttons, then the link. The three-button set is our choice for room; all seven alignments are in the popover. `panels/paragraph/tests.rs` headless tests (`the_control_bar_shows_the_paragraph_alignment_of_the_selected_type`, `the_control_bar_trims_its_paragraph_section_after_the_controls_to_its_right`) | | Pathfinder shape results keep their source names and SVG IDs | done | #1293; Minus Front keeps the back name, Minus Back the front name; Unite/Intersect/Exclude use the backmost named input; compound output carries it once; geometry and paint unchanged | | Attributes fill-rule controls with a compound member selected | done | Edits the compound's rule; direction still edits only the member; rendered-hole and Undo/Redo regression tests (#1197) | -| Info panel follows the tool in use: W and H show the change in x and y, with the distance and the angle, while the selection moves or the Gradient tool draws a vector; the Scale tool's percentages; the center and angles of a Rotate, Reflect or Shear tool drag; the Zoom tool's magnification; the Paintbrush's brush. W and H follow Use Preview Bounds, several selected objects show only the paint and type they share, and Show Options names a tint or a gradient swatch | done | `info.readout`; `Tool::readout`; behavior from the Info panel overview in the [archived user guide](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=76); number formats, the rows shown between drags and the Direct Selection and Group Selection readouts are VectorCraft's own | +| Info panel follows the tool in use: W and H show the change in x and y, with the distance and the angle, while the selection moves, the Gradient tool draws a vector or a Pen drag pulls out an anchor's handle; the Scale tool's percentages; the center and angles of a Rotate, Reflect or Shear tool drag; the Zoom tool's magnification; the Paintbrush's brush. W and H follow Use Preview Bounds, several selected objects show only the paint and type they share, and Show Options names a tint or a gradient swatch | done | `info.readout`; `Tool::readout`; behavior from the Info panel overview in the [archived user guide](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=76); number formats, the rows shown between drags and the Direct Selection and Group Selection readouts are VectorCraft's own | | Make Compound Path on a group (such as outlined type) keeps its backmost path's paint; compound paths joined into one keep their holes | done | #1537 | | Symbol libraries: Window › Symbol Libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, User Defined, Other Library…, Save Symbols…) and the Symbols panel's Symbol Libraries Menu button and its menu's Open Symbol Library / Save Symbol Library…; a click on a library symbol adds it to the document's Symbols (one undo step, it becomes the current symbol), Shift/Cmd-clicks select for Add to Symbols, and a symbol dragged onto the canvas is added and placed where it is dropped | done | [public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html), [Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), [placing from a library](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html); `window.symbolLibrary`, `window.symbolLibrary.other`, `ui.saveSymbolLibrary` (dialog `saveSymbolLibrary`), `window.userSymbolLibrary1`…`10`; `panels::tests_symbol_libraries`; five built-in libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons; original, generated in code) | | Brush libraries: Window › Brush Libraries (Art Ribbons, Ink and Wash, Calligraphic Nibs, Bristle Brushes, Pattern Borders, Scatter Shapes, Game Trails, Energy Beams, Dry Media, Tech Circuit, User Defined, Other Library…, Save Brushes…) and the Brushes panel's Brush Libraries Menu button and its menu's Open Brush Library / Save Brush Library…; a click on a library brush adds it to the document's Brushes (one undo step, it becomes the current brush, and selected paths take it in the same step), Shift/Cmd-clicks select for Add to Brushes, a brush dragged onto a path is added and applied to it and one dragged onto the Brushes panel is added; thumbnails render with the library's patterns and symbols | done | [public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel overview](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html); `window.brushLibrary`, `window.brushLibrary.other`, `ui.saveBrushLibrary` (dialog `saveBrushLibrary`), `window.userBrushLibrary1`…`10`; `panels::tests_brush_libraries`; ten built-in libraries (original, generated in code) | @@ -478,6 +484,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Status bar: a click on the info field opens a Show menu that chooses its readout: Artboard Name, Current Tool (the default), Date and Time, Number of Undos (undo and redo counts) or Document Color Profile; kept with the UI state | done | `view.statusBarShow`; [public behavior reference](https://web.archive.org/web/2014/https://helpx.adobe.com/illustrator/using/workspace-basics.html); `the_status_bar_info_field_shows_the_chosen_readout`, `a_click_on_the_info_field_opens_the_show_menu`, `the_status_bar_show_choice_is_checked_and_saved`. The menu labels are VectorCraft's own | | Background Export: a progress dialog with the file name, the artboard count and a bar (busy for one artboard and for formats made in one go), Cancel (Esc) and Continue in Background; it opens after 0.4 s and never over another dialog. A cancelled export writes no file | done | #2564; on the shared `vectorcraft_doc::cancel` token (#2546), so a cancelled render keeps no half-drawn pattern tile or effect raster. The bar moves between artboards, not within one. Save As, Export for Screens and Export Selection don't show it yet | | Swatch, graphic style and symbol library panels: each library opens in a panel of its own, several at once, that floats, groups, docks and closes like any panel; opening an open library brings its panel forward; Previous / Next Library change the library in place; the panel menu's Persistent reopens the panel at startup with its view and find field (a library loaded from a file is read again; when its file is missing the panel reopens showing the file's path with Locate Library…, and the status bar names the file) | done | #2603; panel ids `library::`, `ui.libraryPanel {panel, library?, view?, showFind?, persistent?}`, `ui.libraryPanel.locate {panel, path?}`; the library panels have no sort option, as before | +| Raster export dialogs retain supplied values for their controls and apply defaults only to omitted values | done | #8324; `tests_raster_supplied_options` checks PNG resolution, background, anti-aliasing and interlacing through `file.export.png`, JPEG quality, omitted defaults, and invalid resolution rejection | | DXF export/import preserves intended curve closure | done | #1299; R13–2018 closed SPLINE bit set/read; an open curve ending at its start stays open; knots and control points unchanged; circular cubic paths export as native CIRCLE/ARC where stroke semantics permit; DXF Options' Preset menu and `document.exportDxf`'s `dxfPreset: "cnc"` set the CNC / CAM options (#5500) | | macOS save sheet: choose the format from a menu | done | #866; the save panel is VectorCraft's own `NSSavePanel` with its Format menu set before the sheet opens (`apps/vectorcraft/src/mac_save_format.rs`); #1855 had withdrawn the menu that was added after the sheet began, which made Save As, Save a Copy and the first Save show no sheet | | Preferences: every option acts | partial | 2 stored but unused (#394, audited 2026-10-30): Scratch Disks, Legacy vector clipboard; the rest act (Units › East Asian Type since 2026-10-31; Open Documents As Tabs: cleared, new documents open in floating windows). General › Corner Radius drives the Rounded Rectangle tool and follows its ↑/↓ (2026-10-24) | @@ -500,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 | @@ -580,6 +588,7 @@ before release (#6373). [Paint faces and edges](https://helpx.adobe.com/illustra | 2026-11-12 | minor | Remove Background for a selected image in the Contextual Task Bar, Properties › Quick Actions and the Control bar, which runs at once with its defaults. Scores and estimates unchanged. | | 2026-11-12 | minor | Live Paint Bucket fills faces crossed in one drag (#6373). Scores and estimates unchanged. | | 2026-11-12 | minor | Save refusal follow-up (#6146): changed format opens its Save options; unchanged format retains original options. Focused UI regressions passed, including the format-change case that failed before the fix; native panel acceptance pending. Scores and estimates unchanged. | +| 2026-11-12 | minor | #6625 cap/join follow-up: hidden-fill and no-fill stroke hits must respect their cap/join geometry; focused CPU regressions passed. Existing fill-stack evidence, scores and estimates unchanged. | | 2026-11-11 | minor | Ruler origin: the corner drag snaps as a drawn point does, onto the art's and the artboards' anchors, centres, edges and paths, and with Snap to Point along the ruler guides; scores and estimates unchanged | | 2026-11-11 | minor | macOS canvas cursor delivery (#2292): while the host owns the cursor it sets it again on every pass, so the tool's cursor stays after the pointer moves (#6362); `mac_cursor` ownership test updated; scores and estimates unchanged. | | 2026-11-11 | minor | Eyedropper copies effective character dimensions between transformed text objects (#6404); scores and estimates unchanged. | @@ -588,6 +597,7 @@ before release (#6373). [Paint faces and edges](https://helpx.adobe.com/illustra | 2026-11-11 | minor | A middle-click on a document tab (or its ×) closes it as the × does; closing a document's last view with unsaved changes asks to save first (#6506). VectorCraft addition; scores and estimates unchanged. | | 2026-11-11 | minor | Files that record no units (PDF, EPS or `.ai` without ruler units, raster images, metafiles, Affinity files, importer plug-ins) open and revert in Preferences › Units › General instead of points; native, SVG and DXF files and `.ai`/EPS ruler units are kept (#5820). Scores and estimates unchanged. | | 2026-11-11 | minor | Blob Brush: while painting, the preview of a round tip is the outline of the area the stroke adds, round at both ends, as the stroke it commits (#4343). Scores unchanged (estimated). | +| 2026-11-11 | minor | #6625: path and compound-path interior hits follow enabled non-None fill rows, including lower fills beneath a top None row; hidden-only interiors miss; zero-opacity fills remain selectable. Scores and estimates unchanged. | | 2026-11-10 | minor | Symbol libraries: Inventory Icons joins Basic Shapes, UI Frames and Map Markers as a fourth built-in library (Sword, Shield, Potion, Key, Gem; no default 9-slice). | | 2026-11-10 | minor | Held numeric spinner arrows keep stepping past the click timeout and stop on release (#6307). Scores and estimates unchanged. | | 2026-11-10 | minor | Vector Halftone Preview leaves the dots unobscured and keeps the selection box (#6369). Scores and estimates unchanged. |