diff --git a/ASSETS.md b/ASSETS.md index 2c7a07478b..0e4e4aa4fe 100644 --- a/ASSETS.md +++ b/ASSETS.md @@ -135,6 +135,7 @@ Generated-in-code art is original and has no file to list. This covers the defau | `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 | | | `assets/icons/dc-crystallize.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-cube.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-curvature-circle.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (an arch with the circle that touches it at its top, and that circle's center) | MIT OR Apache-2.0 | | | `assets/icons/dc-dash-align.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-dash-exact.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-dimension.svg` | Osama Amin | Original work, drawn for VectorCraft: a dimension line with arrowheads between two extension lines | MIT OR Apache-2.0 | | diff --git a/ROADMAP.md b/ROADMAP.md index ea37f12caf..2a7e275faf 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -140,6 +140,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-16: Check Fold Lines in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and the Fold Lines panel's Check button): the fold lines of the selection or the document are split into blanks, panels and hinges (cut lines bound the material, and creases, partial cuts and perforations divide it into panels), and 15 kinds of issue are listed, errors and warnings, each naming its lines: cut lines that enclose nothing or end loose, gaps closed within a tolerance, a cut on top of a crease, duplicate lines, creases that end inside a panel, divide nothing, lie outside the blank or are not straight, gaps too narrow to map, fold lines in a hole, panels joined by no crease, and fold lines on a non-printing layer. The panel lists the issues in the interface language; clicking one selects its lines (`addon.packaging.check`). A VectorCraft addition: headline numbers unchanged. - 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-17: Curvature Circle tool (after the Circle tool in its group): a click on a path draws the circle that touches it there and bends as it bends, on the side it bends toward, or with Shift on the other side; a segment that is the usual cubic of a circular arc of 90° or less gives the arc's own radius, so a click on a circle draws that circle; the tool shows the circle, its center and its radius (with an asterisk for an arc's radius) until the click, or "Straight segment", "Cusp", "Corner" or "Circle too large" where it draws none (`shape.curvatureCircle`). One undo step per circle. A VectorCraft addition: headline numbers unchanged. - 2026-11-15: Circle through three points: three Shift-clicks with the Ellipse tool, or `shape.circleThroughPoints` with three points or three selected anchor points, draw the circle whose edge passes through them, with the current paint, in one undo step; after two points the tool previews the circle through the pointer, and two points that are the same or three on one line are refused with a message. Scores and estimates unchanged. - 2026-11-17: Circle tool (after the Ellipse tool in its group): two clicks or a drag draw the circle on that diameter, and a click followed by a drag from a second point to a third draws the circle through the three; Shift keeps the diameter at 45° steps, Alt rounds a two-point circle's diameter to the rulers' ticks at the current zoom, points snap to Smart Guides, and the tool shows the circle, its center, its radii and its diameter until the release, or "Circle too large" for points on one line or a circle past the canvas. `shape.circleThroughPoints` also takes two points or two selected anchor points as the ends of a diameter. One undo step per circle. A VectorCraft addition: headline numbers unchanged. - 2026-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`). @@ -150,10 +151,12 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-01: Randomize Opacity joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): each selected object gets its own opacity at random between a minimum and a maximum percent, with a seed that repeats the result, as one undo step (`addon.arrange.randomizeOpacity`, #4925). - 2026-11-01: Sort Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects are sorted by width, height, area, position, opacity or stacking order (small to large, large to small or at random) and take another of those in that order, trading their values or stepping them evenly, as one undo step (`addon.arrange.sort`, #4917). - 2026-11-15: Tangent Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the circles that touch two selected paths or compound paths at a set radius, or three of them (up to eight for three circles), touching each outline without crossing it; circles, rotated ellipses and other paths alike. A dialog that previews every circle or one picked by number, the current paint, one undo step (`addon.pathtools.tangentCircle`). A VectorCraft addition: headline numbers unchanged. +- 2026-11-17: Add Bounding Rectangle and Add Bounding Circle join the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): a live rectangle on the selection's geometric bounding box, or the smallest live circle that holds its outlines, around the whole selection or around each object, with the current paint and one undo step; the menu items open a dialog with Offset, One per Object and Preview (`addon.pathtools.boundingRectangle`, `addon.pathtools.boundingCircle`, #6966). A VectorCraft addition: headline numbers unchanged. - 2026-11-01: New Symbols from Layers joins the Document Tools add-on (Object › Plug-ins › Document Tools): one symbol of each top-level layer's art (the layers highlighted in the Layers panel when two or more are, else every layer), named after the layer, made as New Symbol makes one; Convert Layers to Symbols also puts an instance of each in place of its layer's art. Empty layers are skipped and reported; one undo step. A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Document Tools, a built-in add-on (Object › Plug-ins › Document Tools), starts with Save a Timestamped Copy: a copy of the document named `_YYYY-MM-DD_HH-MM` (UTC; `-2`, `-3`… when that name is taken) goes next to it, or into a folder picked for a document never saved, written as File › Save a Copy writes it, so the document keeps its path, title and modified state. Off on the web, which has no clock. A VectorCraft addition: headline numbers unchanged. - 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-17: Tangent Circle Tool joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools, and the All Tools drawer): click a path segment, then another, to draw the circle tangent to the first where it was clicked that touches the second; Shift uses the tool's radius and a drag from the second segment sets the radius (Shift in round steps, Cmd/Ctrl slowly), the circle then touching the first segment anywhere along it. The circle shows with its center and radii before the click, one undo step (`tangentCircle`). A VectorCraft addition: headline numbers unchanged. - 2026-11-18: Common Tangents also takes a point (a path of one anchor) and a convex closed path: the lines from the point that touch the path, and the line from the point to the path's center if asked; a point on the outline gets the one tangent there, and a point inside gets none, with a message (#7846). 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. diff --git a/apps/vectorcraft/src/host_services.rs b/apps/vectorcraft/src/host_services.rs index 1ce124c1dd..3efdb9f93f 100644 --- a/apps/vectorcraft/src/host_services.rs +++ b/apps/vectorcraft/src/host_services.rs @@ -459,6 +459,8 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services { open_file: Some(Box::new(open_file)), // Edit Original of a raster image with Use System Defaults for Edit Original off (#5236). open_in_photocraft: Some(Box::new(open_in_photocraft)), + check_application: Some(Box::new(|p| check_app(std::path::Path::new(p)))), + open_in_application: Some(Box::new(open_in_application)), pick_folder: Some(Box::new(move || pick_now(PickRequest::Folder, &p4).into_iter().next())), pick_folder_at: Some(Box::new(move |start: &str| pick_now(PickRequest::FolderAt(start.to_string()), &p7).into_iter().next())), // Sample Color from Screen: the system's color sampler. @@ -507,15 +509,32 @@ fn open_in_photocraft(path: &str) -> Result { explorer_safe(path)?; let home = std::env::var_os(if cfg!(windows) { "USERPROFILE" } else { "HOME" }).map(std::path::PathBuf::from); let Some(app) = find_photocraft(home.as_deref(), std::env::var_os("PATH").as_deref()) else { return Ok(false) }; + launch_application(&app, path) +} + +/// A missing chosen editor falls back; invalid applications and failed launches remain errors. +fn open_in_application(app: &str, path: &str) -> Result { + explorer_safe(path)?; + let app = std::path::Path::new(app); + match std::fs::metadata(app) { + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false), + Err(e) => return Err(format!("cannot inspect {}: {e}", app.display())), + Ok(_) => {} + } + check_app(app)?; + launch_application(app, path) +} + +fn launch_application(app: &std::path::Path, path: &str) -> Result { #[cfg(target_os = "macos")] let mut c = { let mut c = std::process::Command::new("open"); - c.arg("-a").arg(&app).arg(path); + c.arg("-a").arg(app).arg(path); c }; #[cfg(not(target_os = "macos"))] let mut c = { - let mut c = std::process::Command::new(&app); + let mut c = std::process::Command::new(app); c.arg(path); c }; @@ -688,6 +707,17 @@ mod open_with_tests { tempfile::Builder::new().prefix(&format!("vc-open-with-{name}-")).tempdir().unwrap() } + #[test] + fn chosen_editor_only_falls_back_when_missing() { + let dir = scratch("chosen"); + let missing = dir.path().join("Missing.exe"); + assert!(!super::open_in_application(&missing.to_string_lossy(), "image with spaces.png").unwrap()); + let doc = dir.path().join("notes.txt"); + std::fs::write(&doc, "not an application").unwrap(); + assert!(super::open_in_application(&doc.to_string_lossy(), "image.png").is_err()); + assert!(super::open_in_application(&dir.path().to_string_lossy(), "image.png").is_err()); + } + /// #5236: only an application counts as PhotoCraft, never a document, a folder or a missing /// path. #[test] diff --git a/apps/vectorcraft/src/mac_tablet.rs b/apps/vectorcraft/src/mac_tablet.rs index 1d9aabd442..ade798a393 100644 --- a/apps/vectorcraft/src/mac_tablet.rs +++ b/apps/vectorcraft/src/mac_tablet.rs @@ -1,4 +1,5 @@ -//! macOS: a drawing tablet's pen pressure (#852), tilt and barrel rotation (#764). winit 0.30 +//! macOS: a drawing tablet's pen pressure (#852), tilt and barrel rotation (#764), and an airbrush +//! pen's finger wheel. winit 0.30 //! hands a pen to the window there as a mouse, without them, so the app reads them from AppKit //! itself and writes them into the UI's [`StylusFeed`] (`Services::stylus`), which the canvas //! reads, as on X11 ([`crate::tablet`]). @@ -14,8 +15,9 @@ //! (−1..1 on each axis, ±[`TILT_DEGREES`] at the ends) and its `rotation` go into the feed as the //! pen's pose, kept for that move too. AppKit gives a rotation of 0 for a pen that does not read //! one and a tilt of 0 for an upright pen, so one event cannot tell a pen without tilt or rotation -//! from one held upright and unturned. Each reads as none until the pen reports a value other -//! than 0 after it comes near ([`Pen`]). +//! from one held upright and unturned. Its `tangentialPressure` (−1..1, an airbrush pen's finger +//! wheel) goes into the pose as the wheel, 0 for a pen without one as well. Each reads as none +//! until the pen reports a value other than 0 after it comes near ([`Pen`]). //! A mouse event of any other subtype is a mouse's or a trackpad's: the feed is set to `None`. //! - An `NSEventTypeTabletPoint` event carries the same pressure, tilt and rotation without a move. //! - A tablet proximity event (`NSEventTypeTabletProximity`, or a mouse event of that subtype) says @@ -68,6 +70,8 @@ struct RawEvent { tilt: (f64, f64), /// `rotation`, in degrees (the same events as `pressure`). rotation: f32, + /// `tangentialPressure`, −1..1 (the same events as `pressure`). + tangential: f32, /// `pointingDeviceType` (proximity events only). device: usize, /// `isEnteringProximity` (proximity events only). @@ -107,18 +111,42 @@ impl RawEvent { /// and the pen's rotation is taken the same way. [`PenPose`]'s rotation runs clockwise, so the /// angle is negated and brought into 0..360. /// - /// The tilt is left out unless `tilts`, and the rotation unless `turns` ([`Pen`]). - fn pose(&self, tilts: bool, turns: bool) -> PenPose { + /// AppKit's `tangentialPressure` is −1.0..1.0, the finger wheel of an airbrush pen on the + /// devices that have one (). + /// It becomes [`PenPose`]'s wheel of 0..1, −1.0 at 0 and 1.0 at 1; a value past either end is + /// clamped. + /// + /// The tilt is left out unless `read.tilts`, the rotation unless `read.turns`, and the wheel + /// unless `read.wheels` ([`Pen`]). + fn pose(&self, read: Reads) -> PenPose { let degrees = |v: f64| (v.clamp(-1.0, 1.0) * TILT_DEGREES) as f32; // `0.0 - r` rather than `-r`: a rotation of 0 gives 0, not −0. - let rotation = turns.then(|| (0.0 - self.rotation).rem_euclid(360.0)); - PenPose { tilt: tilts.then(|| [degrees(self.tilt.0), degrees(self.tilt.1)]), rotation } + let rotation = read.turns.then(|| (0.0 - self.rotation).rem_euclid(360.0)); + let wheel = read.wheels.then(|| (self.tangential.clamp(-1.0, 1.0) + 1.0) / 2.0); + PenPose { tilt: read.tilts.then(|| [degrees(self.tilt.0), degrees(self.tilt.1)]), rotation, wheel } } - /// Whether the event reports a tilt other than 0, and a rotation other than 0. - fn reads(&self) -> (bool, bool) { + /// Whether the event reports a tilt other than 0, a rotation other than 0, and a tangential + /// pressure other than 0. + fn reads(&self) -> Reads { let read = |v: f64| v.is_finite() && v != 0.0; - (read(self.tilt.0) || read(self.tilt.1), read(f64::from(self.rotation))) + Reads { tilts: read(self.tilt.0) || read(self.tilt.1), turns: read(f64::from(self.rotation)), wheels: read(f64::from(self.tangential)) } + } +} + +/// Which of a pen's tilt, rotation and finger wheel it has reported. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +struct Reads { + tilts: bool, + turns: bool, + wheels: bool, +} + +impl Reads { + fn add(&mut self, other: Reads) { + self.tilts |= other.tilts; + self.turns |= other.turns; + self.wheels |= other.wheels; } } @@ -148,14 +176,14 @@ impl Update { } } -/// Which end of the pen is near the tablet, and whether it has reported a tilt or a rotation other -/// than 0 since it came near: until it has, its tilt or rotation reads as none, since AppKit gives -/// 0 for a pen without one and for one held upright or unturned. +/// Which end of the pen is near the tablet, and whether it has reported a tilt, a rotation or a +/// tangential pressure other than 0 since it came near: until it has, that value reads as none, +/// since AppKit gives 0 for a pen without one and for one held upright, unturned or with its +/// wheel half way. #[derive(Clone, Copy, Debug, Default, PartialEq)] struct Pen { eraser: bool, - tilts: bool, - turns: bool, + read: Reads, } impl Pen { @@ -163,16 +191,14 @@ impl Pen { if e.proximity() { // Entering with the tip or the eraser end: it hovers. A puck, or leaving, is a mouse. self.eraser = e.entering && e.device == device::ERASER; - (self.tilts, self.turns) = (false, false); + self.read = Reads::default(); let pen = e.entering && e.device != device::CURSOR; return Update::Set(pen.then_some(PenSample { pressure: 0.0, eraser: self.eraser, ..PenSample::default() })); } if e.point() { - let (tilts, turns) = e.reads(); - self.tilts |= tilts; - self.turns |= turns; + self.read.add(e.reads()); } - let sample = PenSample { pressure: e.pressure, eraser: self.eraser, pose: e.pose(self.tilts, self.turns) }; + let sample = PenSample { pressure: e.pressure, eraser: self.eraser, pose: e.pose(self.read) }; match (e.point(), e.mouse()) { (true, true) => Update::Move(sample), (true, false) => Update::Set(Some(sample)), @@ -246,6 +272,7 @@ mod monitor { let tilt = e.tilt(); raw.tilt = (tilt.x, tilt.y); raw.rotation = e.rotation(); + raw.tangential = e.tangentialPressure(); } if raw.proximity() { raw.device = e.pointingDeviceType().0; @@ -326,26 +353,44 @@ mod tests { let sample = |pressure, pose| PenSample { pressure, eraser: false, pose }; assert_eq!(p.handle(&pen(DRAG, 0.5)), Update::Move(tip(0.5)), "no tilt or rotation reported yet"); let leaning = RawEvent { tilt: (0.5, -0.25), rotation: 30.0, ..pen(DRAG, 0.5) }; - let pose = PenPose { tilt: Some([30.0, -15.0]), rotation: Some(330.0) }; + let pose = PenPose { tilt: Some([30.0, -15.0]), rotation: Some(330.0), wheel: None }; assert_eq!(p.handle(&leaning), Update::Move(sample(0.5, pose))); let past_the_ends = RawEvent { tilt: (-4.0, 1.5), rotation: 270.0, ..pen(event_type::TABLET_POINT, 0.8) }; - let pose = PenPose { tilt: Some([-60.0, 60.0]), rotation: Some(90.0) }; + let pose = PenPose { tilt: Some([-60.0, 60.0]), rotation: Some(90.0), wheel: None }; assert_eq!(p.handle(&past_the_ends), Update::Set(Some(sample(0.8, pose))), "clamped"); - let pose = PenPose { tilt: Some([0.0, 0.0]), rotation: Some(0.0) }; + let pose = PenPose { tilt: Some([0.0, 0.0]), rotation: Some(0.0), wheel: None }; let Update::Move(upright) = p.handle(&pen(DRAG, 0.6)) else { panic!("a pen's drag is a move") }; assert_eq!(upright, sample(0.6, pose), "once reported, 0 is upright and unturned"); assert!(upright.pose.rotation.is_some_and(f32::is_sign_positive), "{upright:?}"); let feed = StylusFeed::default(); p.handle(&RawEvent { tilt: (f64::NAN, 0.0), rotation: -90.0, ..pen(DRAG, 0.3) }).apply(&feed); - assert_eq!(feed.pose(), Some(PenPose { tilt: None, rotation: Some(90.0) }), "a tilt that is not a number is left out"); + assert_eq!(feed.pose(), Some(PenPose { rotation: Some(90.0), ..PenPose::default() }), "a tilt that is not a number is left out"); p.handle(&proximity(1, true)); let tilted = RawEvent { tilt: (0.0, 0.5), ..pen(event_type::TABLET_POINT, 0.8) }; - let pose = PenPose { tilt: Some([0.0, 30.0]), rotation: None }; + let pose = PenPose { tilt: Some([0.0, 30.0]), ..PenPose::default() }; assert_eq!(p.handle(&tilted), Update::Set(Some(sample(0.8, pose))), "no rotation reported since the pen came near"); p.handle(&RawEvent { kind: DRAG, ..Default::default() }).apply(&feed); assert_eq!(feed.pose(), None, "a mouse moved"); } + /// An airbrush pen's finger wheel (AppKit's `tangentialPressure`, −1..1) reaches the feed as + /// 0..1, once the pen has reported a value other than 0 since it came near. + #[test] + fn an_airbrush_wheel_goes_into_the_feed() { + let mut p = Pen::default(); + let wheel = |p: &mut Pen, tangential: f32| match p.handle(&RawEvent { tangential, ..pen(DRAG, 0.5) }) { + Update::Move(s) => s.pose.wheel, + u => panic!("a pen's drag is a move: {u:?}"), + }; + assert_eq!(wheel(&mut p, 0.0), None, "no wheel reported yet"); + assert_eq!(wheel(&mut p, -1.0), Some(0.0)); + assert_eq!(wheel(&mut p, 0.5), Some(0.75)); + assert_eq!(wheel(&mut p, 0.0), Some(0.5), "once reported, 0 is half way"); + assert_eq!(wheel(&mut p, 3.0), Some(1.0), "clamped"); + p.handle(&proximity(1, true)); + assert_eq!(wheel(&mut p, 0.0), None, "not reported since the pen came near"); + } + #[test] fn the_feed_gets_each_moves_pressure_within_0_to_1() { let feed = StylusFeed::default(); diff --git a/apps/vectorcraft/src/tablet.rs b/apps/vectorcraft/src/tablet.rs index ed4087e33e..f9371bd368 100644 --- a/apps/vectorcraft/src/tablet.rs +++ b/apps/vectorcraft/src/tablet.rs @@ -1,4 +1,5 @@ -//! Linux: a drawing tablet's pen pressure, tilt and barrel rotation under X11, XWayland included +//! Linux: a drawing tablet's pen pressure, tilt, barrel rotation and airbrush finger wheel under +//! X11, XWayland included //! (#764). winit 0.30 hands a pen to the window there as a mouse, without any of them, so the app //! reads them from XInput2 itself and writes them into the UI's [`StylusFeed`] //! (`Services::stylus`), which the canvas reads. @@ -14,11 +15,17 @@ //! - "Abs Tilt X" and "Abs Tilt Y" (a pen that has both), in degrees as they are when the range //! fits in ±90, otherwise scaled to ±[`TILT_DEGREES`]; //! - "Abs Rotary Z" (the barrel rotation of an Art Pen), scaled to a turn with the middle of the -//! range at 0°. +//! range at 0°; +//! - "Abs Wheel" (the finger wheel of an airbrush pen), scaled from the valuator's range to 0..1. +//! XWayland also sends an Art Pen's barrel rotation on this valuator +//! (), so under +//! XWayland it reads as the wheel. A tablet pad's wheel is on a device without a pressure axis, +//! which is not read. //! //! Any other pointer device moving sets the feed to `None`. Raw events carry only the valuators //! that changed, so the last value of each axis of each pen is kept; an axis the pen has that no -//! event has carried yet reads 0 (upright, unturned), and an axis it lacks reads nothing. +//! event has carried yet reads 0 (upright, unturned), and an axis it lacks reads nothing. The +//! wheel reads nothing until an event carries it. //! //! The X server lists a pen's eraser end as a device of its own, whose name or XInput type contains //! "eraser" (xf86-input-wacom's "… Pen eraser" of type `ERASER`, xf86-input-libinput's @@ -60,6 +67,7 @@ enum AxisKind { TiltX, TiltY, Rotation, + Wheel, } impl AxisKind { @@ -70,6 +78,7 @@ impl AxisKind { "Abs Tilt X" => Some(Self::TiltX), "Abs Tilt Y" => Some(Self::TiltY), "Abs Rotary Z" => Some(Self::Rotation), + "Abs Wheel" => Some(Self::Wheel), _ => None, } } @@ -81,6 +90,7 @@ impl AxisKind { Self::TiltX => 1, Self::TiltY => 2, Self::Rotation => 3, + Self::Wheel => 4, } } } @@ -95,18 +105,22 @@ struct Axis { } impl Axis { - /// A raw value of this valuator as a pressure of 0..1, a tilt in degrees (−90..90) or a - /// rotation in degrees (−180..180, the middle of the range at 0). A value that is not a number - /// is a mouse's pressure, 1, or a tilt or rotation of 0. + /// A raw value of this valuator as a pressure of 0..1, a tilt in degrees (−90..90), a rotation + /// in degrees (−180..180, the middle of the range at 0) or a wheel of 0..1. A value that is not + /// a number is a mouse's pressure, 1, a tilt or rotation of 0, or a wheel half way. fn map(&self, v: f64) -> f32 { if !v.is_finite() { - return if self.kind == AxisKind::Pressure { 1.0 } else { 0.0 }; + return match self.kind { + AxisKind::Pressure => 1.0, + AxisKind::Wheel => 0.5, + _ => 0.0, + }; } let span = self.max - self.min; let unit = if span.is_finite() && span > 0.0 { (v - self.min) / span } else { v }; let unit = unit.clamp(0.0, 1.0); match self.kind { - AxisKind::Pressure => unit as f32, + AxisKind::Pressure | AxisKind::Wheel => unit as f32, AxisKind::TiltX | AxisKind::TiltY if self.min >= -90.0 && self.max <= 90.0 && span > 0.0 => v.clamp(-90.0, 90.0) as f32, AxisKind::TiltX | AxisKind::TiltY => ((unit * 2.0 - 1.0) * TILT_DEGREES) as f32, AxisKind::Rotation => ((unit - 0.5) * 360.0) as f32, @@ -173,7 +187,7 @@ enum Update { #[derive(Debug, Default)] struct Pens { devices: HashMap, - last: HashMap; 4]>, + last: HashMap; 5]>, } impl Pens { @@ -200,10 +214,12 @@ impl Pens { } } } - // An axis the pen has reads 0 until an event carries it; one it lacks reads nothing. + // An axis the pen has reads 0 until an event carries it; one it lacks reads nothing. The + // wheel reads nothing until an event carries it: XWayland lists the axis for every pen. let value = |kind: AxisKind| device.axis(kind).map(|_| last.get(kind.slot()).copied().flatten().unwrap_or(0.0)); let tilt = value(AxisKind::TiltX).zip(value(AxisKind::TiltY)).map(|(x, y)| [x, y]); - let pose = PenPose { tilt, rotation: value(AxisKind::Rotation) }; + let wheel = device.axis(AxisKind::Wheel).and_then(|_| last.get(AxisKind::Wheel.slot()).copied().flatten()); + let pose = PenPose { tilt, rotation: value(AxisKind::Rotation), wheel }; Update::Set(Some(PenSample { pressure: value(AxisKind::Pressure).unwrap_or(0.0), eraser: device.eraser, pose })) } @@ -430,7 +446,7 @@ mod tests { let mut pens = Pens::default(); pens.set_devices([pen(9), Device::new(10, "Wacom Intuos Pro M Pen eraser", Some("ERASER"), pen_valuators()), mouse(12)]); let feed = StylusFeed::default(); - let pose = PenPose { tilt: Some([0.0, 0.0]), rotation: Some(0.0) }; + let pose = PenPose { tilt: Some([0.0, 0.0]), rotation: Some(0.0), wheel: None }; pens.raw_event(&feed, 9, &[0b100], &[32767.5]); assert_eq!(pens.handle(9, []), Update::Set(Some(PenSample { pressure: 0.5, eraser: false, pose }))); assert_eq!(feed.eraser(), Some(false)); @@ -479,10 +495,36 @@ mod tests { // A pen whose tilt and rotation no event has carried yet is upright and unturned. let mut fresh = Pens::default(); fresh.set_devices([pen(9)]); - let upright = PenPose { tilt: Some([0.0, 0.0]), rotation: Some(0.0) }; + let upright = PenPose { tilt: Some([0.0, 0.0]), rotation: Some(0.0), wheel: None }; assert_eq!(fresh.handle(9, [(2, 0.0)]), Update::Set(Some(PenSample { pressure: 0.0, eraser: false, pose: upright }))); } + /// An airbrush pen's "Abs Wheel" valuator goes into the feed as 0..1 of its range, once an + /// event carries it; a pen that lists it but has not moved it reads no wheel, and a device + /// without a pressure axis (a tablet pad's wheel) is not a pen. + #[test] + fn an_airbrush_wheel_goes_into_the_feed() { + let mut valuators = pen_valuators(); + valuators.push((6, "Abs Wheel".to_string(), 0.0, 1023.0)); + let airbrush = Device::new(9, "Wacom Intuos Pro M Pen stylus", Some("STYLUS"), valuators); + let pad = Device::new(13, "Wacom Intuos Pro M Pad pad", Some("PAD"), [(6, "Abs Wheel".to_string(), 0.0, 71.0)]); + let mut pens = Pens::default(); + pens.set_devices([airbrush, pad, pen(10)]); + let feed = StylusFeed::default(); + pens.raw_event(&feed, 9, &[0b100], &[32767.5]); + assert_eq!(feed.pose().and_then(|q| q.wheel), None, "no event has carried the wheel yet"); + pens.raw_event(&feed, 9, &[0b100_0000], &[255.75]); + assert_eq!(feed.pose().and_then(|q| q.wheel), Some(0.25)); + pens.raw_event(&feed, 9, &[0b100_0000], &[5000.0]); + assert_eq!(feed.pose().and_then(|q| q.wheel), Some(1.0), "clamped to the range"); + pens.raw_event(&feed, 9, &[0b100], &[100.0]); + assert_eq!(feed.pose().and_then(|q| q.wheel), Some(1.0), "kept while other valuators move"); + pens.raw_event(&feed, 13, &[0b100_0000], &[30.0]); + assert_eq!((feed.held(), feed.pose()), (None, None), "the pad is not a pen"); + pens.raw_event(&feed, 10, &[0b100_0000], &[512.0]); + assert_eq!(feed.pose().and_then(|q| q.wheel), None, "a pen without the valuator"); + } + /// A device listed again unchanged keeps its last tilt and rotation; another device listed /// under the same id starts upright and unturned. #[test] @@ -495,7 +537,7 @@ mod tests { assert_eq!(pose.tilt, Some([-30.0, 45.0])); let other = Device::new(9, "HUION Kamvas Pen Pen (0x1)", Some("STYLUS"), pen_valuators()); pens.set_devices([other]); - let upright = PenPose { tilt: Some([0.0, 0.0]), rotation: Some(0.0) }; + let upright = PenPose { tilt: Some([0.0, 0.0]), rotation: Some(0.0), wheel: None }; assert_eq!(pens.handle(9, [(2, 0.0)]), Update::Set(Some(PenSample { pressure: 0.0, eraser: false, pose: upright }))); } diff --git a/apps/vectorcraft/src/windows_stylus.rs b/apps/vectorcraft/src/windows_stylus.rs index 5e996c4bdd..e1ea35104d 100644 --- a/apps/vectorcraft/src/windows_stylus.rs +++ b/apps/vectorcraft/src/windows_stylus.rs @@ -133,12 +133,13 @@ fn pen_sample(pressure: u32, pen_mask: u32, pen_flags: u32, in_contact: bool, po /// How a pen whose `POINTER_PEN_INFO` holds `pen_mask`, `tilt_x`, `tilt_y` and `rotation` is /// held: the tilt when the pen reports it along either axis (0 along an axis it doesn't), the -/// rotation when it reports one, each kept within [`PenPose`]'s ranges. +/// rotation when it reports one, each kept within [`PenPose`]'s ranges. `POINTER_PEN_INFO` has no +/// field for an airbrush pen's finger wheel, so the pose has none. fn pen_pose(pen_mask: u32, tilt_x: i32, tilt_y: i32, rotation: u32) -> PenPose { let along = |mask: u32, t: i32| if pen_mask & mask != 0 { t as f32 } else { 0.0 }; let tilt = (pen_mask & (PEN_MASK_TILT_X | PEN_MASK_TILT_Y) != 0).then(|| [along(PEN_MASK_TILT_X, tilt_x), along(PEN_MASK_TILT_Y, tilt_y)]); let rotation = (pen_mask & PEN_MASK_ROTATION != 0).then_some(rotation as f32); - PenPose { tilt, rotation }.sanitized() + PenPose { tilt, rotation, wheel: None }.sanitized() } /// Whether a mouse message with this extra information (`GetMessageExtraInfo`) comes from a mouse, @@ -426,12 +427,12 @@ mod tests { #[test] fn a_pens_tilt_and_rotation_come_where_it_reports_them() { let all = PEN_MASK_TILT_X | PEN_MASK_TILT_Y | PEN_MASK_ROTATION; - assert_eq!(pen_pose(all, 30, -45, 90), PenPose { tilt: Some([30.0, -45.0]), rotation: Some(90.0) }); + assert_eq!(pen_pose(all, 30, -45, 90), PenPose { tilt: Some([30.0, -45.0]), rotation: Some(90.0), wheel: None }); assert_eq!(pen_pose(PEN_MASK_PRESSURE, 30, -45, 90), PenPose::default(), "a pen that reports neither"); - assert_eq!(pen_pose(PEN_MASK_TILT_X, 30, -45, 90), PenPose { tilt: Some([30.0, 0.0]), rotation: None }, "one axis"); - assert_eq!(pen_pose(PEN_MASK_ROTATION, 0, 0, 359), PenPose { tilt: None, rotation: Some(359.0) }, "a 6D Art Pen's barrel"); + assert_eq!(pen_pose(PEN_MASK_TILT_X, 30, -45, 90), PenPose { tilt: Some([30.0, 0.0]), ..PenPose::default() }, "one axis"); + assert_eq!(pen_pose(PEN_MASK_ROTATION, 0, 0, 359), PenPose { rotation: Some(359.0), ..PenPose::default() }, "a 6D Art Pen's barrel"); let wild = pen_pose(all, 400, i32::MIN, 720); - assert_eq!(wild, PenPose { tilt: Some([90.0, -90.0]), rotation: Some(0.0) }, "kept within the ranges"); + assert_eq!(wild, PenPose { tilt: Some([90.0, -90.0]), rotation: Some(0.0), wheel: None }, "kept within the ranges"); let pose = pen_pose(all, 10, 20, 180); assert_eq!(pen_sample(512, PEN_MASK_PRESSURE | all, 0, true, pose).pose, pose); } diff --git a/assets/icons/dc-curvature-circle.svg b/assets/icons/dc-curvature-circle.svg new file mode 100644 index 0000000000..4abaefe063 --- /dev/null +++ b/assets/icons/dc-curvature-circle.svg @@ -0,0 +1 @@ + diff --git a/crates/brush/src/lib.rs b/crates/brush/src/lib.rs index c5354d75cd..d3dd3b6b38 100644 --- a/crates/brush/src/lib.rs +++ b/crates/brush/src/lib.rs @@ -160,7 +160,7 @@ impl Calligraphic { pub fn uses_pressure(&self) -> bool { self.modes().contains(&Variation::Pressure) } - /// Does the pen (its pressure, tilt, bearing or rotation) change the nib? + /// Does the pen (its pressure, tilt, bearing, rotation or wheel) change the nib? pub fn uses_pen(&self) -> bool { self.modes().iter().any(|m| m.follows_pen()) } @@ -202,11 +202,25 @@ pub enum Variation { /// The value plus the variation times the pen barrel's rotation over 180°, counter-clockwise /// from where the pen reports 0° round to ±180°. Rotation, + /// From the value less the variation with an airbrush pen's finger wheel at one end of its + /// travel to the value plus the variation at the other (the value itself half way). + StylusWheel, } impl Variation { - pub const ALL: [Variation; 6] = + pub const ALL: [Variation; 7] = + [Variation::Fixed, Variation::Random, Variation::Pressure, Variation::Tilt, Variation::Bearing, Variation::Rotation, Variation::StylusWheel]; + /// The modes Brush Options offers for a value other than a size (a Calligraphic brush's Angle + /// and Roundness, a Scatter brush's Spacing, Scatter and Rotation): all but + /// [`Variation::StylusWheel`], which drives a Calligraphic or Scatter brush's Size and an Art + /// brush's Width. + pub const OTHER: [Variation; 6] = [Variation::Fixed, Variation::Random, Variation::Pressure, Variation::Tilt, Variation::Bearing, Variation::Rotation]; + /// The modes Brush Options offers for a size (`true`: [`Self::ALL`]) or another value + /// ([`Self::OTHER`]). + pub fn offered(size: bool) -> &'static [Variation] { + if size { &Self::ALL } else { &Self::OTHER } + } /// The name brush definitions use. pub fn id(self) -> &'static str { match self { @@ -216,6 +230,7 @@ impl Variation { Variation::Tilt => "tilt", Variation::Bearing => "bearing", Variation::Rotation => "rotation", + Variation::StylusWheel => "stylusWheel", } } pub fn label(self) -> &'static str { @@ -226,15 +241,16 @@ impl Variation { Variation::Tilt => "Tilt", Variation::Bearing => "Bearing", Variation::Rotation => "Rotation", + Variation::StylusWheel => "Stylus Wheel", } } pub fn parse(id: &str) -> Option { Self::ALL.into_iter().find(|v| v.id() == id) } /// Does the value follow something the pen records along a stroke (Pressure, Tilt, Bearing, - /// Rotation)? + /// Rotation, Stylus Wheel)? pub fn follows_pen(self) -> bool { - matches!(self, Variation::Pressure | Variation::Tilt | Variation::Bearing | Variation::Rotation) + matches!(self, Variation::Pressure | Variation::Tilt | Variation::Bearing | Variation::Rotation | Variation::StylusWheel) } } @@ -251,12 +267,14 @@ pub(crate) struct PenAt { bearing: f64, /// ½ plus the counter-clockwise barrel rotation over 360°. rotation: f64, + /// Where the airbrush finger wheel was set, 0 at one end of its travel to 1 at the other. + wheel: f64, } impl PenAt { /// Every input at `c`. pub(crate) fn uniform(c: f64) -> Self { - Self { pressure: c, tilt: c, bearing: c, rotation: c } + Self { pressure: c, tilt: c, bearing: c, rotation: c, wheel: c } } /// What `stroke` recorded at `f` (the fraction of its path's length). pub(crate) fn of(stroke: &StrokeLayer, f: f64) -> Self { @@ -267,6 +285,7 @@ impl PenAt { tilt: 1.0 - stroke.tilt.as_ref().map_or(mid, |p| p.at(f)), bearing: turn(stroke.bearing.as_ref()), rotation: turn(stroke.rotation.as_ref()), + wheel: stroke.wheel.as_ref().map_or(mid, |p| p.at(f)), } } /// The 0..1 a value on `mode` takes, or `None` for a mode that doesn't follow the pen. @@ -277,6 +296,7 @@ impl PenAt { Variation::Tilt => self.tilt, Variation::Bearing => self.bearing, Variation::Rotation => self.rotation, + Variation::StylusWheel => self.wheel, }; Some(if c.is_finite() { c.clamp(0.0, 1.0) } else { 0.5 }) } @@ -307,9 +327,10 @@ pub struct Scatter { /// 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, - /// Bearing and Rotation the first at −180° and the second at 180° (half way at 0°). `None` - /// (brushes saved before there were modes): Random where the two differ, else Fixed (see - /// [`Scatter::modes`]). + /// Bearing and Rotation the first at −180° and the second at 180° (half way at 0°), and Stylus + /// Wheel (the size's only) the first at one end of an airbrush pen's finger wheel and the + /// second at the other. `None` (brushes saved before there were modes): Random where the two + /// differ, else Fixed (see [`Scatter::modes`]). #[serde(skip_serializing_if = "Option::is_none")] pub modes: Option<[Variation; 4]>, } @@ -384,11 +405,12 @@ pub struct ArtBrush { /// How the width varies along a stroke: `None` (Fixed) always `width`; a mode that follows the /// pen goes from `width` to [`Self::width_max`] over the ranges [`Variation`] gives: Pressure /// from the lightest pressure to the heaviest, Tilt from the pen lying flat to upright, Bearing - /// and Rotation from −180° to 180° (half way at 0°). + /// and Rotation from −180° to 180° (half way at 0°), Stylus Wheel from one end of an airbrush + /// pen's finger wheel to the other. #[serde(skip_serializing_if = "Option::is_none")] pub width_mode: Option, - /// The second width (%) of a mode that follows the pen: at the heaviest pressure, upright, or - /// at 180° (`width` without one). + /// The second width (%) of a mode that follows the pen: at the heaviest pressure, upright, at + /// 180° or at the wheel's far end (`width` without one). #[serde(skip_serializing_if = "Option::is_none")] pub width_max: Option, pub flip_along: bool, @@ -732,7 +754,7 @@ impl Brush { } BrushKind::Art(a) => { a.width = within(a.width, ArtBrush::WIDTH_RANGE, 100.0); - // The width follows the pen (its pressure, tilt, bearing or rotation) or stays fixed. + // The width follows the pen (its pressure, tilt, bearing, rotation or wheel) or stays fixed. if !a.width_mode.is_some_and(Variation::follows_pen) { a.width_mode = None; } diff --git a/crates/brush/src/tests.rs b/crates/brush/src/tests.rs index f4f2d1ae20..c7e4acc927 100644 --- a/crates/brush/src/tests.rs +++ b/crates/brush/src/tests.rs @@ -1545,6 +1545,64 @@ fn pressure_varies_angle_and_roundness() { assert!(near(h, expected, 0.05), "{h} vs {expected}"); } +/// A stroke that recorded an airbrush pen's finger wheel going from `from` to `to` along it. +fn wheeled(from: f64, to: f64) -> StrokeLayer { + StrokeLayer { wheel: Some(vectorcraft_doc::PressureProfile { points: vec![(0.0, from), (1.0, to)] }), ..stroke(1.0) } +} + +/// Stylus Wheel: a Calligraphic brush's size goes from size − variation at one end of the finger +/// wheel to size + variation at the other, a Scatter brush's size from its first value to its +/// second, and an Art brush's width from Width to the second width. Each reads only the wheel: the +/// pressure, tilt, bearing or rotation recorded instead leaves the value half way. +#[test] +fn the_stylus_wheel_varies_sizes_and_widths() { + let doc = Document::new(1.0, 1.0); + let bp = line(0.0, 0.0, 100.0, 0.0); + let c = Calligraphic { + size: 6.0, + variation: [0.0, 0.0, 4.0], + modes: Some([Variation::Fixed, Variation::Fixed, Variation::StylusWheel]), + ..Default::default() + }; + let nib = Brush { name: "w".into(), kind: BrushKind::Calligraphic(c) }; + let out = stroke_pieces(&doc, &nib, &bp, &wheeled(0.0, 1.0)); + // Round nib: 2 pt across at the start, 10 pt at the end, 6 pt half way. + assert!(near(half_width(&out, 0.5, 1.5), 1.0, 0.1), "{}", half_width(&out, 0.5, 1.5)); + assert!(near(half_width(&out, 98.5, 99.5), 5.0, 0.1), "{}", half_width(&out, 98.5, 99.5)); + assert!(near(half_width(&out, 49.5, 50.5), 3.0, 0.1), "{}", half_width(&out, 49.5, 50.5)); + let others = [ + pressed(vec![(0.0, 0.0), (1.0, 1.0)]), + StrokeLayer { tilt: Some(vectorcraft_doc::PressureProfile { points: vec![(0.0, 0.0), (1.0, 1.0)] }), ..stroke(1.0) }, + posed(None, Some(90.0), Some(-90.0)), + ]; + for st in &others { + let h = bounds(&stroke_pieces(&doc, &nib, &bp, st)).height(); + assert!(near(h, 6.0, 0.05), "{st:?}: {h}"); + } + // Scatter size 50 % to 300 % of 4 pt art: 2 pt at one end of the wheel, 12 pt at the other. + let spray = sized_scatter(50.0, 300.0, Variation::StylusWheel); + let h: Vec = + stroke_pieces(&doc, &spray, &line(0.0, 0.0, 400.0, 0.0), &wheeled(1.0, 0.0)).iter().map(|n| n.geometric_bounds().unwrap().height()).collect(); + assert!(near(h[0], 12.0, 0.2) && h[h.len() - 1] < 3.0, "{h:?}"); + // Art width 50 % to 300 % of 4 pt art. + let mut ribbon = art_brush(rect_art(10.0, 4.0), ArtScale::Stretch); + if let BrushKind::Art(a) = &mut ribbon.kind { + (a.width, a.width_mode, a.width_max) = (50.0, Some(Variation::StylusWheel), Some(300.0)); + } + let out = stroke_pieces(&doc, &ribbon, &bp, &wheeled(1.0, 0.0)); + assert!(near(half_width(&out, 0.0, 1.0), 6.0, 0.1), "{}", half_width(&out, 0.0, 1.0)); + assert!(near(half_width(&out, 99.0, 100.0), 1.0, 0.1), "{}", half_width(&out, 99.0, 100.0)); + for st in &others { + let h = bounds(&stroke_pieces(&doc, &ribbon, &bp, st)).height(); + assert!(near(h, 7.0, 1e-6), "{st:?}: {h}"); + } + // A definition keeps the mode by name. + let lib = parse_library(&serde_json::json!([ + {"name": "a", "type": "art", "art": rect_art(10.0, 4.0), "width_mode": "stylusWheel", "width_max": 300.0}, + ])); + assert!(matches!(&lib[0].kind, BrushKind::Art(a) if a.width_mode == Some(Variation::StylusWheel))); +} + /// A stroke that recorded the pen's tilt (`tilt`: 0 upright to 1 flat), bearing and barrel /// rotation (degrees counter-clockwise), each the same all along it where given. fn posed(tilt: Option, bearing: Option, rotation: Option) -> StrokeLayer { @@ -1611,7 +1669,7 @@ fn bearing_and_rotation_turn_the_nib() { #[test] fn pen_modes_without_a_recording_draw_the_value_itself() { let horizontal = line(0.0, 0.0, 100.0, 0.0); - for mode in [Variation::Tilt, Variation::Bearing, Variation::Rotation] { + for mode in [Variation::Tilt, Variation::Bearing, Variation::Rotation, Variation::StylusWheel] { let c = Calligraphic { angle: 90.0, roundness: 50.0, size: 10.0, variation: [90.0, 50.0, 6.0], modes: Some([mode; 3]) }; let b = Brush { name: "n".into(), kind: BrushKind::Calligraphic(c) }; let h = bounds(&stroke_pieces(&Document::new(1.0, 1.0), &b, &horizontal, &stroke(1.0))).height(); @@ -1658,7 +1716,7 @@ fn a_mouse_stroke_draws_pen_modes_as_pressure_did() { }; let (calli_before, scatter_before) = (calli(Variation::Pressure), scattered(Variation::Pressure)); assert!(!calli_before.is_empty() && !scatter_before.is_empty()); - for mode in [Variation::Tilt, Variation::Bearing, Variation::Rotation] { + for mode in [Variation::Tilt, Variation::Bearing, Variation::Rotation, Variation::StylusWheel] { assert_eq!(calli(mode), calli_before, "{mode:?}"); assert_eq!(scattered(mode), scatter_before, "{mode:?}"); } @@ -1726,8 +1784,12 @@ fn brushes_without_modes_vary_randomly_as_before() { stroke_pieces(&Document::new(1.0, 1.0), &old, &bp, &pressed(vec![(0.0, 0.0), (1.0, 1.0)])) ); // Modes are saved by name. - assert_eq!(serde_json::to_value(Variation::ALL).unwrap(), serde_json::json!(["fixed", "random", "pressure", "tilt", "bearing", "rotation"])); - assert!(Variation::ALL.iter().all(|v| Variation::parse(v.id()) == Some(*v))); + assert_eq!( + serde_json::to_value(Variation::ALL).unwrap(), + serde_json::json!(["fixed", "random", "pressure", "tilt", "bearing", "rotation", "stylusWheel"]) + ); + assert!(Variation::ALL.iter().all(|v| Variation::parse(v.id()) == Some(*v) && serde_json::to_value(v).unwrap() == v.id())); + assert!(!Variation::offered(false).contains(&Variation::StylusWheel) && Variation::offered(true).contains(&Variation::StylusWheel)); } /// Junk definitions and pressure never panic and never draw non-finite art. diff --git a/crates/cad/src/hpgl/write.rs b/crates/cad/src/hpgl/write.rs index bb397d7eaa..06ddc09b93 100644 --- a/crates/cad/src/hpgl/write.rs +++ b/crates/cad/src/hpgl/write.rs @@ -198,14 +198,24 @@ pub fn export(doc: &Document, opts: &HpglOptions) -> Result Ok(export_regions(doc, opts, &[opts.region])?.pop().unwrap_or_default()) } +/// An error unless a plot can cover `region`: its corners are finite and it has a width and a +/// height (either corner may come first). +pub fn check_region(region: Rect) -> Result<(), String> { + 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()); + } + Ok(()) +} + /// Write the visible art of `doc` over each of `regions` as an HP-GL plot, one per region, as /// [`export`] does with `opts.region`. The plots share one pen numbering, so a color is the same /// pen in each, and one point budget. pub fn export_regions(doc: &Document, opts: &HpglOptions, regions: &[Rect]) -> 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()); + for r in regions { + check_region(*r)?; } + let regions: Vec = regions.iter().map(|r| r.abs()).collect(); if !TOLERANCE_RANGE.contains(&opts.tolerance) { return Err("the curve tolerance must be from 0.01 to 10 points".into()); } diff --git a/crates/color/src/cms.rs b/crates/color/src/cms.rs index 96640b5508..a3c35db8ce 100644 --- a/crates/color/src/cms.rs +++ b/crates/color/src/cms.rs @@ -185,6 +185,15 @@ pub struct ColorSettings { /// The color management policy for CMYK profiles. Settings saved without one take the default. #[serde(default)] pub cmyk_policy: Policy, + /// Profile Mismatches: Ask When Opening. Off by default, as in settings saved without it. + #[serde(default)] + pub ask_mismatch_open: bool, + /// Profile Mismatches: Ask When Pasting. + #[serde(default)] + pub ask_mismatch_paste: bool, + /// Missing Profiles: Ask When Opening. + #[serde(default)] + pub ask_missing_open: bool, } impl Default for ColorSettings { @@ -196,6 +205,9 @@ impl Default for ColorSettings { bpc: true, rgb_policy: Policy::default(), cmyk_policy: Policy::default(), + ask_mismatch_open: false, + ask_mismatch_paste: false, + ask_missing_open: false, } } } @@ -589,10 +601,11 @@ impl Cms { /// An RGB or CMYK colour of this context's space as the colour of the same model in `dest`'s /// space that looks the same, converted with `intent` (Edit → Color Settings › Convert to - /// Working Space). RGB converts directly from profile to profile, and CMYK between two loaded - /// profiles through ProPhoto RGB ([`IccProfile::to_same_model_of`]), both with this context's - /// black-point compensation; CMYK goes through Lab when either space is built in. Grey and - /// Lab colours stay as they are. + /// Working Space). RGB converts directly from profile to profile, with this context's + /// black-point compensation. CMYK converts between two loaded profiles through ProPhoto RGB + /// ([`IccProfile::to_same_model_of`]), and through Lab when either space is built in: the Lab it + /// displays as ([`Self::cmyk_display_lab`]), or for Absolute Colorimetric its absolute Lab. Grey + /// and Lab colours stay as they are. pub fn convert_into(&self, dest: &Cms, c: &Color, intent: Intent) -> Color { match *c { Color::Rgb { r, g, b } => { @@ -612,9 +625,16 @@ impl Cms { (CmykSpace::Icc(s), CmykSpace::Icc(d)) => s.to_same_model_of(d, &inks, intent, self.settings.bpc), _ => None, }; + // Absolute colorimetry starts from the inks' absolute Lab, paper color included and + // without black-point compensation; the other intents from the Lab they display as. + let source_lab = || match (&self.cmyk, intent) { + (CmykSpace::Generic(g), Intent::AbsoluteColorimetric) => g.to_lab_abs(inks), + (_, Intent::AbsoluteColorimetric) => lab::srgb_to_lab(self.cmyk_to_srgb(inks, true)), + _ => self.cmyk_display_lab(inks), + }; let [c, m, y, k] = match direct.as_deref() { Some(&[c, m, y, k]) => [c, m, y, k], - _ => dest.lab_to_cmyk(self.cmyk_to_lab(inks), intent), + _ => dest.lab_to_cmyk(source_lab(), intent), }; Color::Cmyk { c, m, y, k } } diff --git a/crates/color/src/cms/tests.rs b/crates/color/src/cms/tests.rs index 95e465b623..836ff9fdb6 100644 --- a/crates/color/src/cms/tests.rs +++ b/crates/color/src/cms/tests.rs @@ -459,6 +459,23 @@ fn policies_parse_and_default_in_saved_settings() { assert_eq!((saved["rgbPolicy"].as_str(), saved["cmykPolicy"].as_str()), (Some("preserveEmbedded"), Some("preserveNumbers"))); } +/// The three Ask boxes are off by default and in settings saved before they existed, and save +/// under their own keys. +#[test] +fn ask_boxes_default_off_and_save() { + let old: ColorSettings = + serde_json::from_str(r#"{"rgb": "sRGB IEC61966-2.1", "cmyk": "Device CMYK (uncalibrated)", "intent": "perceptual", "bpc": false}"#).unwrap(); + assert!(!old.ask_mismatch_open && !old.ask_mismatch_paste && !old.ask_missing_open); + let st = ColorSettings::default(); + assert!(!st.ask_mismatch_open && !st.ask_mismatch_paste && !st.ask_missing_open); + let saved = serde_json::to_value(ColorSettings { ask_mismatch_paste: true, ..Default::default() }).unwrap(); + assert_eq!(saved["askMismatchOpen"], false); + assert_eq!(saved["askMismatchPaste"], true); + assert_eq!(saved["askMissingOpen"], false); + let back: ColorSettings = serde_json::from_value(saved).unwrap(); + assert!(back.ask_mismatch_paste); +} + /// Convert to Working Space keeps a color's appearance: an RGB color of a wide space converts into /// sRGB, and a CMYK color of one CMYK space into another, with numbers that look the same. Grey and /// Lab colors stay as they are. @@ -478,3 +495,48 @@ fn convert_into_keeps_the_appearance() { assert_eq!(wide.convert_into(&working, &c, Intent::RelativeColorimetric), c); } } + +/// With black-point compensation on, Generic CMYK displays its press black as black, so dark inks +/// converted out of it keep that appearance: into Device CMYK, and into another document whose +/// CMYK space is also Generic CMYK. +#[test] +fn convert_into_keeps_compensated_dark_inks() { + let generic = cms(); + let device = Cms::new(&ColorSettings { cmyk: DEVICE_CMYK.into(), ..Default::default() }).unwrap(); + let other_generic = Cms::new(&ColorSettings { rgb: WIDE_GAMUT_RGB.into(), ..Default::default() }).unwrap(); + for ink in [ + Color::Cmyk { c: 0.6, m: 0.5, y: 0.5, k: 0.9 }, + Color::Cmyk { c: 0.0, m: 0.0, y: 0.0, k: 1.0 }, + Color::Cmyk { c: 0.3, m: 0.2, y: 0.2, k: 0.75 }, + ] { + for dest in [&device, &other_generic] { + let moved = generic.convert_into(dest, &ink, Intent::RelativeColorimetric); + assert!(matches!(moved, Color::Cmyk { .. }), "{ink:?} → {moved:?}"); + let d = delta_e2000(generic.lab(&ink), dest.lab(&moved)); + assert!(d < 2.0, "{ink:?} → {moved:?}: ΔE {d}"); + } + } +} + +/// Absolute Colorimetric converts CMYK out of Generic CMYK from the inks' absolute Lab (paper color +/// included, no black-point compensation): into another document whose CMYK space is also Generic +/// CMYK, the paper, dark inks and mid tones keep their absolute appearance. +#[test] +fn absolute_cmyk_conversion_keeps_the_absolute_appearance() { + let generic = cms(); + let other_generic = Cms::new(&ColorSettings { rgb: WIDE_GAMUT_RGB.into(), ..Default::default() }).unwrap(); + let absolute = |c: &Cms, ink: &Color| match (&c.cmyk, ink) { + (CmykSpace::Generic(g), Color::Cmyk { c, m, y, k }) => g.to_lab_abs([*c, *m, *y, *k]), + _ => panic!("Generic CMYK inks expected, not {ink:?}"), + }; + for ink in [ + Color::Cmyk { c: 0.0, m: 0.0, y: 0.0, k: 0.0 }, + Color::Cmyk { c: 0.6, m: 0.5, y: 0.5, k: 0.9 }, + Color::Cmyk { c: 0.3, m: 0.2, y: 0.2, k: 0.75 }, + Color::Cmyk { c: 0.4, m: 0.1, y: 0.6, k: 0.1 }, + ] { + let moved = generic.convert_into(&other_generic, &ink, Intent::AbsoluteColorimetric); + let d = delta_e2000(absolute(&generic, &ink), absolute(&other_generic, &moved)); + assert!(d < 2.0, "{ink:?} → {moved:?}: ΔE {d}"); + } +} diff --git a/crates/color/src/harmony.rs b/crates/color/src/harmony.rs index 2cca6e264d..87e1c54548 100644 --- a/crates/color/src/harmony.rs +++ b/crates/color/src/harmony.rs @@ -176,18 +176,33 @@ impl Harmony { /// The rule's colours in the base colour's model, the base colour itself first. pub fn apply(self, base: Color) -> Vec { - let [h, s, v] = base.to_hsb(); - std::iter::once(base) - .chain(self.tones()[1..].iter().map(|tone| { + let rest = self.apply_hsb(base.to_hsb()).into_iter().skip(1); + std::iter::once(base).chain(rest.map(|[h, s, v]| keep_model(base, Color::from_hsb(h, s, v)))).collect() + } + + /// The rule's colours as HSB from base HSB `hsb`, the base first: hue in degrees from 0 to 360, + /// saturation and brightness from 0 to 1. A gray base keeps its hue, so the colours keep their + /// places around a hue wheel. + pub fn apply_hsb(self, [h, s, v]: [f32; 3]) -> Vec<[f32; 3]> { + self.tones() + .iter() + .map(|tone| { let b = match tone.bright { Bright::Times(f) => v * f, Bright::Contrast => contrast(v), }; - keep_model(base, Color::from_hsb(h + tone.turn, (s * tone.sat).clamp(0.0, 1.0), b.clamp(0.0, 1.0))) - })) + [(h + tone.turn).rem_euclid(360.0), (s * tone.sat).clamp(0.0, 1.0), b.clamp(0.0, 1.0)] + }) .collect() } + /// Whether every colour of the rule has a hue of its own (Triad, but not Triad 2 or + /// Monochromatic), so that each can sit on a hue ring apart from the others. + pub fn hues_differ(self) -> bool { + let turns: Vec = self.tones().iter().map(|t| t.turn.rem_euclid(360.0)).collect(); + turns.iter().enumerate().all(|(i, a)| turns[..i].iter().all(|b| a != b)) + } + /// A [`THEME_SIZE`]-colour theme from `base`: the rule's colours, each followed by the lighter or /// darker variations of it that fill the remaining places (the rule's first colours get them /// first). The base colour comes first, every colour in its model. @@ -409,6 +424,34 @@ mod tests { assert_eq!(Harmony::parse("square"), None); } + /// A rule's HSB colours match the colours `apply` gives, and a gray base keeps its hue, so its + /// colours turn around the hue ring from it. + #[test] + fn hsb_colours_match_and_keep_a_grays_hue() { + for h in Harmony::ALL { + let base = Color::rgb8(230, 120, 40); + let hsb = h.apply_hsb(base.to_hsb()); + let colors = h.apply(base); + assert_eq!(hsb.len(), colors.len(), "{}", h.label()); + for (a, c) in hsb.iter().zip(&colors).skip(1) { + assert_eq!(Color::from_hsb(a[0], a[1], a[2]).to_hex(), c.to_hex(), "{}", h.label()); + } + } + let gray = Harmony::Triad.apply_hsb([40.0, 0.0, 0.5]); + assert_eq!(gray.iter().map(|c| c[0]).collect::>(), [40.0, 160.0, 280.0]); + assert_eq!(Harmony::Analogous.apply_hsb([10.0, 1.0, 1.0])[2][0], 340.0, "hues wrap to 0..360"); + } + + /// Fifteen rules give every colour its own hue; the six that repeat a hue are left out. + #[test] + fn rules_whose_colours_all_have_their_own_hue() { + let differ: Vec = Harmony::ALL.into_iter().filter(|h| h.hues_differ()).collect(); + assert_eq!(differ.len(), 15); + for h in [Harmony::Complementary2, Harmony::Monochromatic, Harmony::Shades, Harmony::Triad2, Harmony::Triad3, Harmony::HighContrast2] { + assert!(!h.hues_differ(), "{}", h.label()); + } + } + #[test] fn high_contrast_flips_brightness() { let light = Harmony::HighContrast.apply(Color::rgb(0.9, 0.8, 0.2)); diff --git a/crates/doc/src/appearance.rs b/crates/doc/src/appearance.rs index 737e10eb58..a851320907 100644 --- a/crates/doc/src/appearance.rs +++ b/crates/doc/src/appearance.rs @@ -127,8 +127,8 @@ impl Appearance { pub fn stroke_mut(&mut self) -> Option<&mut StrokeLayer> { self.items.iter_mut().rev().find_map(|i| if let AppearanceItem::Stroke(s) = i { Some(s) } else { None }) } - /// This appearance for other art: the pen pressure, tilt, bearing and rotation its strokes - /// were drawn with stay with them. + /// This appearance for other art: the pen pressure, tilt, bearing, rotation and wheel its + /// strokes were drawn with stay with them. pub fn without_pressure(mut self) -> Self { for it in &mut self.items { if let AppearanceItem::Stroke(s) = it { @@ -136,6 +136,7 @@ impl Appearance { s.tilt = None; s.bearing = None; s.rotation = None; + s.wheel = None; } } self diff --git a/crates/doc/src/appearance/layers.rs b/crates/doc/src/appearance/layers.rs index 5e07dc6cde..1728b7e323 100644 --- a/crates/doc/src/appearance/layers.rs +++ b/crates/doc/src/appearance/layers.rs @@ -113,6 +113,11 @@ pub struct StrokeLayer { /// pressure, it stays with this path. #[serde(default, skip_serializing_if = "Option::is_none")] pub rotation: Option, + /// Where the finger wheel of an airbrush pen was set along the stroke: 0 at one end of its + /// travel to 1 at the other. Brushes with Stylus Wheel variation vary with it. Like the + /// pressure, it stays with this path. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub wheel: Option, } /// How a gradient on a stroke is laid out (the Gradient panel's Stroke buttons). Saved by variant @@ -187,6 +192,7 @@ impl StrokeLayer { tilt: None, bearing: None, rotation: None, + wheel: None, } } /// Weight of the start (`end == false`) or end arrowhead: stroke weight × its scale, at least diff --git a/crates/doc/src/appearance/profile.rs b/crates/doc/src/appearance/profile.rs index 3d89615016..e6f69e6670 100644 --- a/crates/doc/src/appearance/profile.rs +++ b/crates/doc/src/appearance/profile.rs @@ -130,8 +130,9 @@ impl WidthProfile { /// Pen pressure recorded along a stroke (the Paintbrush with a graphics tablet): (position 0..1 /// along the path, pressure 0..1) samples in order, positions measured as a [`WidthProfile`]'s -/// are. The pen's tilt is kept the same way ([`StrokeLayer::tilt`]). Calligraphic and Scatter -/// brushes with Pressure or Tilt variation read them; everything else ignores them. +/// are. The pen's tilt and an airbrush pen's finger wheel are kept the same way +/// ([`StrokeLayer::tilt`], [`StrokeLayer::wheel`]). Brushes with Pressure, Tilt or Stylus Wheel +/// variation read them; everything else ignores them. #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] pub struct PressureProfile { pub points: Vec<(f64, f64)>, diff --git a/crates/doc/src/appearance/tests.rs b/crates/doc/src/appearance/tests.rs index cb5f8fed66..caad4f6edc 100644 --- a/crates/doc/src/appearance/tests.rs +++ b/crates/doc/src/appearance/tests.rs @@ -188,7 +188,7 @@ fn angle_profiles_join_samples_the_shorter_way_round() { #[test] fn strokes_without_pressure_round_trip_unchanged() { let json = serde_json::to_value(StrokeLayer::new(Paint::None, 2.0)).unwrap(); - for key in ["pressure", "tilt", "bearing", "rotation"] { + for key in ["pressure", "tilt", "bearing", "rotation", "wheel"] { assert!(json.get(key).is_none(), "{key}"); } let st: StrokeLayer = serde_json::from_value(json).unwrap(); @@ -199,19 +199,21 @@ fn strokes_without_pressure_round_trip_unchanged() { let mut ap = Appearance::basic(Paint::None, Paint::None, 1.0); ap.stroke_mut().unwrap().pressure = Some(PressureProfile::sample()); assert_eq!(ap.without_pressure().stroke().unwrap().pressure, None); - // The pen's tilt, bearing and rotation load, save and stay behind the same way. + // The pen's tilt, bearing, rotation and wheel load, save and stay behind the same way. let posed = StrokeLayer { tilt: Some(PressureProfile::sample()), bearing: Some(AngleProfile::sample()), rotation: Some(AngleProfile { points: vec![(0.0, -45.0)] }), + wheel: Some(PressureProfile { points: vec![(0.0, 0.25), (1.0, 0.75)] }), ..back }; + assert_eq!(serde_json::to_value(&posed).unwrap()["wheel"], serde_json::json!({"points": [[0.0, 0.25], [1.0, 0.75]]})); let again: StrokeLayer = serde_json::from_value(serde_json::to_value(&posed).unwrap()).unwrap(); assert_eq!(again, posed); let mut ap = Appearance::basic(Paint::None, Paint::None, 1.0); *ap.stroke_mut().unwrap() = posed; let st = ap.without_pressure().stroke().cloned().unwrap(); - assert_eq!((st.pressure, st.tilt, st.bearing, st.rotation), (None, None, None, None)); + assert_eq!((st.pressure, st.tilt, st.bearing, st.rotation, st.wheel), (None, None, None, None, None)); } /// The Lens profile's widths at its middle, a quarter of the way along and past its end. diff --git a/crates/doc/src/blend.rs b/crates/doc/src/blend.rs index f8b62ac815..7c7429acc2 100644 --- a/crates/doc/src/blend.rs +++ b/crates/doc/src/blend.rs @@ -6,7 +6,7 @@ //! tool clicked. //! - **Paint**: colours, gradients (stops resampled to a common set when their counts differ), //! opacity, stroke weight, dashes, miter limit, width profiles and the pen pressure, tilt, -//! bearing and rotation that brushes read interpolate; what can't +//! bearing, rotation and wheel that brushes read interpolate; what can't //! (caps, joins, brushes, fonts, symbols, text content) switches halfway. //! - **Groups** pair their children in stacking order; the children one group has more of grow //! out of the other group's centre. Compound paths stay compound paths. @@ -429,8 +429,8 @@ fn lerp_angle(x: Option<&AngleProfile>, y: Option<&AngleProfile>, t: f64) -> Opt } /// Interpolate a stroke's paint, weight, opacity, miter limit, dashes, arrowhead scale, width -/// profile and the pen pressure, tilt, bearing and rotation its brush reads into `o` (a copy of -/// the nearer stroke, so caps, joins, alignment, arrowheads and brushes switch halfway). +/// profile and the pen pressure, tilt, bearing, rotation and wheel its brush reads into `o` (a +/// copy of the nearer stroke, so caps, joins, alignment, arrowheads and brushes switch halfway). fn lerp_stroke(o: &mut StrokeLayer, x: &StrokeLayer, y: &StrokeLayer, t: f64) { let tf = t as f32; o.paint = lerp_paint(&x.paint, &y.paint, tf); @@ -444,6 +444,7 @@ fn lerp_stroke(o: &mut StrokeLayer, x: &StrokeLayer, y: &StrokeLayer, t: f64) { o.tilt = lerp_pressure(x.tilt.as_ref(), y.tilt.as_ref(), t); o.bearing = lerp_angle(x.bearing.as_ref(), y.bearing.as_ref(), t); o.rotation = lerp_angle(x.rotation.as_ref(), y.rotation.as_ref(), t); + o.wheel = lerp_pressure(x.wheel.as_ref(), y.wheel.as_ref(), t); } /// Interpolate appearance stacks: item by item when their structure matches, else the top fill @@ -755,9 +756,9 @@ fn reorient_dash(d: &mut Dash, o: Orient, lens: &[f64]) { } /// A key's stroke read along its subpaths turned as `o` says (`lens`: their lengths): its width -/// profile (whose sides swap when reversed), pen pressure, tilt, bearing and rotation, its dashes, -/// a gradient along the path or across it (whose sides swap when reversed). Its arrowheads stay as -/// they are. +/// profile (whose sides swap when reversed), pen pressure, tilt, bearing, rotation and wheel, its +/// dashes, a gradient along the path or across it (whose sides swap when reversed). Its arrowheads +/// stay as they are. fn reorient_stroke(s: &mut StrokeLayer, o: Orient, lens: &[f64]) { if o.is_identity() { return; @@ -805,7 +806,7 @@ fn reorient_stroke(s: &mut StrokeLayer, o: Orient, lens: &[f64]) { let out = reoriented(&pts, o, |f| p.at(f), |v| v, |(l, r)| (r, l)); p.points = out.into_iter().map(|(t, (l, r))| (t, l, r)).collect(); } - for p in [&mut s.pressure, &mut s.tilt].into_iter().flatten() { + for p in [&mut s.pressure, &mut s.tilt, &mut s.wheel].into_iter().flatten() { let out = reoriented(&p.points, o, |f| p.at(f), same, same); p.points = out; } @@ -842,8 +843,8 @@ fn reorient_strokes(n: &mut Node, o: Orient) { /// Turn the strokes of path or compound path `n` for Reverse Path Direction, before its subpaths /// flagged in `reversed` are reversed with [`SubPath::reverse`] (a closed one then starts at its -/// last anchor): each stroke's width profile (sides swapped), pen pressure, tilt, bearing and -/// rotation then run the new way, so the stroke draws as it did. A compound path's subpaths are +/// last anchor): each stroke's width profile (sides swapped), pen pressure, tilt, bearing, +/// rotation and wheel then run the new way, so the stroke draws as it did. A compound path's subpaths are /// its members' subpaths in order. A stroke reads one profile along every subpath, so it turns /// only when all of them turn alike. Arrowheads stay at the path's start and end. pub fn reverse_stroke_records(n: &mut Node, reversed: &[bool]) { @@ -3014,6 +3015,48 @@ mod tests { assert!((rot(0.5, 0.499) - rot(0.5, 0.501)).abs() < 1.0, "no jump where the key started: {:?}", stroke(&blend.at(0.5)).rotation); } + #[test] + fn a_stylus_wheel_recording_turns_with_the_gradient_and_dashes_of_its_stroke() { + let keyed = |path: PathData, edit: &dyn Fn(&mut StrokeLayer)| { + let mut ap = Appearance::default(); + ap.set_stroke(Paint::solid(Color::BLACK)); + if let Some(s) = ap.stroke_mut() { + edit(s); + } + Node::path(NodeId(1), path, ap) + }; + let stroke = |n: &Node| n.appearance.stroke().cloned().unwrap_or_else(|| panic!("a stroke")); + let wheel = |s: &StrokeLayer, f: f64| s.wheel.as_ref().map_or(PressureProfile::MID, |p| p.at(f)); + let light = |s: &StrokeLayer, u: f32| match &s.paint { + Paint::Gradient(g) => g.gradient.sample(u).0.to_rgb().iter().sum::(), + p => panic!("a gradient: {p:?}"), + }; + let recorded = |s: &mut StrokeLayer| { + s.wheel = Some(PressureProfile { points: vec![(0.0, 0.0), (1.0, 1.0)] }); + s.paint = Paint::Gradient(Box::new(GradientPaint::new(Gradient::default()))); + s.gradient_mode = StrokeGradientMode::Along; + s.dash = Some(Dash { pattern: vec![1.0, 2.0, 3.0, 1.5], offset: 0.75, align_corners: false }); + }; + // An open key clicked at its last anchor: the wheel runs the other way with the gradient + // along it, and the dashes are read from its end. + let line = |x: f64| PathData::single(SubPath::polyline(&[Point::new(x, 0.0), Point::new(x + 13.0, 0.0)], false)); + let key = keyed(line(100.0), &recorded); + let s = stroke(&Lerp::new(&keyed(line(0.0), &|_| {}), &key, (None, Some(1))).at(1.0)); + assert!((wheel(&s, 0.0) - 1.0).abs() < 1e-9 && wheel(&s, 1.0).abs() < 1e-9, "{:?}", s.wheel); + assert!(light(&s, 0.0) < 0.01 && light(&s, 1.0) > 2.99, "{:?}", s.paint); + assert_ne!(s.dash, stroke(&key).dash, "the dashes turn too"); + // A closed key started half way round starts its wheel recording there, stepping where its + // own start was, as its gradient does. + let square = |x: f64| shapes::rectangle(Rect::new(x, 0.0, x + 10.0, 10.0)); + let key = keyed(square(100.0), &recorded); + let s = stroke(&Lerp::new(&keyed(square(0.0), &|_| {}), &key, (Some(0), Some(2))).at(1.0)); + assert!((wheel(&s, 0.25) - 0.75).abs() < 1e-9 && (wheel(&s, 0.75) - 0.25).abs() < 1e-9, "{:?}", s.wheel); + assert!((light(&s, 0.25) - 0.75).abs() < 0.02 && (light(&s, 0.75) - 2.25).abs() < 0.02, "{:?}", s.paint); + // Half way through, a key without a recording counts as the wheel half way. + let s = stroke(&Lerp::new(&keyed(square(0.0), &|_| {}), &key, (Some(0), Some(2))).at(0.5)); + assert!((wheel(&s, 0.25) - 0.625).abs() < 1e-9, "{:?}", s.wheel); + } + #[test] fn stroke_gradients_and_dashes_turn_with_a_key_path_started_elsewhere() { let keyed = |path: PathData, edit: &dyn Fn(&mut StrokeLayer)| { diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 4365f7788a..608902756b 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -35,6 +35,7 @@ impl Document { char_styles, para_styles, composite_fonts, + kinsoku_sets, text_threads, symbols, graph_designs, @@ -96,6 +97,7 @@ impl Document { && *char_styles == other.char_styles && *para_styles == other.para_styles && *composite_fonts == other.composite_fonts + && *kinsoku_sets == other.kinsoku_sets && *text_threads == other.text_threads && symbols.len() == other.symbols.len() && symbols.iter().zip(&other.symbols).all(|(a, b)| a.name == b.name && Arc::ptr_eq(&a.art, &b.art)) @@ -221,6 +223,7 @@ impl Document { char_styles: Default::default(), para_styles: Default::default(), composite_fonts: Default::default(), + kinsoku_sets: Default::default(), text_threads: vec![], symbols: vec![], graph_designs: vec![], diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index fd1071711b..3f53bc693f 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -138,7 +138,7 @@ pub use text::{ RubyPosition, RubySpan, ScriptMetrics, SingleWordJustify, TabAlign, TabStop, TextFlow, TextKind, TextObject, TextRun, TextStyleDef, TextWrap, VerticalAlign, WrapShape, }; -pub use text::{CharClass, CompositeClass, CompositeFont, CompositePart, CompositeParts, CustomCharSet}; +pub use text::{CharClass, CompositeClass, CompositeFont, CompositePart, CompositeParts, CustomCharSet, KinsokuSet}; pub use trace::TraceView; pub use variables::{DataSet, DataValue, Variable, VariableKind, Variables}; pub use vectorcraft_color as color; @@ -218,6 +218,10 @@ pub struct Document { /// Type › Composite Fonts…: the composite fonts defined in the document, by name. #[serde(default, skip_serializing_if = "skip::is_empty_vec")] pub composite_fonts: Shared>, + /// Type › Kinsoku Shori Settings…: the custom Kinsoku Shori sets defined in the document, by + /// name. A paragraph using one holds a copy of it ([`ParaStyle::kinsoku_set`]). + #[serde(default, skip_serializing_if = "skip::is_empty_vec", deserialize_with = "text::read_kinsoku_sets")] + pub kinsoku_sets: Shared>, /// Threaded text: area-type frames one story flows through, in order. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub text_threads: Vec>, diff --git a/crates/doc/src/mem.rs b/crates/doc/src/mem.rs index 278ee7cf22..3519986512 100644 --- a/crates/doc/src/mem.rs +++ b/crates/doc/src/mem.rs @@ -113,6 +113,19 @@ impl Document { .map(|f| f.name.capacity() + crate::CharClass::ALL.into_iter().map(|k| part(f.parts.get(k))).sum::() + custom(f)) .sum::() }); + n += shared(&self.kinsoku_sets, &newer.kinsoku_sets, |k| { + vec_bytes(k) + + k.iter() + .map(|s: &crate::KinsokuSet| { + s.name.capacity() + + vec_bytes(&s.cannot_start) + + vec_bytes(&s.cannot_end) + + vec_bytes(&s.hanging) + + vec_bytes(&s.inseparable) + + s.inseparable.iter().map(String::capacity).sum::() + }) + .sum::() + }); n += shared(&self.saved_selections, &newer.saved_selections, |s| { vec_bytes(s) + s.iter().map(|s: &SavedSelection| s.name.capacity() + vec_bytes(&s.objects)).sum::() }); @@ -354,7 +367,8 @@ pub fn appearance_heap_bytes(a: &Appearance) -> usize { AppearanceItem::Stroke(s) => { s.dash.as_ref().map_or(0, |d| vec_bytes(&d.pattern)) + s.profile.as_ref().map_or(0, |p| vec_bytes(&p.points)) - + s.pressure.as_ref().map_or(0, |p| vec_bytes(&p.points)) + + [&s.pressure, &s.tilt, &s.wheel].into_iter().flatten().map(|p| vec_bytes(&p.points)).sum::() + + [&s.bearing, &s.rotation].into_iter().flatten().map(|p| vec_bytes(&p.points)).sum::() + s.brush.as_ref().map_or(0, String::capacity) } _ => 0, @@ -425,6 +439,27 @@ mod tests { d } + #[test] + fn every_pen_recording_of_a_stroke_counts() { + use crate::{AngleProfile, PressureProfile}; + let plain = Appearance::default_art(); + let base = appearance_heap_bytes(&plain); + let ramp = || PressureProfile { points: (0..100).map(|i| (f64::from(i) / 99.0, 0.5)).collect() }; + let turn = || AngleProfile { points: (0..100).map(|i| (f64::from(i) / 99.0, 10.0)).collect() }; + for i in 0..5 { + let mut a = plain.clone(); + let s = a.stroke_mut().unwrap(); + match i { + 0 => s.pressure = Some(ramp()), + 1 => s.tilt = Some(ramp()), + 2 => s.bearing = Some(turn()), + 3 => s.rotation = Some(turn()), + _ => s.wheel = Some(ramp()), + } + assert!(appearance_heap_bytes(&a) >= base + 100 * size_of::<(f64, f64)>(), "recording {i}"); + } + } + #[test] fn an_unchanged_copy_keeps_nothing_of_its_own() { let d = doc_with_rects(10); diff --git a/crates/doc/src/node/extras.rs b/crates/doc/src/node/extras.rs index 06a62cb171..f953deda71 100644 --- a/crates/doc/src/node/extras.rs +++ b/crates/doc/src/node/extras.rs @@ -10,8 +10,9 @@ use super::{Node, PathData}; pub struct NodeExtras { /// Opacity mask (Transparency panel). Its art lives here, outside the layer tree. pub mask: Option>, - /// Image Trace object: `{preset, params, view?}` it was traced with (the Image Trace panel shows - /// them; `view` is its [`crate::TraceView`] id, absent for the tracing result). + /// Image Trace object: `{preset, params, view?, split?}` it was traced with (the Image Trace + /// panel shows them; `view` is its [`crate::TraceView`] id, absent for the tracing result, and + /// `split` the Split view's divider, [`crate::TraceView::split_of`]). pub trace: Option>, /// Object → Text Wrap: area type below this object (in the same layer) flows around it. pub wrap: Option, diff --git a/crates/doc/src/style_libs.rs b/crates/doc/src/style_libs.rs index 34faf1f9c4..4bb4ce85bf 100644 --- a/crates/doc/src/style_libs.rs +++ b/crates/doc/src/style_libs.rs @@ -157,6 +157,7 @@ pub const STYLE_LIBRARIES: &[BuiltinStyleLibrary] = &[ BuiltinStyleLibrary { id: "hand-drawn", name: "Hand-Drawn", make: hand_drawn }, BuiltinStyleLibrary { id: "textures", name: "Textures", make: textures }, BuiltinStyleLibrary { id: "painted-sketched", name: "Painted and Sketched", make: painted_sketched }, + BuiltinStyleLibrary { id: "paper-cutouts", name: "Paper Cutouts", make: paper_cutouts }, BuiltinStyleLibrary { id: "gradient-finishes", name: "Gradient Finishes", make: gradient_finishes }, BuiltinStyleLibrary { id: "shape-effects", name: "Shape Effects", make: shape_effects }, BuiltinStyleLibrary { id: "blends-transparency", name: "Blends and Transparency", make: blends_transparency }, @@ -384,6 +385,25 @@ fn painted_sketched() -> Vec { ] } +/// Paper Cutouts: original layered paper colors with visible cut edges and crisp cast shadows. +fn paper_cutouts() -> Vec { + let cutout = |name: &str, face: &str, edge: &str, rim: &str, shadow: &str, x: f64, y: f64| { + style( + name, + vec![F(fill(face)), S(stroke(edge, 7.0)), S(stroke(rim, 2.0))], + vec![fx("stylize.dropShadow", json!({"mode": "normal", "opacity": 100.0, "x": x, "y": y, "blur": 0.0, "color": shadow}))], + ) + }; + vec![ + cutout("Coral Layers", "#ff6b6b", "#f9c74f", "#fff4e6", "#6d597a", 5.0, 5.0), + cutout("Mint Layers", "#80cbc4", "#2a9d8f", "#e9f5db", "#355070", 4.0, 6.0), + cutout("Midnight Layers", "#3d5a80", "#ee6c4d", "#e0fbfc", "#1b263b", 6.0, 4.0), + cutout("Sunflower Sheet", "#ffbe0b", "#fb5607", "#fff3b0", "#6a4c93", 3.0, 6.0), + cutout("Rose Layers", "#f28482", "#84a59d", "#f7ede2", "#4a4e69", 6.0, 3.0), + cutout("Monochrome Stack", "#f5f5f5", "#444444", "#ffffff", "#222222", 5.0, 5.0), + ] +} + /// Textures: fills and strokes painted with the catalog's texture effects (grain, canvas and /// burlap surfaces, craquelure, tiles, patchwork, stained glass and water paper). fn textures() -> Vec { @@ -702,6 +722,26 @@ mod tests { assert_eq!(ids.iter().position(|&i| i == "textures"), ids.iter().position(|&i| i == "hand-drawn").map(|i| i + 1), "after Hand-Drawn"); } + #[test] + fn paper_cutouts_have_layered_edges_and_crisp_shadows() { + let lib = builtin_style_library("paper-cutouts").unwrap(); + assert_eq!(lib.name, "Paper Cutouts"); + let names: Vec<&str> = lib.styles.iter().map(|g| g.name.as_str()).collect(); + assert_eq!(names, ["Coral Layers", "Mint Layers", "Midnight Layers", "Sunflower Sheet", "Rose Layers", "Monochrome Stack"]); + for g in &lib.styles { + assert_eq!(g.appearance.items.len(), 3, "{} has a face and two cut edges", g.name); + assert!(matches!(g.appearance.items[0], AppearanceItem::Fill(_))); + assert!(matches!(g.appearance.items[1], AppearanceItem::Stroke(_))); + assert!(matches!(g.appearance.items[2], AppearanceItem::Stroke(_))); + assert_eq!(g.appearance.effects.len(), 1); + let shadow = &g.appearance.effects[0]; + assert_eq!(shadow.id, "stylize.dropShadow"); + assert_eq!(shadow.params["blur"], 0.0); + assert_eq!(shadow.params["opacity"], 100.0); + } + assert_eq!(read(&write(&lib), "Fallback").unwrap(), *lib); + } + /// The built-in styles' Warps draw with the map a new Warp takes. #[test] fn builtin_warp_styles_take_the_nets_map() { diff --git a/crates/doc/src/text.rs b/crates/doc/src/text.rs index a07afd0843..c6a9860189 100644 --- a/crates/doc/src/text.rs +++ b/crates/doc/src/text.rs @@ -9,6 +9,7 @@ use crate::appearance::{Appearance, AppearanceItem, Dash, FillLayer, LineCap, Li mod area; mod char_style; mod composite; +mod kinsoku_set; mod object; mod para_style; mod runs; @@ -25,6 +26,8 @@ pub use composite::{ COMPOSITE_BASELINE, COMPOSITE_FONTS_MAX, COMPOSITE_NAME_MAX, COMPOSITE_SCALE, COMPOSITE_SIZE, CUSTOM_CHARS_MAX, CUSTOM_SETS_MAX, CharClass, CompositeClass, CompositeClasses, CompositeFont, CompositePart, CompositeParts, CustomCharSet, }; +pub(crate) use kinsoku_set::read_sets as read_kinsoku_sets; +pub use kinsoku_set::{KINSOKU_BUILT_IN, KINSOKU_CATEGORY_MAX, KINSOKU_NAME_MAX, KINSOKU_SEQUENCE, KINSOKU_SETS_MAX, KinsokuSet}; pub use para_style::{ Burasagari, Composer, FirstBaseline, HyphenationOptions, JustificationOptions, Justify, Kashida, Kinsoku, KinsokuShoriType, LeadingModel, Mojikumi, ParaDirection, ParaStyle, SingleWordJustify, diff --git a/crates/doc/src/text/kinsoku_set.rs b/crates/doc/src/text/kinsoku_set.rs new file mode 100644 index 0000000000..625c5a8ffa --- /dev/null +++ b/crates/doc/src/text/kinsoku_set.rs @@ -0,0 +1,382 @@ +//! Type › Kinsoku Shori Settings…: a custom Kinsoku Shori set, saved with the document. Its four +//! categories hold the characters that may not start a line, those that may not end one, the +//! hanging punctuation that Burasagari lets stand outside a line, and the inseparable sequences +//! that Bunri-Kinshi keeps on one line. A paragraph that uses a set holds a copy of it +//! ([`super::ParaStyle::kinsoku_set`]). +//! +//! Behavior reference: the help page +//! . +//! The name rules and the limits are VectorCraft's own. + +use serde::{Deserialize, Serialize}; + +/// The longest set name, in characters. +pub const KINSOKU_NAME_MAX: usize = 128; +/// The most custom sets a document keeps. +pub const KINSOKU_SETS_MAX: usize = 256; +/// The most characters one category holds (an inseparable sequence counts each of its characters). +pub const KINSOKU_CATEGORY_MAX: usize = 4096; +/// The fewest and most characters of an inseparable sequence. +pub const KINSOKU_SEQUENCE: std::ops::RangeInclusive = 2..=16; +/// The names of the built-in sets, which no custom set may take (in any case). +pub const KINSOKU_BUILT_IN: [&str; 3] = ["None", "Hard", "Soft"]; + +/// A custom Kinsoku Shori set. Each list of characters is sorted and holds each character once; +/// the inseparable sequences are sorted and unique. +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(from = "KinsokuSetFile", into = "KinsokuSetFile")] +pub struct KinsokuSet { + pub name: String, + /// Cannot Start Line: characters that never start a line. + pub cannot_start: Vec, + /// Cannot End Line: characters that never end a line. + pub cannot_end: Vec, + /// Hanging Punctuation: characters that Burasagari lets hang outside a line's end. + pub hanging: Vec, + /// Bunri-Kinshi: sequences of characters that a line never breaks inside while Bunri-Kinshi is + /// on. + pub inseparable: Vec, +} + +/// [`KinsokuSet`] as saved: each category of single characters as one string. +#[derive(Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +struct KinsokuSetFile { + #[serde(default, deserialize_with = "read_name")] + name: String, + #[serde(default, deserialize_with = "read_category")] + cannot_start: String, + #[serde(default, deserialize_with = "read_category")] + cannot_end: String, + #[serde(default, deserialize_with = "read_category")] + hanging: String, + #[serde(default, deserialize_with = "read_sequences")] + inseparable: Vec, +} + +/// The most characters of a name read from a file, spaces around it included; a longer name is +/// not read. +const NAME_READ_MAX: usize = KINSOKU_CATEGORY_MAX; +/// The most characters of a category read from a file, before control and space characters are +/// left out. +const CATEGORY_READ_MAX: usize = KINSOKU_CATEGORY_MAX * 4; +/// The longest inseparable sequence, as a constant for [`Capped`]. +const SEQUENCE_MAX: usize = *KINSOKU_SEQUENCE.end(); + +/// Text read from a file, copied up to `N` characters: a longer text keeps its first `N + 1`, which +/// no rule that allows `N` takes, and is not copied whole. +struct Capped(String); + +impl<'de, const N: usize> Deserialize<'de> for Capped { + fn deserialize>(d: D) -> Result { + struct Text; + impl serde::de::Visitor<'_> for Text { + type Value = Capped; + fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + f.write_str("text") + } + fn visit_str(self, v: &str) -> Result, E> { + Ok(Capped(v.chars().take(N + 1).collect())) + } + } + d.deserialize_str(Text::) + } +} + +/// A set's name as read from a file: empty, so not read, when it is longer than [`NAME_READ_MAX`]. +fn read_name<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + let Capped(name) = Capped::::deserialize(d)?; + Ok(if name.chars().count() > NAME_READ_MAX { String::new() } else { name }) +} + +/// A category of a set as read from a file: its first [`CATEGORY_READ_MAX`] characters. +fn read_category<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + let Capped(text) = Capped::::deserialize(d)?; + Ok(text.chars().take(CATEGORY_READ_MAX).collect()) +} + +/// Reads a list, keeping the items `keep` keeps up to `max` of them and skipping the rest of a +/// longer list without storing it. +struct Kept(usize, F, std::marker::PhantomData); + +impl<'de, T: Deserialize<'de>, F: FnMut(&T) -> bool> serde::de::Visitor<'de> for Kept { + type Value = Vec; + fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + f.write_str("a list") + } + fn visit_seq>(mut self, mut seq: A) -> Result, A::Error> { + let mut out = Vec::new(); + while out.len() < self.0 { + match seq.next_element::()? { + Some(item) if (self.1)(&item) => out.push(item), + Some(_) => {} + None => return Ok(out), + } + } + while seq.next_element::()?.is_some() {} + Ok(out) + } +} + +/// A set's inseparable sequences as read from a file: those [`KinsokuSet::takes_sequence`] takes, +/// at most [`KINSOKU_CATEGORY_MAX`]. A text longer than a sequence is not copied whole. +fn read_sequences<'de, D: serde::Deserializer<'de>>(d: D) -> Result, D::Error> { + let keep = |s: &Capped| KinsokuSet::takes_sequence(&s.0); + let kept = d.deserialize_seq(Kept(KINSOKU_CATEGORY_MAX, keep, std::marker::PhantomData))?; + Ok(kept.into_iter().map(|Capped(s)| s).collect()) +} + +impl From for KinsokuSetFile { + fn from(s: KinsokuSet) -> Self { + Self { + name: s.name, + cannot_start: s.cannot_start.into_iter().collect(), + cannot_end: s.cannot_end.into_iter().collect(), + hanging: s.hanging.into_iter().collect(), + inseparable: s.inseparable, + } + } +} + +impl From for KinsokuSet { + /// A set read from a file keeps what a set can hold: its name trimmed, or no name when + /// [`KinsokuSet::clean_name`] refuses it; each category's characters sorted and unique, without + /// control or space characters, up to [`KINSOKU_CATEGORY_MAX`]; and the inseparable sequences of + /// [`KINSOKU_SEQUENCE`] characters, up to the same count of characters. + fn from(f: KinsokuSetFile) -> Self { + let chars = |s: &str| s.chars().filter(|&c| KinsokuSet::takes_char(c)).take(KINSOKU_CATEGORY_MAX * 4).collect::>(); + let mut set = KinsokuSet { + name: KinsokuSet::clean_name(&f.name).unwrap_or_default(), + cannot_start: chars(&f.cannot_start), + cannot_end: chars(&f.cannot_end), + hanging: chars(&f.hanging), + inseparable: f.inseparable, + }; + set.normalize(); + set.cannot_start.truncate(KINSOKU_CATEGORY_MAX); + set.cannot_end.truncate(KINSOKU_CATEGORY_MAX); + set.hanging.truncate(KINSOKU_CATEGORY_MAX); + let mut total = 0; + set.inseparable.retain(|s| { + total += s.chars().count(); + total <= KINSOKU_CATEGORY_MAX + }); + set + } +} + +/// A document's custom sets as read from a file: each set with a name, the first set of each name +/// (in any case), at most [`KINSOKU_SETS_MAX`]; the sets past those are skipped without being +/// stored. +pub(crate) fn read_sets<'de, D: serde::Deserializer<'de>>(d: D) -> Result>, D::Error> { + let mut seen = std::collections::HashSet::new(); + let keep = move |s: &KinsokuSet| !s.name.is_empty() && seen.insert(s.name.to_lowercase()); + Ok(crate::Shared::new(d.deserialize_seq(Kept(KINSOKU_SETS_MAX, keep, std::marker::PhantomData))?)) +} + +impl KinsokuSet { + /// Do `a` and `b` name the same set: equal in any case? + pub fn same_name(a: &str, b: &str) -> bool { + a == b || a.to_lowercase() == b.to_lowercase() + } + + /// The set of `sets` (a document's custom sets) named `name`, in any case. + pub fn named<'a>(sets: &'a [KinsokuSet], name: &str) -> Option<&'a KinsokuSet> { + sets.iter().find(|s| Self::same_name(&s.name, name)) + } + + /// `name` trimmed, when it can name a custom set: not empty, at most [`KINSOKU_NAME_MAX`] + /// characters, without control characters, and none of [`KINSOKU_BUILT_IN`] in any case. + pub fn clean_name(name: &str) -> Option { + let name = name.trim(); + let ok = !name.is_empty() + && name.chars().count() <= KINSOKU_NAME_MAX + && !name.chars().any(char::is_control) + && !KINSOKU_BUILT_IN.iter().any(|b| Self::same_name(b, name)); + ok.then(|| name.to_string()) + } + + /// Can a category hold character `c`: not a control character nor a space? + pub fn takes_char(c: char) -> bool { + !c.is_control() && !c.is_whitespace() + } + + /// Can `s` be an inseparable sequence: [`KINSOKU_SEQUENCE`] characters that + /// [`Self::takes_char`] takes? + pub fn takes_sequence(s: &str) -> bool { + KINSOKU_SEQUENCE.contains(&s.chars().count()) && s.chars().all(Self::takes_char) + } + + /// Sort each category and keep each character or sequence once. + pub fn normalize(&mut self) { + for list in [&mut self.cannot_start, &mut self.cannot_end, &mut self.hanging] { + list.sort_unstable(); + list.dedup(); + } + self.inseparable.sort_unstable(); + self.inseparable.dedup(); + } + + /// Why this set can't be used, if it can't: a name [`Self::clean_name`] refuses, a character + /// [`Self::takes_char`] refuses, a sequence [`Self::takes_sequence`] refuses, or a category of + /// more than [`KINSOKU_CATEGORY_MAX`] characters. + pub fn check(&self) -> Result<(), String> { + if Self::clean_name(&self.name).as_deref() != Some(self.name.as_str()) { + return Err(format!( + "`{}` can't name a Kinsoku set (1 to {KINSOKU_NAME_MAX} characters, no control characters, not None, Hard or Soft)", + self.name + )); + } + for (key, list) in [("cannotStart", &self.cannot_start), ("cannotEnd", &self.cannot_end), ("hanging", &self.hanging)] { + if list.len() > KINSOKU_CATEGORY_MAX { + return Err(format!("{key}: at most {KINSOKU_CATEGORY_MAX} characters")); + } + if let Some(c) = list.iter().find(|&&c| !Self::takes_char(c)) { + return Err(format!("{key}: U+{:04X} is a control or space character", u32::from(*c))); + } + } + if let Some(s) = self.inseparable.iter().find(|s| !Self::takes_sequence(s)) { + return Err(format!( + "inseparable: `{s}` must be {} to {} characters, none of them control or space characters", + KINSOKU_SEQUENCE.start(), + KINSOKU_SEQUENCE.end() + )); + } + if self.inseparable.iter().map(|s| s.chars().count()).sum::() > KINSOKU_CATEGORY_MAX { + return Err(format!("inseparable: at most {KINSOKU_CATEGORY_MAX} characters in all")); + } + Ok(()) + } + + /// May `c` not start a line? + pub fn cannot_start(&self, c: char) -> bool { + self.cannot_start.binary_search(&c).is_ok() + } + + /// May `c` not end a line? + pub fn cannot_end(&self, c: char) -> bool { + self.cannot_end.binary_search(&c).is_ok() + } + + /// May `c` hang outside a line's end (Burasagari)? + pub fn hangs(&self, c: char) -> bool { + self.hanging.binary_search(&c).is_ok() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::text::{Kinsoku, ParaStyle}; + use serde_json::json; + use std::sync::Arc; + + /// A set is saved with each category as one string and read back as it was; a paragraph saves + /// its copy of the set beside Hard, and a paragraph saved without one reads with none. + #[test] + fn kinsoku_sets_are_saved_with_the_paragraphs_that_use_them() { + let mut set = KinsokuSet { + name: "Tight".into(), + cannot_start: "」。、".chars().collect(), + cannot_end: vec!['「'], + hanging: vec!['、', '。'], + inseparable: vec!["——".into(), "あいう".into()], + }; + set.normalize(); + let saved = serde_json::to_value(&set).unwrap(); + assert_eq!(saved, json!({"name": "Tight", "cannotStart": "、。」", "cannotEnd": "「", "hanging": "、。", "inseparable": ["——", "あいう"]})); + assert_eq!(serde_json::from_value::(saved).unwrap(), set); + let p = ParaStyle { kinsoku_set: Some(Arc::new(set.clone())), ..ParaStyle::default() }; + let v = serde_json::to_value(&p).unwrap(); + assert_eq!(v["kinsoku_set"]["name"], "Tight"); + assert!(v.get("kinsoku").is_none(), "Hard, the default, is left out"); + let back: ParaStyle = serde_json::from_value(v).unwrap(); + assert_eq!(back.kinsoku_set.as_deref(), Some(&set)); + assert_eq!((back.kinsoku, back.kinsoku_name(), back.kinsoku_on()), (Kinsoku::Hard, "Tight", true)); + let old: ParaStyle = serde_json::from_value(json!({"justify": "Left", "kinsoku": "soft"})).unwrap(); + assert_eq!((old.kinsoku_set, old.kinsoku), (None, Kinsoku::Soft)); + assert!(serde_json::to_value(ParaStyle::default()).unwrap().get("kinsoku_set").is_none()); + } + + /// A set read from a file keeps only what a set can hold: each character once, sorted, without + /// control or space characters, at most 4096 to a category, and sequences of 2 to 16 + /// characters; a category left out is empty. Only the start of a longer text is read. + #[test] + fn kinsoku_sets_read_from_a_file_keep_what_a_set_can_hold() { + let long: String = (0x4E00..0x4E00 + 5000).filter_map(char::from_u32).collect(); + let v = json!({ + "name": "Odd", + "cannotStart": "ccba \t\u{0}a", + "cannotEnd": long, + "inseparable": ["a", "ab", "ab", "a b", "abcdefghijklmnopq", "abcdefghijklmnop"], + }); + let set: KinsokuSet = serde_json::from_value(v).unwrap(); + assert_eq!(set.cannot_start, ['a', 'b', 'c']); + assert_eq!(set.cannot_end.len(), KINSOKU_CATEGORY_MAX); + assert!(set.hanging.is_empty()); + assert_eq!(set.inseparable, ["ab", "abcdefghijklmnop"]); + assert!(set.check().is_ok()); + let empty: KinsokuSet = serde_json::from_value(json!({})).unwrap(); + assert!(empty.check().is_err(), "a set needs a name"); + // Only the start of a long text is read: a category's first 16384 characters, a name of at + // most 4096 characters, spaces included, and a sequence's first 17. + let spaces = " ".repeat(CATEGORY_READ_MAX); + let text = format!( + r#"{{"name": "{}Tight", "hanging": "{spaces}、", "cannotEnd": "、", "inseparable": ["{}あ"]}}"#, + " ".repeat(NAME_READ_MAX), + "あ".repeat(100) + ); + let set: KinsokuSet = serde_json::from_str(&text).unwrap(); + assert_eq!((set.name.as_str(), set.hanging.len(), set.cannot_end.len(), set.inseparable.len()), ("", 0, 1, 0)); + let set: KinsokuSet = serde_json::from_str(&format!(r#"{{"name": "{}Tight"}}"#, " ".repeat(NAME_READ_MAX - 5))).unwrap(); + assert_eq!(set.name, "Tight"); + } + + /// A set read from a file under a name a custom set can't take (a built-in name, a blank one) + /// is not read: a paragraph holding it keeps its Kinsoku Set, so it doesn't show as Hard while + /// composing by other characters, and a document's list drops it. The list also keeps the + /// first set of each name in any case, and a name read with spaces around it is trimmed. A + /// paragraph's set read beside None or Soft is not read either. + #[test] + fn kinsoku_sets_read_under_names_a_set_cannot_take_are_dropped() { + let p: ParaStyle = serde_json::from_value(json!({"kinsoku_set": {"name": "Hard", "cannotStart": "あ"}})).unwrap(); + assert_eq!((p.kinsoku_set, p.kinsoku), (None, Kinsoku::Hard)); + let p: ParaStyle = serde_json::from_value(json!({"kinsoku": "none", "kinsoku_set": {"name": "Tight", "cannotStart": "あ"}})).unwrap(); + assert_eq!((p.kinsoku_set.is_none(), p.kinsoku_name()), (true, "None")); + let p: ParaStyle = serde_json::from_value(json!({"kinsoku_set": {"name": " Tight ", "cannotStart": "あ"}})).unwrap(); + assert_eq!(p.kinsoku_name(), "Tight"); + let mut v = serde_json::to_value(crate::Document::new(100.0, 100.0)).unwrap(); + v["kinsoku_sets"] = json!([{"name": "soft"}, {"name": " "}, {"name": "Tight", "cannotEnd": "「"}, {"name": "TIGHT"}, {"name": "Loose"}]); + let d: crate::Document = serde_json::from_value(v).unwrap(); + let names: Vec<&str> = d.kinsoku_sets.iter().map(|s| s.name.as_str()).collect(); + assert_eq!(names, ["Tight", "Loose"]); + assert_eq!(d.kinsoku_sets[0].cannot_end, ['「']); + let mut v = serde_json::to_value(crate::Document::new(100.0, 100.0)).unwrap(); + // The sets past the limit are skipped unread: one that isn't a set at all doesn't fail the + // file. + let mut list: Vec = (0..KINSOKU_SETS_MAX + 5).map(|i| json!({"name": format!("S{i}")})).collect(); + list.push(json!("not a set")); + v["kinsoku_sets"] = json!(list); + let d: crate::Document = serde_json::from_value(v).unwrap(); + assert_eq!(d.kinsoku_sets.len(), KINSOKU_SETS_MAX); + let past: Vec = (0..KINSOKU_CATEGORY_MAX + 1).map(|i| format!("あ{i}")).chain(["x".to_string()]).collect(); + let mut seqs: Vec = past.iter().map(|s| json!(s)).collect(); + seqs.push(json!(7)); + let set: KinsokuSet = serde_json::from_value(json!({"name": "Long", "inseparable": seqs})).unwrap(); + assert!(set.check().is_ok()); + } + + /// A name is trimmed, 1 to 128 characters without control characters, and never None, Hard or + /// Soft in any case; names match in any case. + #[test] + fn kinsoku_set_names_are_checked() { + assert_eq!(KinsokuSet::clean_name(" Tight "), Some("Tight".into())); + for bad in ["", " ", "hard", "SOFT", "None", "a\u{7}b", &"x".repeat(KINSOKU_NAME_MAX + 1)] { + assert_eq!(KinsokuSet::clean_name(bad), None, "{bad:?}"); + } + assert!(KinsokuSet::clean_name(&"漢".repeat(KINSOKU_NAME_MAX)).is_some()); + assert!(KinsokuSet::same_name("Tight", "tIGHT")); + let sets = [KinsokuSet { name: "Tight".into(), ..Default::default() }]; + assert!(KinsokuSet::named(&sets, "TIGHT").is_some() && KinsokuSet::named(&sets, "Loose").is_none()); + } +} diff --git a/crates/doc/src/text/para_style.rs b/crates/doc/src/text/para_style.rs index 17325d071c..3b0847d8fb 100644 --- a/crates/doc/src/text/para_style.rs +++ b/crates/doc/src/text/para_style.rs @@ -1,4 +1,7 @@ +use std::sync::Arc; + use super::char_style::CharStyle; +use super::kinsoku_set::KinsokuSet; use super::tabs_lists::{ParaList, TabStop}; use super::{Deserialize, Serialize}; @@ -256,14 +259,18 @@ pub struct ParaStyle { /// How leading is measured (Paragraph panel menu): from baseline to baseline, or from the top /// of one line's ideographic em box to the next. pub leading_model: LeadingModel, - /// Hanging punctuation (Paragraph panel menu › Burasagari): a comma or full stop ending a line - /// may stand outside the frame. New type takes [`Burasagari::Standard`]; documents from before + /// Hanging punctuation (Paragraph panel menu › Burasagari): the Kinsoku Set's hanging + /// punctuation ending a line may stand outside the frame. New type takes [`Burasagari::Standard`]; documents from before /// it and imported text keep [`Burasagari::None`], except legacy `.ai` type with binding /// punctuation on, which opens with [`Burasagari::Forced`]. pub burasagari: Burasagari, /// Kinsoku (Paragraph panel › Kinsoku Set): which Japanese characters may not start or end a /// line. pub kinsoku: Kinsoku, + /// A custom Kinsoku Shori set (Type › Kinsoku Shori Settings…) chosen in Kinsoku Set: a copy of + /// the document's set of that name, which takes the place of [`Self::kinsoku`]. A paragraph + /// with one keeps [`Kinsoku::Hard`] in `kinsoku`, which builds without custom sets read. + pub kinsoku_set: Option>, /// Kinsoku Shori Type (Paragraph panel menu): how a line keeps those characters off its start /// and end, by pushing them in onto the line or out to the next one. No effect without kinsoku. pub kinsoku_type: KinsokuShoriType, @@ -310,6 +317,21 @@ impl ParaStyle { } } + /// Does kinsoku apply: a custom set, or a Kinsoku Set other than None? + pub fn kinsoku_on(&self) -> bool { + self.kinsoku_set.is_some() || self.kinsoku != Kinsoku::None + } + + /// The name Kinsoku Set shows: the custom set's, or None, Hard or Soft. + pub fn kinsoku_name(&self) -> &str { + match (&self.kinsoku_set, self.kinsoku) { + (Some(set), _) => &set.name, + (None, Kinsoku::None) => "None", + (None, Kinsoku::Hard) => "Hard", + (None, Kinsoku::Soft) => "Soft", + } + } + /// The left indent the layout sets the paragraph at: its left indent, and for a paragraph in a /// list at a level past the first, [`ParaList::level_indent`] more. pub fn laid_out_left_indent(&self) -> f64 { @@ -373,6 +395,8 @@ struct ParaStyleFile { burasagari: Burasagari, #[serde(default, skip_serializing_if = "crate::skip::is_default")] kinsoku: Kinsoku, + #[serde(default, skip_serializing_if = "Option::is_none")] + kinsoku_set: Option>, #[serde(default, skip_serializing_if = "crate::skip::is_default")] kinsoku_type: KinsokuShoriType, #[serde(default, skip_serializing_if = "crate::skip::is_default")] @@ -415,6 +439,7 @@ impl From for ParaStyleFile { leading_model, burasagari, kinsoku, + kinsoku_set, kinsoku_type, bunri_kinshi, kurikaeshi_moji_shori, @@ -443,6 +468,7 @@ impl From for ParaStyleFile { leading_model, burasagari, kinsoku, + kinsoku_set, kinsoku_type, bunri_kinshi, kurikaeshi_moji_shori, @@ -475,6 +501,7 @@ impl From for ParaStyle { leading_model, burasagari, kinsoku, + kinsoku_set, kinsoku_type, bunri_kinshi, kurikaeshi_moji_shori, @@ -483,6 +510,11 @@ impl From for ParaStyle { korean_line_break_anywhere, .. } = f; + // A set whose saved name can't name a custom set (None, Hard or Soft, say) is read as no set: + // the paragraph keeps its Kinsoku Set. A paragraph with a custom set keeps Hard, so one read + // with None or Soft (a paragraph style written before custom sets, applied over one) has no + // custom set. + let kinsoku_set = kinsoku_set.filter(|s| !s.name.is_empty() && kinsoku == Kinsoku::Hard); Self { justify, left_indent, @@ -502,6 +534,7 @@ impl From for ParaStyle { leading_model, burasagari, kinsoku, + kinsoku_set, kinsoku_type, bunri_kinshi, kurikaeshi_moji_shori, @@ -604,19 +637,21 @@ pub enum KinsokuShoriType { PushOutOnly, } -/// Hanging punctuation (burasagari): an East Asian comma or full stop ending a line (、。,.、。) -/// stands outside the line's measure, in the space its punctuation spacing gives it (half width -/// with Line-end Punctuation Half Width). Closing brackets and Latin punctuation don't hang. Shown -/// as None / Regular / Force. +/// Hanging punctuation (burasagari): hanging punctuation ending a line stands outside the line's +/// measure, in the space its punctuation spacing gives it (half width with Line-end Punctuation +/// Half Width). With the built-in Kinsoku Sets that is an East Asian comma or full stop +/// (、。,.、。), and closing brackets and Latin punctuation don't hang; a custom Kinsoku Set hangs +/// the characters in its hanging category. Shown as None / Regular / Force. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum Burasagari { /// A comma or full stop that doesn't fit goes to the next line with the character before it. #[default] None, - /// A comma or full stop that doesn't fit hangs outside the line; one that fits stays inside. + /// Hanging punctuation that doesn't fit hangs outside the line; punctuation that fits stays + /// inside. Standard, - /// A comma or full stop ending a line always hangs, and the rest of the line fills the measure. + /// Hanging punctuation ending a line always hangs, and the rest of the line fills the measure. Forced, } diff --git a/crates/doc/src/trace.rs b/crates/doc/src/trace.rs index 042d6b3ada..a2d17cc990 100644 --- a/crates/doc/src/trace.rs +++ b/crates/doc/src/trace.rs @@ -20,11 +20,18 @@ pub enum TraceView { OutlinesWithSource, /// Only the source image. Source, + /// The source image on the part of the image left of a divider across it, and the traced + /// shapes everywhere else ([`TraceView::split_of`]). + Split, } +/// Where the Split view's divider is when the `trace` settings name no valid position: across the +/// middle of the source image. +pub const DEFAULT_TRACE_SPLIT: f64 = 0.5; + impl TraceView { /// Panel order. - pub const ALL: [Self; 5] = [Self::Result, Self::ResultWithOutlines, Self::Outlines, Self::OutlinesWithSource, Self::Source]; + pub const ALL: [Self; 6] = [Self::Result, Self::ResultWithOutlines, Self::Outlines, Self::OutlinesWithSource, Self::Source, Self::Split]; /// The id used in command params and in the saved `trace` object. pub fn id(self) -> &'static str { @@ -34,6 +41,7 @@ impl TraceView { Self::Outlines => "outlines", Self::OutlinesWithSource => "outlinesWithSourceImage", Self::Source => "sourceImage", + Self::Split => "split", } } @@ -48,14 +56,21 @@ impl TraceView { trace.get("view").and_then(serde_json::Value::as_str).and_then(Self::from_id).unwrap_or_default() } - /// Whether the source image shows. - pub fn shows_source(self) -> bool { - matches!(self, Self::OutlinesWithSource | Self::Source) + /// The Split view's divider in `trace` settings: the fraction of the source image's width, from + /// its left edge in its own pixels, that shows the source image ([`DEFAULT_TRACE_SPLIT`] when + /// `split` is missing, not a number or outside 0 to 1). + pub fn split_of(trace: &serde_json::Value) -> f64 { + trace.get("split").and_then(serde_json::Value::as_f64).filter(|f| (0.0..=1.0).contains(f)).unwrap_or(DEFAULT_TRACE_SPLIT) } - /// Whether the traced shapes show filled. + /// Whether the source image shows (in the Split view, on one side of the divider). + pub fn shows_source(self) -> bool { + matches!(self, Self::OutlinesWithSource | Self::Source | Self::Split) + } + + /// Whether the traced shapes show filled (in the Split view, on one side of the divider). pub fn shows_result(self) -> bool { - matches!(self, Self::Result | Self::ResultWithOutlines) + matches!(self, Self::Result | Self::ResultWithOutlines | Self::Split) } /// Whether the traced shapes' outlines show. @@ -69,6 +84,12 @@ impl Node { pub fn trace_view(&self) -> TraceView { self.extras().trace.as_deref().map(TraceView::of).unwrap_or_default() } + + /// The Split view's divider of an Image Trace object ([`TraceView::split_of`]; + /// [`DEFAULT_TRACE_SPLIT`] for anything else). + pub fn trace_split(&self) -> f64 { + self.extras().trace.as_deref().map_or(DEFAULT_TRACE_SPLIT, TraceView::split_of) + } } #[cfg(test)] @@ -89,6 +110,26 @@ mod tests { g.extras_mut().trace = Some(Box::new(serde_json::json!({"view": "sepia"}))); assert_eq!(g.trace_view(), TraceView::Result); } + + #[test] + fn the_split_divider_reads_a_fraction_and_falls_back_to_the_middle() { + let mut g = Node::group(crate::NodeId(1), vec![]); + assert_eq!(g.trace_split(), DEFAULT_TRACE_SPLIT); + assert_eq!(TraceView::from_id("Split"), Some(TraceView::Split)); + assert!(TraceView::Split.shows_source() && TraceView::Split.shows_result() && !TraceView::Split.shows_outlines()); + for (split, want) in [ + (serde_json::json!(0.25), 0.25), + (serde_json::json!(0), 0.0), + (serde_json::json!(1), 1.0), + (serde_json::json!(-0.1), DEFAULT_TRACE_SPLIT), + (serde_json::json!(1.5), DEFAULT_TRACE_SPLIT), + (serde_json::json!("0.3"), DEFAULT_TRACE_SPLIT), + (serde_json::Value::Null, DEFAULT_TRACE_SPLIT), + ] { + g.extras_mut().trace = Some(Box::new(serde_json::json!({"view": "split", "split": split}))); + assert_eq!(g.trace_split(), want, "{split}"); + } + } #[test] fn live_trace_result_bounds_exclude_the_retained_bitmap_at_any_angle() { use crate::{Appearance, Document, ImageObject, NodeId, NodeKind}; @@ -132,6 +173,13 @@ mod tests { } } } + // The Split view measures the whole image wherever the divider is, so the selection box + // stays put while the divider moves. + for split in [0.0, 0.01, 1.0] { + let want = Rect::new(0.0, 0.0, 200.0, 200.0); + group.extras_mut().trace = Some(Box::new(serde_json::json!({"view": "split", "split": split}))); + assert_eq!((group.geometric_bounds(), group.visual_bounds()), (Some(want), Some(want)), "split {split}"); + } group.extras_mut().trace = None; assert_eq!( group.geometric_bounds(), diff --git a/crates/doc/src/units.rs b/crates/doc/src/units.rs index f61319326c..728c8aa816 100644 --- a/crates/doc/src/units.rs +++ b/crates/doc/src/units.rs @@ -81,6 +81,21 @@ impl Unit { Unit::Ha => "H", } } + /// Whether this unit is a physical measurement unit (not points or pixels). + pub fn is_physical(self) -> bool { + self.svg_suffix().is_some() || matches!(self, Unit::FeetInches | Unit::Meters | Unit::Yards | Unit::Feet | Unit::Q | Unit::Ha) + } + /// The standard SVG length unit suffix, if this unit is a physical unit supported in SVG + /// (`mm`, `cm`, `in`, `pc`). + pub fn svg_suffix(self) -> Option<&'static str> { + match self { + Unit::Millimeters => Some("mm"), + Unit::Centimeters => Some("cm"), + Unit::Inches => Some("in"), + Unit::Picas => Some("pc"), + _ => None, + } + } pub const fn label(self) -> &'static str { match self { Unit::Points => "Points", diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index 568aa583b1..8e45364857 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -210,15 +210,15 @@ pub fn effect_catalog() -> Vec { CLASSIC_EXTRUDE, "Extrude & Bevel (Classic)…", &["Effect", "3D and Materials", "3D (Classic)"], - "{depth: pt (0..2000, 50), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelHeight: pt (1..100, 4; the bevel is as wide as it is tall), bevelInside: bool (false: added around the shape; true: carved into it), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face, hidden ones included, and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none|blackOverprint (black; the color the faces darken toward; none keeps the paint and adds only the highlight; blackOverprint keeps the paint and draws the shading over it as overprinting black, on the black plate, with no highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom, and with blackOverprint every face keeps its paint and swatch link whether it is on or off), drawHiddenFaces: bool (false; also draws the faces turned away, behind the others)}. The front face is the art, extruded backwards about the center of its bounds; a solid is built for the top fill and for each stroke, each in its own paint. The defaults are VectorCraft's own.", - json!({"depth":50.0,"cap":true,"bevel":"none","bevelHeight":4.0,"bevelInside":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"plastic","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"highlightIntensity":60.0,"highlightSize":90.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","preserveSpotColors":false,"drawHiddenFaces":false}), + "{depth: pt (0..2000, 50), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelHeight: pt (1..100, 4; the bevel is as wide as it is tall), bevelInside: bool (false: added around the shape; true: carved into it), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face, hidden ones included, and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none|blackOverprint (black; the color the faces darken toward; none keeps the paint and adds only the highlight; blackOverprint keeps the paint and draws the shading over it as overprinting black, on the black plate, with no highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom, and with blackOverprint every face keeps its paint and swatch link whether it is on or off), drawHiddenFaces: bool (false; also draws the faces turned away, behind the others), mapArt: array of 0..64 objects ([]; Map Art, see threeD.mapArt: surface: integer (1..100000; the numbered surface, one map for a surface), symbol: name of a document symbol, x: pt (-1000000..1000000, 0; the offset of the art's center from the center of the surface laid out flat), y: pt (-1000000..1000000, 0), scaleX: % (1..10000, 100; of the symbol's own width), scaleY: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); the surfaces are numbered through the object's solids in the order they are built: each solid's front cap and back cap (none on a hollow solid, cap false), then each side wall from corner to corner of the outline, then the bevel above each wall; a map past the object's surfaces draws nothing; wireframe draws no mapped art), mapShade: bool (false; Shade Artwork: the mapped art takes the tone and highlight of its face), mapInvisible: bool (false; Invisible Geometry: with at least one map, only the mapped art is drawn)}. The front face is the art, extruded backwards about the center of its bounds; a solid is built for the top fill and for each stroke, each in its own paint. The defaults, the surface numbering and the limits are VectorCraft's own.", + json!({"depth":50.0,"cap":true,"bevel":"none","bevelHeight":4.0,"bevelInside":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"plastic","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"highlightIntensity":60.0,"highlightSize":90.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","preserveSpotColors":false,"drawHiddenFaces":false,"mapArt":[],"mapShade":false,"mapInvisible":false}), ), g( CLASSIC_REVOLVE, "Revolve (Classic)…", &["Effect", "3D and Materials", "3D (Classic)"], - "{angle: degrees (0..360, 360; how far the profile sweeps round the axis), cap: bool (true: solid, the open ends and a partial sweep's cut sides closed; false: hollow), offset: pt (0..1000, 0; the axis's distance from the profile, a ring past 0), edge: left|right (left; the axis is at the left or the right edge of the profile's bounds), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none|blackOverprint (black; the color the faces darken toward; none keeps the paint and adds only the highlight; blackOverprint keeps the paint and draws the shading over it as overprinting black, on the black plate, with no highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom, and with blackOverprint every face keeps its paint and swatch link whether it is on or off)}. The profile sweeps round a vertical axis, as Revolve's does, painted with the top fill (else the top stroke); every face is drawn, back to front. The defaults are VectorCraft's own.", - json!({"angle":360.0,"cap":true,"offset":0.0,"edge":"left","rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"plastic","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"highlightIntensity":60.0,"highlightSize":90.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","preserveSpotColors":false}), + "{angle: degrees (0..360, 360; how far the profile sweeps round the axis), cap: bool (true: solid, the open ends and a partial sweep's cut sides closed; false: hollow), offset: pt (0..1000, 0; the axis's distance from the profile, a ring past 0), edge: left|right (left; the axis is at the left or the right edge of the profile's bounds), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none|blackOverprint (black; the color the faces darken toward; none keeps the paint and adds only the highlight; blackOverprint keeps the paint and draws the shading over it as overprinting black, on the black plate, with no highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom, and with blackOverprint every face keeps its paint and swatch link whether it is on or off), mapArt: array of 0..64 objects ([]; Map Art, see threeD.mapArt: surface: integer (the swept side is surface 1, the only one; in a group, the side of the member with the longest profile; a map of another surface draws nothing), symbol: name of a document symbol, x: pt (-1000000..1000000, 0; the offset of the art's center from the middle of the side unrolled flat, around the axis), y: pt (-1000000..1000000, 0; along the profile), scaleX: % (1..10000, 100; of the symbol's own width), scaleY: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); the art wraps around the side and is drawn where its outside faces the viewer; wireframe draws no mapped art), mapShade: bool (false; Shade Artwork: the mapped art takes the tone and highlight of its face), mapInvisible: bool (false; Invisible Geometry: with at least one map, only the mapped art is drawn)}. The profile sweeps round a vertical axis, as Revolve's does, painted with the top fill (else the top stroke); every face is drawn, back to front. The defaults, the surface numbering and the limits are VectorCraft's own.", + json!({"angle":360.0,"cap":true,"offset":0.0,"edge":"left","rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"plastic","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"highlightIntensity":60.0,"highlightSize":90.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","preserveSpotColors":false,"mapArt":[],"mapShade":false,"mapInvisible":false}), ), g( CLASSIC_ROTATE, diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index a6b4ccece9..fff4705333 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -108,6 +108,10 @@ pub use solids::{ 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 solids::{ + MAP_ART, MAP_ART_NOT_TAKEN, MAP_INVISIBLE, MAP_SHADE, MAX_MAP_SURFACE, MAX_MAPS, MapSurface, SurfaceKind, SurfaceMap, map_surfaces_at, + map_surfaces_with, surface_maps, takes_map_art, with_surface_map, +}; pub use stylize::{ScribbleSetting, scribble_setting_id, scribble_settings}; pub use svg_filter::SVG_FILTER; pub use trap::TRAP; diff --git a/crates/effects/src/revolve.rs b/crates/effects/src/revolve.rs index 43e60a0022..19522873f3 100644 --- a/crates/effects/src/revolve.rs +++ b/crates/effects/src/revolve.rs @@ -113,7 +113,7 @@ pub fn revolve_options(p: &Value) -> Revolve { /// The options Revolve (`id` [`REVOLVE`]) or Revolve (Classic) ([`CLASSIC_REVOLVE`]) with /// parameters `p` sweeps its surface with. A Revolve with graphics lays out its side for them. -fn options_of(id: &str, p: &Value) -> Revolve { +pub(crate) fn options_of(id: &str, p: &Value) -> Revolve { if id == CLASSIC_REVOLVE { classic::options(p) } else { @@ -141,6 +141,7 @@ pub fn validate_revolve_in(doc: Option<&Document>, n: &Node, p: &Value) -> Resul /// [`validate_revolve_in`] for Revolve or Revolve (Classic), `id`. pub(crate) fn validate_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value) -> Result<(), String> { validate_params_of(id, p)?; + validate_map_symbols(doc, id, p)?; let n = &*resolve_for(doc, n, "Revolve", false)?; let effects = &n.appearance.effects; // The profile is measured before the object's one Revolve, hidden or shown. @@ -215,7 +216,7 @@ fn check_graphics(doc: Option<&Document>, id: &str, path: &PathData, b: Rect, op /// The member of a group whose side takes the group's graphics: the first with the longest /// profile among those with a fill or stroke. -fn graphics_member(shapes: &[Profile], b: Rect, options: Revolve) -> Option { +pub(crate) fn graphics_member(shapes: &[Profile], b: Rect, options: Revolve) -> Option { shapes .iter() .enumerate() @@ -237,6 +238,20 @@ fn check_shadow<'a>(p: &Value, paths: impl IntoIterator, b: /// [`validate_revolve`] for a Revolve with parameters `p` at index `index` of the effects of /// appearance item `target` of `n` ([`validate_item_of`]). +/// An error when the symbols that Revolve (Classic)'s Map Art in `p` places, with the symbols of +/// `doc`, are past the limits of a graphic's art, as on Extrude & Bevel (Classic), or past the +/// limits of art unrolled onto its side, its only surface. +fn validate_map_symbols(doc: Option<&Document>, id: &str, p: &Value) -> Result<(), String> { + match doc.filter(|_| id == CLASSIC_REVOLVE) { + Some(doc) => { + crate::solids::graphics::validate_symbols(doc, p)?; + // The side is surface 1, laid out about the origin; a map past it draws nothing. + crate::solids::graphics::validate_unrolled_symbols(doc, p, &|surface| (surface == 1).then_some(Point::ZERO)) + } + None => Ok(()), + } +} + #[cfg(test)] pub(crate) fn validate_item_revolve(n: &Node, p: &Value, target: usize, index: usize) -> Result<(), String> { validate_item_of(None, n, REVOLVE, p, target, index) @@ -252,6 +267,7 @@ pub(crate) fn validate_item_of(doc: Option<&Document>, n: &Node, id: &str, p: &V return validate_in(doc, n, id, p); } validate_params_of(id, p)?; + validate_map_symbols(doc, id, p)?; const EMPTY: &str = "Revolve requires a shape with at least two anchors"; let (path, _) = object_profile(n, "Revolve")?; if !has_two_anchors(&path) { @@ -334,7 +350,7 @@ fn check_surface(path: &PathData, b: Rect, options: Revolve, item: Option<&Appea /// `options` with one number of samples for every curve of `shapes`, the members of one group: the /// members share Revolve's limits. -fn shared_options(shapes: &[Profile], options: Revolve) -> Result { +pub(crate) fn shared_options(shapes: &[Profile], options: Revolve) -> Result { let samples = vectorcraft_three_d::revolve_curve_samples(shapes.iter().map(|s| &s.path), options)?; Ok(Revolve { curve_samples: Some(samples), ..options }) } @@ -463,10 +479,12 @@ fn group_shadow( /// with its classic surface, as Extrude & Bevel (Classic) does. Revolve's graphics, with the /// symbols of `doc`, are drawn on the faces of the side ([`crate::solids::graphics::surface_parts`]): /// a face with a part of a graphic is a group of the face and that part. With `cast`, the sweep -/// that draws the surface also keeps the faces its shadow is cast from ([`SolidFaces`]). The last -/// value is whether the faces go over an underlay of themselves ([`seals`]): the caller seals them -/// ([`sealed_surface`], [`sealed_runs`]) in the order it draws them. -#[allow(clippy::too_many_arguments)] +/// that draws the surface also keeps the faces its shadow is cast from ([`SolidFaces`]). With +/// `hide`, a Revolve (Classic) surface without mapped art leaves its faces out, as Invisible +/// Geometry does ([`crate::solids::classic::surface`]). The last two values are whether the faces +/// go over an underlay of themselves ([`seals`]): the caller seals them ([`sealed_surface`], +/// [`sealed_runs`]) in the order it draws them; and whether the faces were left out. +#[allow(clippy::too_many_arguments, clippy::type_complexity)] fn surface( doc: Option<&Document>, n: &Node, @@ -480,7 +498,8 @@ fn surface( expand: bool, copies: &mut Copies, cast: bool, -) -> Option<(Vec, Node, Option, bool)> { + hide: bool, +) -> Option<(Vec, Node, Option, bool, bool)> { #[cfg(test)] crate::solids::SOLIDS_BUILT.with(|n| n.set(n.get() + 1)); // A loaded file or a profile edited past the limits keeps drawing its source path instead @@ -500,7 +519,23 @@ fn surface( let drawn = facets.iter().map(|f| Drawn { depth: f.depth, points: f.contours.first().cloned().unwrap_or_default(), plane: f.plane }).collect(); let p = merged_params(&fx.id, &fx.params); - return Some((drawn, crate::solids::classic::surface(n, facets, &paint, opacity, blend, &p), kept, false)); + // Mapped art goes on the side, the surface's one numbered surface. Its paints' copies + // count with the graphics', and art past the limits is left out. + let map_art = crate::solids::graphics::map_art::MapArt::of(doc, &fx.id, &p); + let layout = map_art.as_ref().and_then(|_| { + let (width, height) = vectorcraft_three_d::revolve_surface_size(path, b, options)?; + let side = vectorcraft_three_d::SolidSurface { kind: vectorcraft_three_d::SurfaceKind::Side, width, height, center: None }; + Some(crate::solids::graphics::map_art::SolidLayout { first: 0, surfaces: vec![side], ends: None }) + }); + let mut budget = crate::solids::graphics::map_art::MapBudget::default(); + let mapped = map_art.as_ref().zip(layout.as_ref()).map(|(art, layout)| crate::solids::classic::Mapped { + art, + layout, + budget: &mut budget, + copies: &mut copies.graphics, + }); + let (art, hidden, _) = crate::solids::classic::surface(n, &facets, &paint, (opacity, blend), &p, mapped, hide); + return Some((drawn, art, kept, false, hidden)); } let colored = colored(&options); let (faces, kept) = if cast { @@ -632,7 +667,7 @@ fn surface( let mut group = Node::group(n.id, children); group.opacity = opacity; group.blend = blend; - Some((keys, group, kept, seal)) + Some((keys, group, kept, seal, false)) } /// Plain `surface` ([`surface`]: a group of its faces) over an underlay of its faces when `seal` @@ -722,8 +757,8 @@ fn object_surface( let b = path.bounds()?; let (paint, opacity, blend) = paint_of(item); let cast = casts(fx, opacity); - surface(doc, n, path, b, rule_options(fx, rule), fx, paint, opacity, blend, expand, copies, cast) - .map(|(_, art, kept, seal)| (sealed_surface(n.id, art, seal), kept)) + surface(doc, n, path, b, rule_options(fx, rule), fx, paint, opacity, blend, expand, copies, cast, false) + .map(|(_, art, kept, seal, _)| (sealed_surface(n.id, art, seal), kept)) } /// The options effect `fx` sweeps the surface of a profile filled with `rule` with: its cut sides @@ -797,11 +832,12 @@ pub(crate) fn revolve_meshes(n: &Node, total: &mut usize, limit: usize) -> Resul } let (path, rule) = object_profile(n, "Revolve")?; let ctx = GeomContext::of(n); - let mesh = |path: &PathData, fx: &Effect, item: &AppearanceItem| -> Result { + let mut keep = |out: &mut Vec, path: &PathData, fx: &Effect, item: &AppearanceItem| -> Result<(), String> { let b = path.bounds().ok_or("Revolve requires a shape with at least two anchors")?; let (paint, opacity, _) = paint_of(item); - let mesh = vectorcraft_three_d::revolve_mesh(path, rule, b, fx_options(fx))?; - Ok(crate::SolidMesh::plain(mesh, crate::solids::mesh_color(&paint, opacity))) + surface_meshes(path, rule, b, fx, fx_options(fx), (&paint, opacity, 1.0), true)? + .into_iter() + .try_for_each(|m| crate::solids::keep_mesh(out, total, m, limit)) }; if let Some(index) = n.appearance.effects.iter().position(|e| e.visible && is_revolve(&e.id)) { let before = n.appearance.effects.get(..index).unwrap_or_default(); @@ -810,7 +846,7 @@ pub(crate) fn revolve_meshes(n: &Node, total: &mut usize, limit: usize) -> Resul let paints = solid_paints(n); let item = surface_item(&paints).ok_or("the revolved object has no fill or stroke")?; let mut out = vec![]; - crate::solids::keep_mesh(&mut out, total, mesh(&path, fx, item)?, limit)?; + keep(&mut out, &path, fx, item)?; return Ok(out); } let path = geometry(&path, &n.appearance.effects, &ctx); @@ -820,12 +856,69 @@ pub(crate) fn revolve_meshes(n: &Node, total: &mut usize, limit: usize) -> Resul && let Some(fx) = item.effects().get(index) { let p = geometry(&path, item.effects().get(..index).unwrap_or_default(), &ctx.item(item)); - crate::solids::keep_mesh(&mut out, total, mesh(&p, fx, item)?, limit)?; + keep(&mut out, &p, fx, item)?; } } Ok(out) } +/// The surface Revolve `fx` sweeps from `path` (filled under `rule`) about the axis of `b` with +/// `options`, painted `paint` at `opacity` in a group member of opacity `member` (1 for an object +/// of its own), as meshes. When `graphics` and `fx` maps graphics onto the side, the side's +/// triangles are a mesh of their own with the point of the unrolled side surface each corner shows +/// ([`crate::MeshGraphics`]), the points the canvas places the graphics by +/// ([`crate::solids::graphics::surface_parts`]), after a mesh of the rest (the end caps and the cut +/// sides). As on the canvas, the graphics take `opacity`, and `member` applies to the side and its +/// graphics together. Otherwise the surface is one plain mesh. +fn surface_meshes( + path: &PathData, + rule: FillRule, + b: Rect, + fx: &Effect, + options: Revolve, + (paint, opacity, member): (&Paint, f32, f32), + graphics: bool, +) -> Result, String> { + let color = crate::solids::mesh_color(paint, opacity * member); + let list: Vec = if graphics && fx.id == REVOLVE && options.map_surface { + crate::solids::mapped_graphics(&merged_params(&fx.id, &fx.params)).into_iter().filter(|g| g.face == crate::PlanarFace::Front).collect() + } else { + vec![] + }; + if list.is_empty() { + return Ok(vec![crate::SolidMesh::plain(vectorcraft_three_d::revolve_mesh(path, rule, b, options)?, color)]); + } + let (mesh, on) = vectorcraft_three_d::revolve_mesh_surface(path, rule, b, options)?; + let (mut side, mut rest, mut art) = (vectorcraft_three_d::Mesh::default(), vectorcraft_three_d::Mesh::default(), vec![]); + for (t, points) in mesh.triangles.iter().zip(&on) { + let corner = |i: u32| mesh.positions.get(i as usize).copied().zip(mesh.normals.get(i as usize).copied()); + let Some(corners) = t.iter().map(|&i| corner(i)).collect::>>() else { continue }; + let into = match points { + Some(points) => { + art.extend(points); + &mut side + } + None => &mut rest, + }; + let base = into.positions.len() as u32; + for (p, n) in corners { + into.positions.push(p); + into.normals.push(n); + } + into.triangles.push([base, base + 1, base + 2]); + } + let mut out = vec![]; + if !rest.is_empty() { + out.push(crate::SolidMesh::plain(rest, color)); + } + if !side.is_empty() { + let graphics = + crate::MeshGraphics { face: crate::PlanarFace::Front, graphics: list, center: Point::ZERO, art, opacity, object: member.clamp(0.0, 1.0) }; + out.push(crate::SolidMesh { mesh: side, color, graphics: Some(graphics) }); + } + Ok(out) +} + /// The outline of every face [`revolve_art`] draws for `n`'s Revolve or Revolve (Classic) (its symbol /// instances, blends and clipping groups already resolved), in document coordinates: with the /// effect on the object, the surface in its top visible fill (else its stroke); with it on fills and strokes, one surface for each of @@ -919,12 +1012,15 @@ fn group_meshes(n: &Node, total: &mut usize, limit: usize) -> Result, n: &Node, expand: bool) -> Option { let mut opaque = true; // The graphics go once, on the side of the member with the longest profile. Without graphics // no member is measured for them. - let mapped = fx.id == REVOLVE && !crate::solids::mapped_graphics(&merged_params(&fx.id, &fx.params)).is_empty(); + // Revolve (Classic)'s mapped art goes on that member's side too. + let p = merged_params(&fx.id, &fx.params); + let mapped = (fx.id == REVOLVE && !crate::solids::mapped_graphics(&p).is_empty()) + || (fx.id == CLASSIC_REVOLVE && !crate::solids::surface_maps(&p).is_empty()); let longest = if mapped { graphics_member(&shapes, b, options) } else { None }; - for (k, s) in shapes.iter().enumerate() { - let Some(item) = surface_item(&s.items) else { - kept.push(None); - continue; - }; + // Member `k`'s surface, its faces left out with `hide`, with its opacity and blending mode; + // `None` for a member with no fill or stroke. + let member = |k: usize, s: &Profile, hide: bool, copies: &mut Copies| { + let item = surface_item(&s.items)?; // The opacity and blending of the member and the groups it is in apply through its scopes. let (paint, opacity, blend) = paint_of(item); - opaque &= opacity >= 1.0 && blend == Default::default() && s.scopes.is_empty(); // A member with transparency of its own keeps every face, as a transparent object does. let expand = expand && s.scopes.is_empty(); let doc = doc.filter(|_| longest == Some(k)); let cast = casts(fx, opacity * s.opacity); let options = Revolve { fill_rule: s.rule, ..options }; - let (depths, art, faces, seal) = surface(doc, n, &s.path, b, options, fx, paint, opacity, blend, expand, &mut copies, cast)?; + Some((opacity, blend, surface(doc, n, &s.path, b, options, fx, paint, opacity, blend, expand, copies, cast, hide))) + }; + // With Invisible Geometry the other members leave their faces out too, once the mapped art on + // the longest member's side has left that member's faces out, so it is built first. + let invisible = fx.id == CLASSIC_REVOLVE && doc.is_some() && p.get(crate::solids::MAP_INVISIBLE).and_then(Value::as_bool).unwrap_or(false); + let mut first = None; + if let Some(l) = longest.filter(|_| invisible) + && let Some(s) = shapes.get(l) + { + first = member(l, s, false, &mut copies); + } + let hide = matches!(first, Some((_, _, Some((_, _, _, _, true))))); + for (k, s) in shapes.iter().enumerate() { + let built = if longest == Some(k) && first.is_some() { first.take() } else { member(k, s, hide, &mut copies) }; + let Some((opacity, blend, built)) = built else { + kept.push(None); + continue; + }; + opaque &= opacity >= 1.0 && blend == Default::default() && s.scopes.is_empty(); + let (depths, art, faces, seal, _) = built?; surfaces.push((depths, art, s.scopes.as_slice())); kept.push(faces); seals.push(seal); @@ -1870,8 +1986,9 @@ mod tests { let path = n.path_data().unwrap(); let fx = n.appearance.effects.first().unwrap(); let (paint, opacity, blend) = paint_of(n.appearance.items.first().unwrap()); - let (_, art, _, seal) = - surface(None, n, path, path.bounds().unwrap(), fx_options(fx), fx, paint, opacity, blend, false, &mut Copies::default(), false).unwrap(); + let (_, art, _, seal, _) = + surface(None, n, path, path.bounds().unwrap(), fx_options(fx), fx, paint, opacity, blend, false, &mut Copies::default(), false, false) + .unwrap(); (art, seal) } @@ -2129,7 +2246,7 @@ mod tests { .map(|s| { let (paint, opacity, blend) = paint_of(surface_item(&s.items).unwrap()); let cast = casts(&fx, opacity * s.opacity); - surface(None, &g, &s.path, b, options, &fx, paint, opacity, blend, false, &mut Copies::default(), cast).unwrap().2 + surface(None, &g, &s.path, b, options, &fx, paint, opacity, blend, false, &mut Copies::default(), cast, false).unwrap().2 }) .collect(); assert!(kept.iter().all(Option::is_some), "{id} {params}"); @@ -2165,7 +2282,7 @@ mod tests { .map(|s| { let (paint, opacity, blend) = paint_of(surface_item(&s.items).unwrap()); let cast = casts(&fx, opacity * s.opacity); - surface(None, g, &s.path, b, options, &fx, paint, opacity, blend, false, &mut Copies::default(), cast).unwrap().2 + surface(None, g, &s.path, b, options, &fx, paint, opacity, blend, false, &mut Copies::default(), cast, false).unwrap().2 }) .collect(); [group_shadow(g.id, &fx, &shapes, b, options, kept).unwrap(), group_shadow(g.id, &fx, &shapes, b, options, vec![]).unwrap()] diff --git a/crates/effects/src/revolve/classic.rs b/crates/effects/src/revolve/classic.rs index 4aefb13eef..97bfa67add 100644 --- a/crates/effects/src/revolve/classic.rs +++ b/crates/effects/src/revolve/classic.rs @@ -4,6 +4,8 @@ use serde_json::Value; use vectorcraft_three_d::Revolve; +use crate::solids::graphics::map_art; + pub const CLASSIC_REVOLVE: &str = "threeD.classicRevolve"; /// The numeric parameters: (key, lowest, highest, whole numbers only). @@ -23,19 +25,28 @@ const RANGES: [(&str, f64, f64, bool); 13] = [ ("blendSteps", 1.0, 256.0, true), ]; -const FLAGS: [&str; 3] = ["cap", "lightBehind", "preserveSpotColors"]; +const FLAGS: [&str; 5] = ["cap", "lightBehind", "preserveSpotColors", map_art::MAP_SHADE, map_art::MAP_INVISIBLE]; /// The surface Revolve (Classic)'s parameters `p` sweep: Revolve's angle, cap, offset, edge, -/// rotation and perspective, built unshaded, since the classic surfaces light its faces. +/// rotation and perspective, built unshaded, since the classic surfaces light its faces. With +/// mapped art its side is laid out for it. pub(crate) fn options(p: &Value) -> Revolve { - Revolve { shade: false, smooth_shading: false, lights: None, light_color: [1.0; 3], ..super::revolve_options(p) } + Revolve { + shade: false, + smooth_shading: false, + lights: None, + light_color: [1.0; 3], + map_surface: !map_art::surface_maps(p).is_empty(), + ..super::revolve_options(p) + } } /// Check Revolve (Classic)'s parameters `p` (its defaults filled in) beyond the checks it shares /// with Revolve: every key is one of its parameters, numbers are in range, flags are true or false, -/// and the surface and shading color are named. +/// the surface and shading color are named, and `mapArt` holds valid maps. pub(crate) fn validate(p: &Value) -> Result<(), String> { - crate::solids::classic::validate_classic(CLASSIC_REVOLVE, p, &RANGES, &FLAGS) + crate::solids::classic::validate_classic(CLASSIC_REVOLVE, p, &RANGES, &FLAGS)?; + map_art::validate(CLASSIC_REVOLVE, p) } #[cfg(test)] diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index 2bda4dc126..0ac1bbe416 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -24,6 +24,10 @@ mod source; pub(crate) use source::{resolve, resolve_for}; pub(crate) mod graphics; +pub use graphics::map_art::{ + MAP_ART, MAP_ART_NOT_TAKEN, MAP_INVISIBLE, MAP_SHADE, MAX_MAP_SURFACE, MAX_MAPS, SurfaceMap, surface_maps, takes_map_art, with_surface_map, +}; +use graphics::map_art::{MapArt, MapBudget, SolidLayout}; pub use graphics::{ GRAPHICS, GraphicFrame, MAX_GRAPHICS, MappedGraphic, MeshGraphics, graphic_symbols, mapped_graphics, mesh_graphics_art, missing_symbol, names_graphic_symbol, rename_graphic_symbol, rename_graphic_symbol_in, takes_graphics, with_graphic, @@ -32,6 +36,7 @@ pub use graphics::{ MAX_OFFSET as GRAPHIC_MAX_OFFSET, NOT_TAKEN as GRAPHICS_NOT_TAKEN, SCALE_RANGE as GRAPHIC_SCALE_RANGE, appearance_graphic_symbols, fitting as graphic_fitting_scale, rename_appearance_graphic_symbol, }; +pub use vectorcraft_three_d::SurfaceKind; pub(crate) mod shadow; @@ -180,6 +185,7 @@ pub fn extrude_options(p: &Value) -> Extrude { both_sides: flag(p, "bevelBothSides", false), }), hidden: false, + map_surfaces: false, map_surface: false, } } @@ -431,11 +437,22 @@ fn visible(item: &AppearanceItem, member: f32) -> bool { /// ([`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. +/// included. On Extrude & Bevel (Classic), the art Map Art places on walls and bevels must also fit +/// ([`graphics::validate_unrolled_symbols`]). 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); + // Map Art unrolls its art onto walls and bevels; the caps draw it as it is. + if id == CLASSIC_EXTRUDE && !surface_maps(p).is_empty() { + let options = vectorcraft_three_d::Extrude { map_surfaces: true, ..classic_extrude_options(p) }; + let unrolled: Vec> = parts + .iter() + .flat_map(|(_, _, area, rule, _, _)| vectorcraft_three_d::extrude_surfaces(area, *rule, bounds, options).unwrap_or_default()) + .map(|s| (!matches!(s.kind, SurfaceKind::End(_))).then(|| graphics::map_art::flat_center(&s))) + .collect(); + graphics::validate_unrolled_symbols(doc, p, &|surface| surface.checked_sub(1).and_then(|k| unrolled.get(k).copied().flatten()))?; + } if side_carrier(id, p, &parts, bounds).is_none() { return Ok(()); } @@ -1924,8 +1941,11 @@ fn surfaces_with(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profil filled.push(Filled { at: out.len(), member, caps, opacity, blend, masked: masks_surface(&paint, colored) }); } } - let art = - if classic { classic::surface(n, f, &paint, opacity, blend, &p) } else { surface(n, f, &paint, opacity, blend, colored, false) }; + let art = if classic { + classic::surface(n, &f, &paint, (opacity, blend), &p, None, false).0 + } else { + surface(n, f, &paint, opacity, blend, colored, false) + }; out.push((s.scopes.as_slice(), Arc::new(art))); } } @@ -1939,15 +1959,28 @@ fn surfaces_with(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profil let carrier = if graphics_on { side_carrier(&fx.id, &p, &parts, bounds) } else { None }; let mut solids = vec![]; let mut built = vec![]; + // With mapped art, each solid's place among the object's numbered surfaces: the surfaces are + // counted through the parts in order, those of a part whose solid is left out too. + let map_art = MapArt::of(doc, &fx.id, &p).filter(|_| fx.id == CLASSIC_EXTRUDE); + let mut layouts: Vec = vec![]; + let mut surfaces_before = 0usize; 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() { + for (k, ((item, opacity, area, rule, scopes, member), f)) in parts.iter().zip(made).enumerate() { let item: &AppearanceItem = item; + let layout = map_art.as_ref().map(|_| { + let options = classic_extrude_options(&p); + let surfaces = vectorcraft_three_d::extrude_surfaces(area, *rule, bounds, options).unwrap_or_default(); + let first = surfaces_before; + surfaces_before += surfaces.len(); + SolidLayout { first, surfaces, ends: Some((bounds, options, view_options(&p))) } + }); match f { Ok(Some((f, _))) if !crate::revolve::paint_copies_add(&mut paint_bytes, facet_copies(&f, paint_ref(item), colored), paint_ref(item)) => { return None; } Ok(Some((f, faces))) => { solids.push((item, *opacity, *scopes, f, *member)); + layouts.extend(layout); built.push(faces); } // A stroke's outline past the limits is left out; the fill's solid still draws, and @@ -2035,6 +2068,34 @@ fn surfaces_with(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profil let split = split && solids.iter().filter(|(item, _, _, f, _)| composite(item, f)).map(|(.., f, _)| f.len()).sum::() <= MAX_FACE_COMPOSITES; let members: Vec = solids.iter().map(|s| s.4).collect(); + // The classic surfaces of the solids, with mapped art when the effect has maps. When the art of + // any solid is past the limits the object's maps share, every solid draws without mapped art. + let mut classic_arts = if classic { + let draw = |with_art: bool, copies: &mut usize| { + let mut budget = MapBudget::default(); + let mut dropped = false; + let mut arts = Vec::with_capacity(solids.len()); + for (k, (item, member, _, f, _)) in solids.iter().enumerate() { + let (paint, opacity, blend) = paint_of(item, *member); + let mapped = map_art.as_ref().filter(|_| with_art).zip(layouts.get(k)).map(|(art, layout)| classic::Mapped { + art, + layout, + budget: &mut budget, + copies: &mut *copies, + }); + let (art, _, left_out) = classic::surface(n, f, &paint, (opacity, blend), &p, mapped, false); + dropped |= left_out; + arts.push(art); + } + (arts, dropped) + }; + let mut used = paint_bytes; + let (arts, dropped) = draw(map_art.is_some(), &mut used); + if dropped { draw(false, &mut paint_bytes).0 } else { arts } + } else { + vec![] + } + .into_iter(); // Which surfaces lie over an underlay of their facets, in one order or whole // ([`in_one_order`], [`underlaid_surface`]). let seals: Vec = solids.iter().map(|(.., f, _)| underlaid(f, colored)).collect(); @@ -2061,7 +2122,7 @@ fn surfaces_with(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profil }; let drawn = parts.iter().any(|p| !p.is_empty()); let art = if classic { - classic::surface(n, f, &paint, opacity, blend, &p) + classic_arts.next().unwrap_or_else(|| Node::group(n.id, vec![])) } else { 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) @@ -2391,28 +2452,7 @@ pub fn graphic_side_size(doc: Option<&Document>, n: &Node, item: Option, /// 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())?; - let mut shapes = members(n, "").ok()?; - reshape_members(n, n.appearance.effects.get(..index)?, &mut shapes); - (fx, shapes) - } else { - let (path, rule) = profile(n)?; - let ctx = GeomContext::of(n); - match item { - None => { - let (index, fx) = pick(&n.appearance.effects)?; - let path = geometry(&path, n.appearance.effects.get(..index)?, &ctx); - (fx, vec![Profile { path, rule, items: solid_paints(n), opacity: 1.0, scopes: vec![] }]) - } - Some(k) => { - let it = n.appearance.items.get(k)?; - let (index, fx) = pick(it.effects())?; - let path = geometry(&geometry(&path, &n.appearance.effects, &ctx), it.effects().get(..index)?, &ctx.item(it)); - (fx, vec![Profile { path, rule, items: vec![it.clone()], opacity: 1.0, scopes: vec![] }]) - } - } - }; + let (fx, shapes) = picked(n, item, pick)?; Some((fx.clone(), shapes)) } @@ -2459,6 +2499,175 @@ fn frame_of(doc: Option<&Document>, n: &Node, item: Option, pick: &Pick<' }) } +/// One numbered surface of a 3D object that takes Map Art: what it is, its size laid out flat in +/// points, whether the viewer sees any of it, and the edges of its outline on the page. +#[derive(Clone, Debug, PartialEq)] +pub struct MapSurface { + pub kind: SurfaceKind, + pub width: f64, + pub height: f64, + pub visible: bool, + pub outline: Vec<[Point; 2]>, +} + +/// The numbered surfaces of the 3D effect at `index` of the effects of `n` (on the object itself +/// with `item` `None`, else on its fill or stroke `item`), which must be an Extrude & Bevel +/// (Classic) or Revolve (Classic), shown or hidden, in the order Map Art numbers them from 1. +/// `None` for any other effect, and when the object's art can't be built. +pub fn map_surfaces_at(doc: Option<&Document>, n: &Node, item: Option, index: usize) -> Option> { + let n = &*resolve(doc, n, "").ok()?; + let (fx, shapes) = picked(n, item, &|fx: &[Effect]| fx.get(index).filter(|e| takes_map_art(&e.id)).map(|e| (index, e)))?; + let p = crate::merged_params(&fx.id, &fx.params); + let b = union_bounds(&shapes)?; + // The edges of `facets` on each local surface of `surfaces`, in one pass over the facets: every + // edge of an end, and the edges of the cells that lie along the sides of the flat surface. + let seen = |surfaces: &[vectorcraft_three_d::SolidSurface], facets: &[Facet]| -> Vec> { + let mut edges: Vec> = vec![vec![]; surfaces.len()]; + // Each surface laid out flat, and how near a point must be to its side to lie along it. + let frames: Vec<(Rect, f64)> = surfaces + .iter() + .map(|s| { + let flat = match s.kind { + SurfaceKind::Side => Rect::new(-s.width / 2.0, -s.height / 2.0, s.width / 2.0, s.height / 2.0), + _ => Rect::new(0.0, 0.0, s.width, s.height), + }; + (flat, (s.width.max(s.height) * 1e-6).max(1e-9)) + }) + .collect(); + let ends: Vec<(usize, PlanarFace)> = surfaces + .iter() + .enumerate() + .filter_map(|(k, s)| match s.kind { + SurfaceKind::End(end) => Some((k, end)), + _ => None, + }) + .collect(); + for f in facets.iter().filter(|f| !f.away) { + if let Some(at) = f.end { + for &(k, end) in &ends { + if end == at + && let Some(out) = edges.get_mut(k) + { + for c in &f.contours { + out.extend(c.iter().zip(c.iter().cycle().skip(1)).take(c.len()).map(|(a, b)| [*a, *b])); + } + } + } + } + let Some(cell) = f.cell.as_deref().filter(|c| c.uv.len() == c.page.len()) else { continue }; + let k = cell.surface; + // A facet of an end adds to an end's surface only its own edges, above. + if f.end.is_some() && surfaces.get(k).is_some_and(|s| matches!(s.kind, SurfaceKind::End(_))) { + continue; + } + let (Some(&(flat, near)), Some(out)) = (frames.get(k), edges.get_mut(k)) else { continue }; + let count = cell.uv.len(); + for i in 0..count { + let j = (i + 1) % count; + let (Some(a), Some(c)) = (cell.uv.get(i), cell.uv.get(j)) else { continue }; + let along = |at: f64, of: fn(&Point) -> f64| (of(a) - at).abs() <= near && (of(c) - at).abs() <= near; + let on_side = along(flat.x0, |p| p.x) || along(flat.x1, |p| p.x) || along(flat.y0, |p| p.y) || along(flat.y1, |p| p.y); + if let (true, Some(from), Some(to)) = (on_side, cell.page.get(i), cell.page.get(j)) { + out.push([*from, *to]); + } + } + } + edges + }; + let listed = |surfaces: &[vectorcraft_three_d::SolidSurface], facets: &[Facet], out: &mut Vec| { + for (s, outline) in surfaces.iter().zip(seen(surfaces, facets)) { + out.push(MapSurface { kind: s.kind, width: s.width, height: s.height, visible: !outline.is_empty(), outline }); + } + }; + let mut out = vec![]; + if fx.id == crate::CLASSIC_REVOLVE { + // Revolve (Classic) has one surface: its side, in a group that of the member with the + // longest profile. A group's members share one sampling of their curves, and a group past + // those shared limits has no surface. + let mut options = vectorcraft_three_d::Revolve { map_surface: true, ..crate::revolve::options_of(&fx.id, &p) }; + if is_container(n) { + options = crate::revolve::shared_options(&shapes, options).ok()?; + } + let shape = shapes.get(crate::revolve::graphics_member(&shapes, b, options)?)?; + let (width, height) = vectorcraft_three_d::revolve_surface_size(&shape.path, b, options)?; + let surfaces = [vectorcraft_three_d::SolidSurface { kind: SurfaceKind::Side, width, height, center: None }]; + let facets = vectorcraft_three_d::revolve_facets(&shape.path, b, options).unwrap_or_default(); + listed(&surfaces, &facets, &mut out); + return Some(out); + } + let (parts, bounds) = solid_parts(&shapes, b); + let options = vectorcraft_three_d::Extrude { map_surfaces: true, ..classic_extrude_options(&p) }; + let view = view_options(&p); + // The faces of the solids count together against the limit the art draws within. + let mut kept = 0usize; + for (_, _, area, rule, _, _) in &parts { + let surfaces = vectorcraft_three_d::extrude_surfaces(area, *rule, bounds, options).unwrap_or_default(); + let facets = vectorcraft_three_d::extrude(area, *rule, bounds, options, view).unwrap_or_default(); + kept = kept.saturating_add(facets.len()); + if kept > MAX_OBJECT_FACES { + return None; + } + listed(&surfaces, &facets, &mut out); + } + Some(out) +} + +/// [`map_surfaces_at`] for `n` as it is with 3D effect `id` and parameters `p` among the effects of +/// the object itself (`item` `None`) or of its fill or stroke `item`: in place of the effect at +/// `index` when that is an effect `id`, else of the last effect `id` there, or after those effects +/// when there is none. A dialog lists the surfaces of the effect it edits with this, whether or not +/// its preview has changed the object. +pub fn map_surfaces_with( + doc: Option<&Document>, + n: &Node, + (item, index): (Option, Option), + id: &str, + p: &Value, +) -> Option> { + let mut n = n.clone(); + let effects = n.appearance.effects_mut(item)?; + let at = index.filter(|&k| effects.get(k).is_some_and(|e| e.id == id)).or_else(|| effects.iter().rposition(|e| e.id == id)); + let index = match at { + Some(index) => { + effects.get_mut(index)?.params = p.clone(); + index + } + None => { + effects.push(crate::new_effect(id, p)?); + effects.len() - 1 + } + }; + map_surfaces_at(doc, &n, item, index) +} + +/// The 3D effect `pick` finds in the effects of `n` (resolved) or of its `item`, with the shapes +/// it builds from: the members of a group or layer, or the object's own profile after the geometry +/// effects before the 3D effect. +fn picked<'n>(n: &'n Node, item: Option, pick: &Pick<'_>) -> Option<(&'n Effect, Vec)> { + Some(if is_container(n) { + let (index, fx) = pick(&n.appearance.effects).filter(|_| item.is_none())?; + let mut shapes = members(n, "").ok()?; + reshape_members(n, n.appearance.effects.get(..index)?, &mut shapes); + (fx, shapes) + } else { + let (path, rule) = profile(n)?; + let ctx = GeomContext::of(n); + match item { + None => { + let (index, fx) = pick(&n.appearance.effects)?; + let path = geometry(&path, n.appearance.effects.get(..index)?, &ctx); + (fx, vec![Profile { path, rule, items: solid_paints(n), opacity: 1.0, scopes: vec![] }]) + } + Some(k) => { + let it = n.appearance.items.get(k)?; + let (index, fx) = pick(it.effects())?; + let path = geometry(&geometry(&path, &n.appearance.effects, &ctx), it.effects().get(..index)?, &ctx.item(it)); + (fx, vec![Profile { path, rule, items: vec![it.clone()], opacity: 1.0, scopes: vec![] }]) + } + } + }) +} + /// The bounds of the art symbol `name` of `doc` draws as a graphic, in the symbol's coordinates. pub fn graphic_bounds(doc: &Document, name: &str) -> Option { graphics::art_bounds(doc, name) @@ -2501,8 +2710,8 @@ impl SolidMesh { /// The parts of `mesh`, a solid that 3D effect `id` with parameters `p` built about `bounds`, painted /// `color` from a fill or stroke at `opacity`: for each planar face that carries graphics (Extrude & /// Bevel's caps, the plane), the triangles on it as a mesh of their own with the art point of each -/// corner ([`MeshGraphics`]), then the rest. Revolve's side, whose graphics are not mapped onto its -/// mesh, stays plain. +/// corner ([`MeshGraphics`]), then the rest. Revolve's meshes are split by their side instead +/// (`revolve::surface_meshes`), so a Revolve's mesh stays plain here. fn split_graphics(id: &str, p: &Value, bounds: Rect, mesh: Mesh, (color, opacity): ([f32; 4], f32)) -> Vec { let list = graphics::mapped_graphics(p); if list.is_empty() || !takes_graphics(id) || id == crate::REVOLVE { diff --git a/crates/effects/src/solids/classic.rs b/crates/effects/src/solids/classic.rs index 79d87fdb25..609743fe03 100644 --- a/crates/effects/src/solids/classic.rs +++ b/crates/effects/src/solids/classic.rs @@ -9,6 +9,7 @@ use vectorcraft_doc::{Appearance, AppearanceItem, FillLayer, Node}; use vectorcraft_geom::Rect; use vectorcraft_three_d::{Bevel, BevelShape, ClassicShading, ClassicSurface, Extrude, Facet, Light}; +use super::graphics::map_art::{self, MapArt, MapBudget, SolidLayout}; use crate::util::{flag, num, text}; pub const CLASSIC_EXTRUDE: &str = "threeD.classicExtrude"; @@ -51,10 +52,21 @@ pub fn classic_extrude_options(p: &Value) -> Extrude { ..Bevel::default() }), hidden: flag(p, "drawHiddenFaces", false) || classic_shading(p).surface == ClassicSurface::Wireframe, + // The numbered surfaces are laid out only for an effect that maps art onto them. + map_surfaces: !map_art::surface_maps(p).is_empty(), ..Extrude::default() } } +/// The mapped art of one solid for [`surface`]: the effect's maps, the solid's place among the +/// object's numbered surfaces, and the limits the object's mapped art shares. +pub(crate) struct Mapped<'a, 'd> { + pub(crate) art: &'a MapArt<'d>, + pub(crate) layout: &'a SolidLayout, + pub(crate) budget: &'a mut MapBudget, + pub(crate) copies: &'a mut usize, +} + /// The color faces darken toward: black (for Black Overprint too), the custom color, or none (faces /// keep their paint and only the highlight lightens them). fn shading_color(p: &Value) -> Option { @@ -102,13 +114,15 @@ const RANGES: [(&str, f64, f64, bool); 13] = [ ("blendSteps", 1.0, 256.0, true), ]; -const FLAGS: [&str; 5] = ["cap", "bevelInside", "lightBehind", "drawHiddenFaces", "preserveSpotColors"]; +const FLAGS: [&str; 7] = ["cap", "bevelInside", "lightBehind", "drawHiddenFaces", "preserveSpotColors", map_art::MAP_SHADE, map_art::MAP_INVISIBLE]; /// Check Extrude & Bevel (Classic)'s parameters `p` (its defaults filled in): every key is one of -/// its parameters, numbers are in range, flags are true or false, and `surface`, `shadingColor` and -/// `shadingCustom` name a surface, a shading color and a #rrggbb color. +/// its parameters, numbers are in range, flags are true or false, `surface`, `shadingColor` and +/// `shadingCustom` name a surface, a shading color and a #rrggbb color, and `mapArt` holds valid +/// maps. pub fn validate(p: &Value) -> Result<(), String> { - validate_classic(CLASSIC_EXTRUDE, p, &RANGES, &FLAGS) + validate_classic(CLASSIC_EXTRUDE, p, &RANGES, &FLAGS)?; + map_art::validate(CLASSIC_EXTRUDE, p) } /// Rotate (Classic)'s numeric parameters: (key, lowest, highest, whole numbers only). @@ -261,66 +275,67 @@ pub(crate) fn stroke_width(face: &Facet, p: &Value) -> f64 { /// is shaded opaque and then masked by its own transparency, so the shading follows the gradient's /// coverage; without a placement of its own, it is placed once on all the faces /// ([`crate::lighting::opaque_surface_paint`]). -pub(crate) fn surface(n: &Node, facets: Vec, source: &Paint, opacity: f32, blend: BlendMode, p: &Value) -> Node { +/// +/// With `mapped`, a face that carries mapped art is a group of the face and that art, which the +/// surface's opacity mask covers too. Shade Artwork gives the art its face's tone and highlight, +/// and Invisible Geometry leaves the faces out: a face is then a group of its art alone. Wireframe +/// draws no mapped art. Without `mapped`, `hide` leaves the faces out the same way, for a solid +/// that shares Invisible Geometry with another solid's mapped art; Wireframe still draws. +/// +/// Returns the group, whether its faces were left out, and whether `mapped` art was left out past +/// the limits. +pub(crate) fn surface( + n: &Node, + facets: &[Facet], + source: &Paint, + (opacity, blend): (f32, BlendMode), + p: &Value, + mapped: Option>, + hide: bool, +) -> (Node, bool, bool) { let shading = classic_shading(p); let lights = lights(p); let shade = shading_color(p); let preserve = preserves_spot_colors(p); let overprint = black_overprint(p); let wire = shading.surface == ClassicSurface::Wireframe; - let (paint, mask) = if wire { (source.clone(), None) } else { crate::lighting::opaque_surface_paint(source, || super::facets_bounds(&facets)) }; + let (paint, mask) = if wire { (source.clone(), None) } else { crate::lighting::opaque_surface_paint(source, || super::facets_bounds(facets)) }; let paint = &paint; + // The mapped art of each facet, and whether the faces themselves are left out. Art past the + // limits is left out, and the faces draw; the copies and the points of art left out do not + // count against the art of later solids. + let (mut parts, invisible, dropped) = match mapped.filter(|_| !wire) { + Some(m) => { + let shaded_as = |f: &Facet, c: Color| { + let (tone, spec) = shading.tone(f.normal, &lights); + shaded(c, tone, spec, shade) + }; + let (mut used, mut budget) = (*m.copies, m.budget.clone()); + match m.art.parts(n.id, facets, m.layout, &shaded_as, &mut budget, &mut used) { + Some(parts) => { + (*m.copies, *m.budget) = (used, budget); + (parts, m.art.invisible, false) + } + None => (vec![], false, true), + } + } + None => (vec![], hide && !wire, false), + }; let children = facets - .into_iter() - .map(|face| { + .iter() + .enumerate() + .map(|(k, face)| { + let art = parts.get_mut(k).map(std::mem::take).unwrap_or_default(); + if !art.is_empty() || invisible { + let drawn = (!invisible).then(|| Arc::new(shaded_face(n, face, paint, &shading, &lights, shade, preserve, overprint))); + return Arc::new(Node::group(n.id, drawn.into_iter().chain(art).collect())); + } if wire { // A wire edge is drawn as a seam is: a round-joined stroke of the paint. let edge = crate::lighting::seam_stroke(paint.clone(), WIRE); return Arc::new(Node::path(n.id, face.path(), Appearance { items: vec![AppearanceItem::Stroke(edge)], ..Default::default() })); } - let (tone, spec) = shading.tone(face.normal, &lights); - // A narrow stroke of the face's own paint closes the hairline seams between faces. - let seam = super::seam_width(&face); - if overprint { - let items = overprinted_face(paint, tone, seam); - return Arc::new(Node::path(n.id, face.path(), Appearance { items, ..Default::default() })); - } - let items = match paint.color() { - // Unshaded (No Shading, no shading color, or a face in full light) with no - // highlight: the paint itself, its color space and swatch kept. - Some(_) if (tone >= 1.0 || shade.is_none()) && spec <= 0.0 => { - vec![ - AppearanceItem::Fill(FillLayer::new(paint.clone())), - AppearanceItem::Stroke(crate::lighting::seam_stroke(paint.clone(), seam)), - ] - } - // Preserve Spot Colors: a color linked to a swatch stays a tint of that swatch. - Some(_) if preserve && matches!(paint, Paint::Solid { swatch: Some(_), .. }) && !paint.is_registration() => { - linked_face(paint, tone, spec, shade, seam) - } - Some(c) => { - let fill = Paint::solid(shaded(c, tone, spec, shade)); - vec![AppearanceItem::Fill(FillLayer::new(fill.clone())), AppearanceItem::Stroke(crate::lighting::seam_stroke(fill, seam))] - } - // Gradients and patterns keep their paint, darkened by a layer of the shading color - // and lightened by one of white. As with the other 3D effects' pattern shadow, the - // layers cover the whole face, transparent pattern cells included. - None => { - let mut items = vec![ - AppearanceItem::Fill(FillLayer::new(paint.clone())), - AppearanceItem::Stroke(crate::lighting::seam_stroke(paint.clone(), seam)), - ]; - for (color, share) in [(shade, 1.0 - tone), (Some(Color::WHITE), spec)] { - if let Some(color) = color.filter(|_| share > 0.0) { - let mut layer = FillLayer::new(Paint::solid(color)); - layer.opacity = share as f32; - items.push(AppearanceItem::Fill(layer)); - } - } - items - } - }; - Arc::new(Node::path(n.id, face.path(), Appearance { items, ..Default::default() })) + Arc::new(shaded_face(n, face, paint, &shading, &lights, shade, preserve, overprint)) }) .collect(); let mut group = Node::group(n.id, children); @@ -331,5 +346,61 @@ pub(crate) fn surface(n: &Node, facets: Vec, source: &Paint, opacity: f32 let coverage = Node::path(n.id, vectorcraft_geom::shapes::rectangle(bounds), Appearance::basic(mask, Paint::None, 0.0)); group.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(coverage, true))); } - group + (group, invisible, dropped) +} + +/// One face of a solid in paint `paint` (opaque: [`surface`] masks a gradient's transparency), +/// filled in the paint shaded by the face's tone and highlight under `lights`, toward shading +/// color `shade`. With `preserve` (Preserve Spot Colors), a color linked to a swatch is drawn as +/// [`linked_face`] draws it. With `overprint` (Black Overprint), the face is drawn as +/// [`overprinted_face`] draws it. +#[allow(clippy::too_many_arguments)] +fn shaded_face( + n: &Node, + face: &Facet, + paint: &Paint, + shading: &ClassicShading, + lights: &[([f64; 3], f64)], + shade: Option, + preserve: bool, + overprint: bool, +) -> Node { + let (tone, spec) = shading.tone(face.normal, lights); + // A narrow stroke of the face's own paint closes the hairline seams between faces. + let seam = super::seam_width(face); + if overprint { + let items = overprinted_face(paint, tone, seam); + return Node::path(n.id, face.path(), Appearance { items, ..Default::default() }); + } + let items = match paint.color() { + // Unshaded (No Shading, no shading color, or a face in full light) with no + // highlight: the paint itself, its color space and swatch kept. + Some(_) if (tone >= 1.0 || shade.is_none()) && spec <= 0.0 => { + vec![AppearanceItem::Fill(FillLayer::new(paint.clone())), AppearanceItem::Stroke(crate::lighting::seam_stroke(paint.clone(), seam))] + } + // Preserve Spot Colors: a color linked to a swatch stays a tint of that swatch. + Some(_) if preserve && matches!(paint, Paint::Solid { swatch: Some(_), .. }) && !paint.is_registration() => { + linked_face(paint, tone, spec, shade, seam) + } + Some(c) => { + let fill = Paint::solid(shaded(c, tone, spec, shade)); + vec![AppearanceItem::Fill(FillLayer::new(fill.clone())), AppearanceItem::Stroke(crate::lighting::seam_stroke(fill, seam))] + } + // Gradients and patterns keep their paint, darkened by a layer of the shading color + // and lightened by one of white. As with the other 3D effects' pattern shadow, the + // layers cover the whole face, transparent pattern cells included. + None => { + let mut items = + vec![AppearanceItem::Fill(FillLayer::new(paint.clone())), AppearanceItem::Stroke(crate::lighting::seam_stroke(paint.clone(), seam))]; + for (color, share) in [(shade, 1.0 - tone), (Some(Color::WHITE), spec)] { + if let Some(color) = color.filter(|_| share > 0.0) { + let mut layer = FillLayer::new(Paint::solid(color)); + layer.opacity = share as f32; + items.push(AppearanceItem::Fill(layer)); + } + } + items + } + }; + Node::path(n.id, face.path(), Appearance { items, ..Default::default() }) } diff --git a/crates/effects/src/solids/graphics.rs b/crates/effects/src/solids/graphics.rs index bf4a71ace7..66358df431 100644 --- a/crates/effects/src/solids/graphics.rs +++ b/crates/effects/src/solids/graphics.rs @@ -170,6 +170,8 @@ pub fn mapped_graphics(p: &Value) -> Vec { /// Revolve take graphics; a plane has only a front, and Revolve's graphics go on its side, named /// the front. Only Extrude & Bevel takes graphics on its side. pub fn validate(id: &str, p: &Value) -> Result<(), String> { + // Map Art's maps are checked with the graphics: an effect that takes none refuses them. + map_art::validate(id, p)?; let list = match p.get(GRAPHICS) { None => return Ok(()), Some(Value::Array(list)) => list, @@ -200,21 +202,23 @@ pub fn validate(id: &str, p: &Value) -> Result<(), String> { /// graphics in `old` (the effect's parameters before an edit) already name: a graphic whose symbol /// was deleted may stay. pub fn missing_symbol(doc: &Document, p: &Value, old: Option<&Value>) -> Option { - let kept = old.map(mapped_graphics).unwrap_or_default(); - mapped_graphics(p) - .into_iter() - .map(|g| g.symbol) - .find(|name| !doc.symbols.iter().any(|s| s.name == *name) && !kept.iter().any(|g| g.symbol == *name)) + let names = |p: &Value| -> Vec { + mapped_graphics(p).into_iter().map(|g| g.symbol).chain(map_art::surface_maps(p).into_iter().map(|m| m.symbol)).collect() + }; + let kept = old.map(names).unwrap_or_default(); + names(p).into_iter().find(|name| !doc.symbols.iter().any(|s| s.name == *name) && !kept.contains(name)) } /// Does the art of the symbols the graphics in `p` name fit the limits? A graphic whose symbol /// `doc` does not have draws nothing and is not counted. With a perspective, each curve counts as -/// the [`PERSPECTIVE_PIECES`] pieces it is cut into; without one, it counts once. +/// the [`PERSPECTIVE_PIECES`] pieces it is cut into; without one, it counts once. The symbols Map +/// Art places count with the graphics. pub fn validate_symbols(doc: &Document, p: &Value) -> Result<(), String> { let curve = if super::view_options(p).perspective > 0.0 { PERSPECTIVE_PIECES } else { 1 }; let mut elements = 0usize; - for g in mapped_graphics(p) { - let Some(symbol) = doc.symbols.iter().find(|s| s.name == g.symbol) else { continue }; + let names = mapped_graphics(p).into_iter().map(|g| g.symbol).chain(map_art::surface_maps(p).into_iter().map(|m| m.symbol)); + for name in names { + let Some(symbol) = doc.symbols.iter().find(|s| s.name == name) else { continue }; let pieces = pieces_of(doc, symbol)?; elements = elements.saturating_add(pieces.iter().map(|p| drawn_elements(&p.path, curve)).sum()); if elements > MAX_ELEMENTS { @@ -224,6 +228,30 @@ pub fn validate_symbols(doc: &Document, p: &Value) -> Result<(), String> { Ok(()) } +/// Does the art Map Art in `p` places on the surfaces that `unrolled` gives a flat center for (by +/// number, from 1; [`map_art::flat_center`]), with the symbols of `doc`, fit the limits as a wall, a +/// bevel or Revolve's side draws it: each map's art placed about that center at its scale, cut into +/// straight pieces, at most [`MAX_ELEMENTS`] points together and within reach? A map whose symbol +/// `doc` does not have is not counted. +pub fn validate_unrolled_symbols(doc: &Document, p: &Value, unrolled: &dyn Fn(usize) -> Option) -> Result<(), String> { + const TOO_COMPLEX: &str = "The graphics are too complex: simplify the symbols' art"; + let mut points = 0usize; + for m in map_art::surface_maps(p) { + let Some(center) = unrolled(m.surface) else { continue }; + let Some(symbol) = doc.symbols.iter().find(|s| s.name == m.symbol) else { continue }; + let pieces = pieces_of(doc, symbol)?; + let Some(bounds) = pieces.iter().filter_map(|p| p.path.bounds()).reduce(|a, b| a.union(b)) else { continue }; + let place = m.placement(bounds, center, false); + for piece in &pieces { + straight_pieces(&(place * piece.path.to_bezpath()), &mut points).ok_or(TOO_COMPLEX)?; + } + if points > MAX_ELEMENTS { + return Err(TOO_COMPLEX.into()); + } + } + Ok(()) +} + /// The path elements `path` draws when each curve draws `curve` elements, before curves near the /// eye are split further: one for each straight line, move and close. fn drawn_elements(path: &PathData, curve: usize) -> usize { @@ -844,7 +872,12 @@ pub(crate) fn surface_parts( for k in near { let Some(piece) = pieces.get(k) else { continue }; let mut path = BezPath::new(); - // Each contour is cut only where its own bounds reach the triangle. + // Each contour is cut only where its own bounds reach the triangle. Each bounds test + // counts as one point cut, whether or not the contour reaches it. + cut_points = cut_points.saturating_add(piece.boxes.len()); + if cut_points > MAX_SURFACE_CUTS { + return None; + } for (polygon, b) in piece.polygons.iter().zip(&piece.boxes) { if b.x1 < reach.x0 || b.x0 > reach.x1 || b.y1 < reach.y0 || b.y0 > reach.y1 { continue; @@ -1225,9 +1258,11 @@ pub fn appearance_graphic_symbols(appearance: &Appearance) -> Vec { std::iter::once(&appearance.effects) .chain(appearance.items.iter().map(AppearanceItem::effects)) .flatten() - .filter(|e| takes_graphics(&e.id)) - .flat_map(|e| mapped_graphics(&e.params)) - .map(|g| g.symbol) + .filter(|e| takes_graphics(&e.id) || map_art::takes_map_art(&e.id)) + .flat_map(|e| { + let graphics = mapped_graphics(&e.params).into_iter().map(|g| g.symbol).filter(|_| takes_graphics(&e.id)); + graphics.chain(map_art::surface_maps(&e.params).into_iter().map(|m| m.symbol).filter(|_| map_art::takes_map_art(&e.id))) + }) .collect() } @@ -1247,8 +1282,15 @@ pub fn rename_appearance_graphic_symbol(appearance: &mut Appearance, from: &str, let (effects, items) = (&mut appearance.effects, &mut appearance.items); lists.push(effects); lists.extend(items.iter_mut().map(AppearanceItem::effects_mut)); - for e in lists.into_iter().flatten().filter(|e| takes_graphics(&e.id)) { - if let Some(Value::Array(list)) = e.params.get_mut(GRAPHICS) { + for e in lists.into_iter().flatten() { + let key = if takes_graphics(&e.id) { + GRAPHICS + } else if map_art::takes_map_art(&e.id) { + map_art::MAP_ART + } else { + continue; + }; + if let Some(Value::Array(list)) = e.params.get_mut(key) { for g in list.iter_mut() { if g.get("symbol").and_then(Value::as_str) == Some(from) { g["symbol"] = json!(to); @@ -1294,6 +1336,9 @@ pub fn with_graphic(p: &Value, g: &MappedGraphic) -> Value { Value::Object(out) } +#[path = "map_art.rs"] +pub(crate) mod map_art; + #[cfg(test)] #[path = "tests_graphics.rs"] mod tests; diff --git a/crates/effects/src/solids/map_art.rs b/crates/effects/src/solids/map_art.rs new file mode 100644 index 0000000000..3e395a6d03 --- /dev/null +++ b/crates/effects/src/solids/map_art.rs @@ -0,0 +1,781 @@ +//! Map Art: the art of a document symbol mapped onto the numbered surfaces of Extrude & Bevel +//! (Classic) and Revolve (Classic). +//! +//! The effect keeps its maps in its `mapArt` parameter, each `{surface, symbol, x, y, scaleX, +//! scaleY, rotation}`: the surface's number (from 1), the symbol's name, the offset of the art's +//! center from the center of the surface laid out flat (points, x to the right and y down as the +//! surface is seen from outside the solid), its size as a share of the symbol's own, and its turn +//! (degrees, counterclockwise). `mapShade` shades the mapped art with its surface, and +//! `mapInvisible` draws the mapped art without the solid's faces. +//! +//! The surfaces of Extrude & Bevel (Classic) are numbered through its solids in the order they are +//! built, each solid's as [`vectorcraft_three_d::extrude_surfaces`] lists them. Revolve (Classic) +//! has one surface, its swept side (in a group, the side of the member with the longest profile). +//! A map whose number is past the object's surfaces draws nothing. + +use std::collections::{HashMap, HashSet}; +use std::sync::Arc; + +use serde_json::{Map, Value, json}; +use vectorcraft_doc::color::{Color, Paint}; +use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, Node, NodeId, NodeKind}; +use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect}; +use vectorcraft_three_d::{Extrude, FaceMap, Facet, MapCell, PlanarFace, SolidSurface, SurfaceKind, View}; + +use super::{ + MAX_ELEMENTS, MAX_SURFACE_CUTS, MAX_SURFACE_POINTS, NotMapped, SURFACE_SEAM, SURFACE_TOLERANCE, Unrolled, counterclockwise, map_path, pieces_of, + straight_pieces, takes_seam, triangle_map, +}; + +/// The effect parameter that holds the maps. +pub const MAP_ART: &str = "mapArt"; + +/// The effect parameter of Shade Artwork. +pub const MAP_SHADE: &str = "mapShade"; + +/// The effect parameter of Invisible Geometry. +pub const MAP_INVISIBLE: &str = "mapInvisible"; + +/// The most surfaces of one 3D effect that carry a map. +pub const MAX_MAPS: usize = 64; + +/// The highest surface number a map may name. +pub const MAX_MAP_SURFACE: usize = 100_000; + +/// The error for maps on a 3D effect that takes none. +pub const MAP_ART_NOT_TAKEN: &str = "Map Art maps symbols onto Extrude & Bevel (Classic) and Revolve (Classic)"; + +/// The symbol mapped onto one numbered surface of a 3D object. +#[derive(Clone, Debug, PartialEq)] +pub struct SurfaceMap { + /// The surface's number, from 1. + pub surface: usize, + pub symbol: String, + pub x: f64, + pub y: f64, + /// Percent of the symbol's own width. + pub scale_x: f64, + /// Percent of the symbol's own height. + pub scale_y: f64, + /// Degrees, counterclockwise. + pub rotation: f64, +} + +impl SurfaceMap { + pub fn to_value(&self) -> Value { + json!({ + "surface": self.surface, + "symbol": self.symbol, + "x": self.x, + "y": self.y, + "scaleX": self.scale_x, + "scaleY": self.scale_y, + "rotation": self.rotation, + }) + } + + /// The map `v` describes. `surface` and `symbol` are required: the offsets and the rotation + /// default to 0 and the scales to 100. + pub fn from_value(v: &Value) -> Result { + let Value::Object(m) = v else { return Err(format!("each of `{MAP_ART}` must be an object")) }; + if let Some(k) = m.keys().find(|k| !matches!(k.as_str(), "surface" | "symbol" | "x" | "y" | "scaleX" | "scaleY" | "rotation")) { + return Err(format!("`{MAP_ART}` entries take surface, symbol, x, y, scaleX, scaleY and rotation, not `{k}`")); + } + let surface = m + .get("surface") + .and_then(Value::as_u64) + .and_then(|n| usize::try_from(n).ok()) + .filter(|n| (1..=MAX_MAP_SURFACE).contains(n)) + .ok_or_else(|| format!("each of `{MAP_ART}` needs `surface`, a whole number from 1 to {MAX_MAP_SURFACE}"))?; + let symbol = match m.get("symbol") { + Some(Value::String(s)) if !s.trim().is_empty() => s.clone(), + _ => return Err(format!("each of `{MAP_ART}` needs `symbol`, the name of a symbol")), + }; + let number = |key: &str, default: f64, (lo, hi): (f64, f64)| -> Result { + match m.get(key) { + None => Ok(default), + Some(v) => v + .as_f64() + .filter(|n| n.is_finite() && (lo..=hi).contains(n)) + .ok_or_else(|| format!("`{MAP_ART}` {key} must be a number from {lo} to {hi}")), + } + }; + Ok(Self { + surface, + symbol, + x: number("x", 0.0, (-super::MAX_OFFSET, super::MAX_OFFSET))?, + y: number("y", 0.0, (-super::MAX_OFFSET, super::MAX_OFFSET))?, + scale_x: number("scaleX", 100.0, super::SCALE_RANGE)?, + scale_y: number("scaleY", 100.0, super::SCALE_RANGE)?, + rotation: number("rotation", 0.0, (-360.0, 360.0))?, + }) + } + + /// Where the symbol's art goes on the flat surface, for art whose bounds are `art` on a + /// surface with center `center`. With `mirrored` (the back cap) x runs to the right as the + /// surface is seen from behind the solid. + pub fn placement(&self, art: Rect, center: Point, mirrored: bool) -> Affine { + let place = Affine::translate((center.x + self.x, center.y + self.y)) + * Affine::rotate(-self.rotation.to_radians()) + * Affine::scale_non_uniform(self.scale_x / 100.0, self.scale_y / 100.0) + * Affine::translate(-art.center().to_vec2()); + if mirrored { + Affine::translate(center.to_vec2()) * Affine::scale_non_uniform(-1.0, 1.0) * Affine::translate(-center.to_vec2()) * place + } else { + place + } + } + + /// The scales (percent) at which art with bounds `art`, turned by the map's rotation, fills a + /// surface `width` by `height` points: Scale to Fit. `None` for art or a surface with no area. + pub fn fitting_scales(&self, art: Rect, (width, height): (f64, f64)) -> Option<(f64, f64)> { + let (w, h) = (art.width(), art.height()); + if w <= 0.0 || h <= 0.0 || width <= 0.0 || height <= 0.0 { + return None; + } + // The box of the art turned by the rotation, at its own size. + let (sin, cos) = self.rotation.to_radians().sin_cos(); + let (bw, bh) = (w * cos.abs() + h * sin.abs(), w * sin.abs() + h * cos.abs()); + let clamp = |v: f64| v.clamp(super::SCALE_RANGE.0, super::SCALE_RANGE.1); + if sin.abs() < 1e-9 || cos.abs() < 1e-9 { + // Square to the surface, each side takes its own scale. + let (sx, sy) = if cos.abs() >= 0.5 { (width / w, height / h) } else { (height / w, width / h) }; + return Some((clamp(sx * 100.0), clamp(sy * 100.0))); + } + let fit = (width / bw).min(height / bh); + Some((clamp(fit * 100.0), clamp(fit * 100.0))) + } +} + +/// The 3D effects that take Map Art: Extrude & Bevel (Classic) and Revolve (Classic). +pub fn takes_map_art(id: &str) -> bool { + id == super::super::CLASSIC_EXTRUDE || id == crate::CLASSIC_REVOLVE +} + +/// The maps in parameters `p`, leaving out entries that are not valid and, of two maps of one +/// surface, the later one (a file may hold anything; commands check every entry with +/// [`validate`]). +pub fn surface_maps(p: &Value) -> Vec { + let Some(Value::Array(list)) = p.get(MAP_ART) else { return vec![] }; + let mut seen = HashSet::new(); + list.iter().filter_map(|v| SurfaceMap::from_value(v).ok()).filter(|m| seen.insert(m.surface)).take(MAX_MAPS).collect() +} + +/// Are the maps in parameters `p` of 3D effect `id` valid? Only Extrude & Bevel (Classic) and +/// Revolve (Classic) take maps, at most [`MAX_MAPS`] of them, one for a surface. +pub fn validate(id: &str, p: &Value) -> Result<(), String> { + let list = match p.get(MAP_ART) { + None => return Ok(()), + Some(Value::Array(list)) => list, + Some(_) => return Err(format!("`{MAP_ART}` must be an array")), + }; + if list.is_empty() { + return Ok(()); + } + if !takes_map_art(id) { + return Err(MAP_ART_NOT_TAKEN.into()); + } + if list.len() > MAX_MAPS { + return Err(format!("`{MAP_ART}` takes at most {MAX_MAPS} maps")); + } + let mut seen = HashSet::new(); + for v in list { + let m = SurfaceMap::from_value(v)?; + if !seen.insert(m.surface) { + return Err(format!("`{MAP_ART}` maps surface {} more than once", m.surface)); + } + } + Ok(()) +} + +/// `p` with the map of surface `surface` replaced by `map`, or removed with `None`. The maps stay +/// in the order of their surfaces. +pub fn with_surface_map(p: &Value, surface: usize, map: Option<&SurfaceMap>) -> Value { + let mut maps: Vec = surface_maps(p).into_iter().filter(|m| m.surface != surface).collect(); + maps.extend(map.cloned()); + maps.sort_by_key(|m| m.surface); + let mut out = p.as_object().cloned().unwrap_or_else(Map::new); + out.insert(MAP_ART.into(), Value::Array(maps.iter().map(SurfaceMap::to_value).collect())); + Value::Object(out) +} + +/// One solid's place among its object's numbered surfaces: the index of its first surface, its +/// surfaces, and for a solid with planar ends the bounds, options and view it was built with. +pub(crate) struct SolidLayout { + pub(crate) first: usize, + pub(crate) surfaces: Vec, + pub(crate) ends: Option<(Rect, Extrude, View)>, +} + +/// What the mapped art of one object has drawn so far, against the limits its maps share. +#[derive(Clone, Debug, Default, PartialEq)] +pub(crate) struct MapBudget { + elements: usize, + /// The points of the maps' symbols cut into straight pieces, against [`MAX_ELEMENTS`]. + input: usize, + /// The points the maps' art draws on the faces, against [`MAX_SURFACE_POINTS`]. + points: usize, + cuts: usize, +} + +/// The maps of one 3D effect, with the document whose symbols they place. +pub(crate) struct MapArt<'a> { + doc: &'a Document, + maps: Vec, + /// Shade Artwork: the mapped art takes the shading of its surface. + pub(crate) shade: bool, + /// Invisible Geometry: only the mapped art is drawn. + pub(crate) invisible: bool, +} + +impl<'a> MapArt<'a> { + /// The maps of 3D effect `id` with parameters `p`. `None` without a document, for an effect + /// that takes no maps and for one that has none. + pub(crate) fn of(doc: Option<&'a Document>, id: &str, p: &Value) -> Option { + let maps = surface_maps(p); + let flag = |key: &str| p.get(key).and_then(Value::as_bool).unwrap_or(false); + (takes_map_art(id) && !maps.is_empty()).then_some(Self { doc: doc?, maps, shade: flag(MAP_SHADE), invisible: flag(MAP_INVISIBLE) }) + } + + fn map_of(&self, index: usize) -> Option<&SurfaceMap> { + self.maps.iter().find(|m| m.surface == index + 1) + } + + /// The mapped art that falls on each of `facets`, one solid's facets in drawing order, for an + /// object with id `id`: for each facet, the nodes to draw right after it. Only facets turned + /// toward the viewer carry art. `shade` gives a color as its facet shades it, for Shade + /// Artwork. A map whose symbol the document does not have, or whose art is past the limits of + /// a graphic's art, draws nothing. `None` when the art is past the limits the maps of one + /// object share, or the copies of its paints take `copies` past the object's allowance: the + /// solid then draws without mapped art. + pub(crate) fn parts( + &self, + id: NodeId, + facets: &[Facet], + layout: &SolidLayout, + shade: &dyn Fn(&Facet, Color) -> Color, + budget: &mut MapBudget, + copies: &mut usize, + ) -> Option>>> { + let mut out: Vec>> = vec![vec![]; facets.len()]; + let mut flat: HashMap> = HashMap::new(); + for (f, parts) in facets.iter().zip(out.iter_mut()) { + if f.away { + continue; + } + let recolor = |c: Color| if self.shade { shade(f, c) } else { c }; + if let Some(end) = f.end { + let Some(local) = layout.surfaces.iter().position(|s| s.kind == SurfaceKind::End(end)) else { continue }; + let (Some(m), Some(center)) = (self.map_of(layout.first + local), layout.surfaces.get(local).and_then(|s| s.center)) else { + continue; + }; + let Some((bounds, options, view)) = layout.ends else { continue }; + let Some(map) = vectorcraft_three_d::extrude_face_map(bounds, options, view, end) else { continue }; + parts.extend(self.end_art(id, m, (end, &map), center, f, &recolor, budget, copies)?); + } else if let Some(cell) = f.cell.as_deref() { + let (Some(m), Some(surface)) = (self.map_of(layout.first + cell.surface), layout.surfaces.get(cell.surface)) else { continue }; + if let std::collections::hash_map::Entry::Vacant(e) = flat.entry(cell.surface) { + e.insert(self.unrolled(m, surface, budget)?); + } + let Some(pieces) = flat.get(&cell.surface) else { continue }; + parts.extend(cell_art(id, pieces, cell, f, &recolor, budget, copies)?); + } + } + Some(out) + } + + /// The art of map `m` on planar end `end` of a solid, drawn on its facet `f` through `map`, + /// for an end whose bounds have center `center`: one clipping group, as a graphic on a cap is + /// drawn. `None` past the limits. + #[allow(clippy::too_many_arguments)] + fn end_art( + &self, + id: NodeId, + m: &SurfaceMap, + (end, map): (PlanarFace, &FaceMap), + center: Point, + f: &Facet, + recolor: &dyn Fn(Color) -> Color, + budget: &mut MapBudget, + copies: &mut usize, + ) -> Option>> { + let Some(symbol) = self.doc.symbols.iter().find(|s| s.name == m.symbol) else { return Some(vec![]) }; + let Ok(pieces) = pieces_of(self.doc, symbol) else { return Some(vec![]) }; + let Some(bounds) = pieces.iter().filter_map(|p| p.path.bounds()).reduce(|a, b| a.union(b)) else { return Some(vec![]) }; + let place = m.placement(bounds, center, end == PlanarFace::Back); + let affine = map.local_affine(center).filter(|_| map.is_affine()); + // Gradients follow the end's map as it is near the art's center, or near the middle of the + // part in front of the eye when the center is not. + let local = map.local_affine(place * bounds.center()).or_else(|| { + let part = map.mapped_part(place.transform_rect_bbox(bounds))?; + let sum = part.iter().fold(Point::ZERO, |s, p| s + p.to_vec2()); + map.local_affine(Point::new(sum.x / part.len() as f64, sum.y / part.len() as f64)) + }); + let Some(local) = local else { return Some(vec![]) }; + let gradient_map = local * place; + let mut children = vec![]; + for piece in pieces { + let placed = piece.path.transformed(place); + let least: usize = placed.subpaths.iter().map(|s| s.anchors.len()).sum(); + let before = budget.elements; + if before.saturating_add(least) > MAX_ELEMENTS { + return None; + } + let room = MAX_ELEMENTS - before; + let mut rule = piece.rule; + let mapped = match map_path(&placed, map, affine, room) { + Err(NotMapped::Behind) => { + // Part of it is at or behind the eye: the part in front is drawn. + let Some(part) = placed.bounds().and_then(|b| map.mapped_part(b)) else { continue }; + let Some(&first) = part.first() else { continue }; + let mut front = BezPath::new(); + front.move_to(first); + part.iter().skip(1).for_each(|p| front.line_to(*p)); + front.close_path(); + let cut = vectorcraft_pathops::boolean( + &placed, + piece.rule, + &PathData::from_bezpath(&front), + FillRule::NonZero, + vectorcraft_pathops::BoolOp::Intersect, + ); + rule = FillRule::NonZero; + map_path(&cut, map, affine, room) + } + done => done, + }; + let mapped = match mapped { + Ok(mapped) => mapped, + Err(NotMapped::Full) => return None, + Err(NotMapped::Behind) => continue, + }; + budget.elements = before.saturating_add(mapped.elements().len()); + if !crate::revolve::paint_copies_add(copies, 1, &piece.paint) { + return None; + } + children.push(Arc::new(piece_node(id, piece.paint, (piece.opacity, piece.blend), (mapped, rule), gradient_map, recolor, None))); + } + if children.is_empty() { + return Some(vec![]); + } + // An end's holes are contours of the same path wound against its outline, so turning the + // whole path keeps them holes under the nonzero rule. + let mut outline = f.path().to_bezpath(); + if vectorcraft_geom::kurbo::Shape::area(&outline) < 0.0 { + outline = outline.reverse_subpaths(); + } + let clip = Node::path(id, PathData::from_bezpath(&outline), Appearance::default()); + Some(vec![Arc::new(Node::new(id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(Node::group(id, children))], clip: true }))]) + } + + /// The areas of map `m`'s symbol placed on `surface` laid out flat, cut into straight pieces. + /// Empty for a symbol the document does not have or whose art is past the limits of a + /// graphic's art. `None` when the pieces of the object's maps take more than + /// [`MAX_ELEMENTS`] points together. + fn unrolled(&self, m: &SurfaceMap, surface: &SolidSurface, budget: &mut MapBudget) -> Option> { + let Some(symbol) = self.doc.symbols.iter().find(|s| s.name == m.symbol) else { return Some(vec![]) }; + let Ok(art) = pieces_of(self.doc, symbol) else { return Some(vec![]) }; + let Some(bounds) = art.iter().filter_map(|p| p.path.bounds()).reduce(|a, b| a.union(b)) else { return Some(vec![]) }; + let place = m.placement(bounds, flat_center(surface), false); + let mut pieces = vec![]; + for piece in art { + let placed = place * piece.path.to_bezpath(); + let mut polygons = straight_pieces(&placed, &mut budget.input)?; + polygons.retain(|p| p.len() >= 3 && p.iter().all(|q| q.is_finite())); + let boxes: Vec = polygons.iter().filter_map(|polygon| box_of(polygon)).collect(); + let Some(bounds) = boxes.iter().copied().reduce(|a, b| a.union(b)) else { continue }; + pieces.push(Unrolled { + polygons, + boxes, + bounds, + rule: piece.rule, + paint: piece.paint, + opacity: piece.opacity, + blend: piece.blend, + place, + }); + } + Some(pieces) + } +} + +/// The center of `surface` laid out flat, which a map's offset is measured from: the middle of a +/// wall or a bevel, whose flat coordinates start at its corner, and the origin of Revolve's side, +/// whose flat coordinates start at its middle. +pub fn flat_center(surface: &SolidSurface) -> Point { + match surface.kind { + SurfaceKind::Side => Point::ZERO, + SurfaceKind::End(_) => surface.center.unwrap_or(Point::ZERO), + SurfaceKind::Wall | SurfaceKind::Bevel => Point::new(surface.width / 2.0, surface.height / 2.0), + } +} + +fn box_of(points: &[Point]) -> Option { + points.iter().map(|p| Rect::from_points(*p, *p)).reduce(|a, b| a.union(b)) +} + +/// A map from a region of a flat surface onto the page. +enum Mapper { + Affine(Affine), + /// The projective map that takes the rectangle with corner `origin` and size `size` onto a + /// quadrilateral: `rows` are its coefficients on the unit square. + Quad { + origin: Point, + size: (f64, f64), + rows: [f64; 8], + }, +} + +impl Mapper { + fn at(&self, p: Point) -> Point { + match self { + Mapper::Affine(a) => *a * p, + Mapper::Quad { origin, size, rows: [a, b, c, d, e, f, g, h] } => { + let (u, v) = ((p.x - origin.x) / size.0, (p.y - origin.y) / size.1); + let w = g * u + h * v + 1.0; + Point::new((a * u + b * v + c) / w, (d * u + e * v + f) / w) + } + } + } + + /// The point of the flat surface this map takes to `p` on the page. `None` where there is none. + fn back(&self, p: Point) -> Option { + let q = match self { + Mapper::Affine(a) => a.inverse() * p, + Mapper::Quad { origin, size, rows: [a, b, c, d, e, f, g, h] } => { + // x (g u + h v + 1) = a u + b v + c, and the same for y, solved for u and v. + let (m00, m01, r0) = (a - g * p.x, b - h * p.x, p.x - c); + let (m10, m11, r1) = (d - g * p.y, e - h * p.y, p.y - f); + let det = m00 * m11 - m01 * m10; + let (u, v) = ((r0 * m11 - m01 * r1) / det, (m00 * r1 - r0 * m10) / det); + Point::new(origin.x + u * size.0, origin.y + v * size.1) + } + }; + q.is_finite().then_some(q) + } + + /// The affine map nearest this one around `p`, for gradients and patterns. + fn local(&self, p: Point, step: f64) -> Affine { + match self { + Mapper::Affine(a) => *a, + Mapper::Quad { .. } => { + let (o, x, y) = (self.at(p), self.at(Point::new(p.x + step, p.y)), self.at(Point::new(p.x, p.y + step))); + let (dx, dy) = ((x - o) / step, (y - o) / step); + Affine::new([dx.x, dx.y, dy.x, dy.y, o.x - dx.x * p.x - dy.x * p.y, o.y - dx.y * p.x - dy.y * p.y]) + } + } + } +} + +/// The projective map of `cell`, a cell whose flat corners are those of an upright rectangle, in +/// order along its edge nearest the origin and back: exact for a flat wall under a perspective. `None` +/// for any other cell and for a quadrilateral the map turns inside out. +fn quad_mapper(cell: &MapCell) -> Option<(Vec, Mapper)> { + let [mut u0, mut u1, mut u2, mut u3] = <[Point; 4]>::try_from(cell.uv.as_slice()).ok()?; + let [mut p0, mut p1, mut p2, mut p3] = <[Point; 4]>::try_from(cell.page.as_slice()).ok()?; + // A cell whose first edge runs from right to left is read from its other end. + if u1.x < u0.x { + (u0, u1, u2, u3) = (u1, u0, u3, u2); + (p0, p1, p2, p3) = (p1, p0, p3, p2); + } + let size = (u1.x - u0.x, u3.y - u0.y); + let upright = u1.y == u0.y && u2.x == u1.x && u2.y == u3.y && u3.x == u0.x && size.0 > 1e-9 && size.1 > 1e-9; + if !upright { + return None; + } + let (dx1, dx2, sx) = (p1.x - p2.x, p3.x - p2.x, p0.x - p1.x + p2.x - p3.x); + let (dy1, dy2, sy) = (p1.y - p2.y, p3.y - p2.y, p0.y - p1.y + p2.y - p3.y); + let den = dx1 * dy2 - dx2 * dy1; + let scale = dx1.abs() + dx2.abs() + dy1.abs() + dy2.abs(); + if den.is_nan() || den.abs() <= 1e-12 * scale * scale { + return None; + } + let (g, h) = ((sx * dy2 - dx2 * sy) / den, (dx1 * sy - sx * dy1) / den); + let rows = [p1.x - p0.x + g * p1.x, p3.x - p0.x + h * p3.x, p0.x, p1.y - p0.y + g * p1.y, p3.y - p0.y + h * p3.y, p0.y, g, h]; + let inside = g + 1.0 > 1e-6 && h + 1.0 > 1e-6 && g + h + 1.0 > 1e-6; + (inside && rows.iter().all(|v| v.is_finite())).then(|| (vec![u0, u1, u2, u3], Mapper::Quad { origin: u0, size, rows })) +} + +/// The regions of `cell` on its flat surface, each a convex polygon wound as [`clip_convex`] reads +/// it, with its map onto the page: the whole of an upright rectangle ([`quad_mapper`]), else the +/// triangles the cell is cut into. +fn regions(cell: &MapCell) -> Vec<(Vec, Mapper)> { + if let Some(quad) = quad_mapper(cell) { + return vec![quad]; + } + let triangles: &[[usize; 3]] = if cell.uv.len() == 3 { &[[0, 1, 2]] } else { &[[0, 1, 2], [0, 2, 3]] }; + triangles + .iter() + .filter_map(|corners| { + let pick = |of: &[Point]| corners.iter().map(|k| of.get(*k).copied()).collect::>>(); + let (uv, page) = (pick(&cell.uv)?, pick(&cell.page)?); + Some((counterclockwise(&uv)?.to_vec(), Mapper::Affine(triangle_map(&uv, &page)?))) + }) + .collect() +} + +/// The part of `polygon` inside the convex `window` (one step of Sutherland and Hodgman's clip for +/// each of its edges), wound so that its inside is on the positive side of each edge. +fn clip_convex(polygon: &[Point], window: &[Point]) -> Vec { + let mut out = polygon.to_vec(); + for (k, &a) in window.iter().enumerate() { + let Some(&b) = window.get((k + 1) % window.len()) else { continue }; + let side = |p: Point| (b - a).cross(p - a); + let input = std::mem::take(&mut out); + for (i, &p) in input.iter().enumerate() { + let Some(&q) = input.get((i + 1) % input.len()) else { continue }; + let (sp, sq) = (side(p), side(q)); + if sp >= 0.0 { + out.push(p); + } + if (sp >= 0.0) != (sq >= 0.0) { + out.push(p.lerp(q, sp / (sp - sq))); + } + } + if out.len() < 3 { + return vec![]; + } + } + out +} + +/// How far `p` lies outside the convex `polygon`, wound with its inside on the positive side of each +/// edge, across the edges for which `counts` holds: 0 or less when it lies inside them. +fn beyond(polygon: &[Point], p: Point, counts: &dyn Fn(Point, Point) -> bool) -> f64 { + let mut most = f64::NEG_INFINITY; + for (k, &a) in polygon.iter().enumerate() { + let Some(&b) = polygon.get((k + 1) % polygon.len()) else { continue }; + let length = (b - a).hypot(); + if length > 0.0 && counts(a, b) { + most = most.max(-(b - a).cross(p - a) / length); + } + } + most +} + +/// `regions` of `cell` ([`regions`]) with the edges they share with the cell's own outline moved out +/// on the flat surface, far enough that their maps reach the outline of facet `f` where its curved +/// edges bow out of the cell: each outline point is taken back onto the flat surface through the +/// region's own map. The edge between two triangles stays, so the regions do not overlap. A region +/// moves out at most four times the size of the cell, and one whose projective map would turn +/// inside out where it reaches stays as it is. Without a curved outline, or where the outline stays +/// inside the cell, the regions are returned unchanged. +fn reaching_outline(regions: Vec<(Vec, Mapper)>, cell: &MapCell, f: &Facet) -> Vec<(Vec, Mapper)> { + let Some(outline) = f.outline.as_ref() else { return regions }; + let Some(uv) = box_of(&cell.uv) else { return regions }; + // The cell on the page, wound with its inside on the positive side of each edge. + let mut around = cell.page.clone(); + let turn: f64 = around.iter().zip(around.iter().cycle().skip(1)).map(|(a, b)| a.to_vec2().cross(b.to_vec2())).sum(); + if turn < 0.0 { + around.reverse(); + } + // The points of the outline that lie outside the cell on the page, or near enough that the + // curve between them may: the curve strays from its flattened points by up to the tolerance, + // so each point counts as the corners of a square of that half width around it. + let mut out = vec![]; + let outline = outline.to_bezpath(); + let t = SURFACE_TOLERANCE; + vectorcraft_geom::kurbo::flatten(outline.elements().iter().copied(), t, |el| { + if let vectorcraft_geom::kurbo::PathEl::MoveTo(p) | vectorcraft_geom::kurbo::PathEl::LineTo(p) = el + && beyond(&around, p, &|_, _| true) > -2.0 * t + { + out.extend([(t, t), (t, -t), (-t, t), (-t, -t)].map(|(x, y)| p + vectorcraft_geom::Vec2::new(x, y))); + } + }); + if out.is_empty() { + return regions; + } + let most = 4.0 * uv.width().hypot(uv.height()); + let on_outline = |a: Point, b: Point| { + let at = |q: Point| cell.uv.iter().position(|u| *u == q); + let count = cell.uv.len(); + matches!((at(a), at(b)), (Some(i), Some(j)) if (i + 1) % count == j || (j + 1) % count == i) + }; + regions + .into_iter() + .map(|(window, mapper)| { + let reach = out.iter().filter_map(|p| mapper.back(*p)).map(|q| beyond(&window, q, &on_outline)).fold(0.0f64, f64::max); + if reach <= 0.0 { + return (window, mapper); + } + // A little past the farthest point, so the cut to the outline meets it. + let reach = (reach * 1.01 + 1e-9).min(most); + let grown = grown_window(&window, reach, &on_outline); + let holds = match &mapper { + Mapper::Affine(_) => true, + Mapper::Quad { origin, size, rows } => grown.iter().all(|p| { + let (u, v) = ((p.x - origin.x) / size.0, (p.y - origin.y) / size.1); + rows[6] * u + rows[7] * v + 1.0 > 1e-6 + }), + }; + (if holds && grown.len() == window.len() { grown } else { window }, mapper) + }) + .collect() +} + +/// The convex `window`, wound as [`clip_convex`] reads it, with each edge for which `moves` holds +/// moved out by `by`, and its corners where the moved edges meet. +fn grown_window(window: &[Point], by: f64, moves: &dyn Fn(Point, Point) -> bool) -> Vec { + let count = window.len(); + // Each edge as a point on its line and its direction, moved out where it moves. + let lines: Vec<(Point, vectorcraft_geom::Vec2)> = (0..count) + .filter_map(|k| { + let (a, b) = (*window.get(k)?, *window.get((k + 1) % count)?); + let d = b - a; + let length = d.hypot(); + let out = if moves(a, b) && length > 0.0 { vectorcraft_geom::Vec2::new(d.y, -d.x) * (by / length) } else { vectorcraft_geom::Vec2::ZERO }; + Some((a + out, d)) + }) + .collect(); + (0..count) + .filter_map(|k| { + let ((p1, d1), (p2, d2)) = (*lines.get((k + count - 1) % count)?, *lines.get(k)?); + let den = d1.cross(d2); + if den.abs() <= 1e-12 * d1.hypot() * d2.hypot() { + return Some(p2); + } + let t = (p2 - p1).cross(d2) / den; + let p = p1 + d1 * t; + p.is_finite().then_some(p) + }) + .collect() +} + +/// The parts of `pieces`, a map's art on its flat surface, that fall on `cell`, the cell of facet +/// `f`, drawn on the page. `None` past the limits. +fn cell_art( + id: NodeId, + pieces: &[Unrolled], + cell: &MapCell, + f: &Facet, + recolor: &dyn Fn(Color) -> Color, + budget: &mut MapBudget, + copies: &mut usize, +) -> Option>> { + if cell.uv.len() != cell.page.len() || !(3..=4).contains(&cell.uv.len()) { + return Some(vec![]); + } + let Some(reach) = box_of(&cell.uv) else { return Some(vec![]) }; + // A facet cut after it was built, or one whose edges follow the profile's curves, draws only the + // part of the art inside its own outline, which the regions reach where it bows out of the cell. + let whole = f.outline.is_none() && f.contours.first() == Some(&cell.page); + let regions = if whole { regions(cell) } else { reaching_outline(regions(cell), cell, f) }; + let within = regions.iter().filter_map(|(w, _)| box_of(w)).fold(reach, |a, b| a.union(b)); + let apart = |b: &Rect| b.x1 < within.x0 || b.x0 > within.x1 || b.y1 < within.y0 || b.y0 > within.y1; + let mut out = vec![]; + for piece in pieces.iter().filter(|p| !apart(&p.bounds)) { + // Each contour's bounds test counts as one point cut, whether or not the contour reaches + // the cell. + budget.cuts = budget.cuts.saturating_add(piece.boxes.len()); + if budget.cuts > MAX_SURFACE_CUTS { + return None; + } + let near: Vec<&Vec> = piece.polygons.iter().zip(&piece.boxes).filter(|(_, b)| !apart(b)).map(|(p, _)| p).collect(); + let mut path = BezPath::new(); + for (window, mapper) in ®ions { + for polygon in &near { + budget.cuts = budget.cuts.saturating_add(polygon.len()); + if budget.cuts > MAX_SURFACE_CUTS { + return None; + } + let cut = clip_convex(polygon, window); + let Some((first, rest)) = cut.split_first() else { continue }; + path.move_to(mapper.at(*first)); + rest.iter().for_each(|q| path.line_to(mapper.at(*q))); + path.close_path(); + budget.points = budget.points.saturating_add(cut.len()); + } + } + if budget.points > MAX_SURFACE_POINTS { + return None; + } + if path.elements().is_empty() { + continue; + } + let (path, rule) = if whole { + (path, piece.rule) + } else { + let cut = vectorcraft_pathops::boolean( + &PathData::from_bezpath(&path), + piece.rule, + &f.path(), + FillRule::NonZero, + vectorcraft_pathops::BoolOp::Intersect, + ); + (cut.to_bezpath(), FillRule::NonZero) + }; + if path.elements().is_empty() || !path.elements().iter().all(el_is_finite) { + continue; + } + let seam = takes_seam(piece); + if !crate::revolve::paint_copies_add(copies, 1 + usize::from(seam), &piece.paint) { + return None; + } + // Gradients and patterns follow the cell's map as it is at the cell's middle. + let middle = reach.center(); + let local = regions.first().map_or(Affine::IDENTITY, |(_, m)| m.local(middle, (reach.width().max(reach.height()) * 1e-3).max(1e-6))); + let node = piece_node( + id, + piece.paint.clone(), + (piece.opacity, piece.blend), + (path, rule), + local * piece.place, + recolor, + seam.then_some(SURFACE_SEAM), + ); + out.push(Arc::new(node)); + } + Some(out) +} + +fn el_is_finite(el: &vectorcraft_geom::kurbo::PathEl) -> bool { + use vectorcraft_geom::kurbo::PathEl; + match *el { + PathEl::MoveTo(p) | PathEl::LineTo(p) => p.is_finite(), + PathEl::QuadTo(a, p) => a.is_finite() && p.is_finite(), + PathEl::CurveTo(a, b, p) => a.is_finite() && b.is_finite() && p.is_finite(), + PathEl::ClosePath => true, + } +} + +/// One painted area of mapped art on the page: `path` filled under `rule` with `paint`, its +/// gradients and pattern tiles placed through `gradient_map`, its colors through `recolor`, and +/// with `seam` a stroke of that width in the same paint over the seams between neighboring parts. +fn piece_node( + id: NodeId, + mut paint: Paint, + (opacity, blend): (f32, vectorcraft_doc::color::BlendMode), + (path, rule): (BezPath, FillRule), + gradient_map: Affine, + recolor: &dyn Fn(Color) -> Color, + seam: Option, +) -> Node { + if let Paint::Pattern { xf, .. } = &mut paint { + *xf = gradient_map * *xf; + } + let mut fill = FillLayer::new(paint); + fill.opacity = opacity; + fill.blend = blend; + let mut appearance = Appearance { items: vec![AppearanceItem::Fill(fill)], ..Default::default() }; + appearance.transform_gradients(gradient_map); + for item in appearance.items.iter_mut() { + if let AppearanceItem::Fill(f) = item { + // Pattern tiles keep their colors: the document's pattern draws them. + vectorcraft_doc::recolor::map_paint(&mut f.paint, recolor); + } + } + if let (Some(width), Some(AppearanceItem::Fill(f))) = (seam, appearance.items.first()) { + let mut stroke = vectorcraft_doc::StrokeLayer::new(f.paint.clone(), width); + stroke.join = vectorcraft_doc::LineJoin::Round; + appearance.items.push(AppearanceItem::Stroke(stroke)); + } + let mut node = Node::path(id, PathData::from_bezpath(&path), appearance); + if let NodeKind::Path { rule: r, .. } = &mut node.kind { + *r = rule; + } + node +} + +#[cfg(test)] +#[path = "tests_map_art.rs"] +mod tests; diff --git a/crates/effects/src/solids/tests.rs b/crates/effects/src/solids/tests.rs index b77903714e..74636721b8 100644 --- a/crates/effects/src/solids/tests.rs +++ b/crates/effects/src/solids/tests.rs @@ -776,6 +776,7 @@ fn a_stroke_face_through_a_fill_wall_is_cut_where_their_depths_meet() { end: None, surface: None, plane: Some(DepthPlane { normal, offset, center: Point::ZERO, eye: None }), + cell: 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. diff --git a/crates/effects/src/solids/tests_graphics_side.rs b/crates/effects/src/solids/tests_graphics_side.rs index d216ff7d0d..a35757257f 100644 --- a/crates/effects/src/solids/tests_graphics_side.rs +++ b/crates/effects/src/solids/tests_graphics_side.rs @@ -186,6 +186,7 @@ fn a_piece_cut_from_a_face_draws_its_own_part() { 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 }), + cell: None, } }; let wall = facet(0.0, [0.0, 0.0, 1.0], 0.0); diff --git a/crates/effects/src/solids/tests_map_art.rs b/crates/effects/src/solids/tests_map_art.rs new file mode 100644 index 0000000000..af7fe06965 --- /dev/null +++ b/crates/effects/src/solids/tests_map_art.rs @@ -0,0 +1,707 @@ +use serde_json::json; +use vectorcraft_doc::Symbol; +use vectorcraft_geom::shapes; + +use super::super::super::{CLASSIC_EXTRUDE, CLASSIC_ROTATE, MapSurface, map_surfaces_at, solid_art_in, validate_three_d_at_in, validate_three_d_in}; +use super::*; +use crate::CLASSIC_REVOLVE; + +const RED: Color = Color::Rgb { r: 1.0, g: 0.0, b: 0.0 }; +const GREEN: Color = Color::Rgb { r: 0.0, g: 1.0, b: 0.0 }; +const BLUE: Color = Color::Rgb { r: 0.0, g: 0.0, b: 1.0 }; + +fn square(id: u64, r: Rect, c: Color) -> Node { + Node::path(NodeId(id), shapes::rectangle(r), Appearance::basic(Paint::solid(c), Paint::None, 0.0)) +} + +/// A document with symbol "Mark", a red 10 × 10 square, and symbol "Corner", 30 × 30: a red square +/// at its top left, a blue one to the right of it and a green one below it. +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), RED)) }); + let corner = Node::group( + NodeId(0), + vec![ + Arc::new(square(0, Rect::new(0.0, 0.0, 10.0, 10.0), RED)), + Arc::new(square(0, Rect::new(20.0, 0.0, 30.0, 10.0), BLUE)), + Arc::new(square(0, Rect::new(0.0, 20.0, 10.0, 30.0), GREEN)), + ], + ); + d.symbols.push(Symbol { dynamic: false, name: "Corner".into(), art: Arc::new(corner) }); + d +} + +/// A gray 100 × 100 square at (0, 0) with effect `id`, its parameters `params` over a view +/// straight on with No Shading. +fn object(id: &str, params: Value) -> Node { + let mut p = json!({"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0, "surface": "none"}); + 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), Color::rgb(0.5, 0.5, 0.5)); + n.appearance.effects.push(crate::new_effect(id, &p).unwrap()); + n +} + +/// The paths of `art` filled with color `c`, in drawing order. +fn filled(art: &Node, c: Color) -> Vec { + let mut out = vec![]; + art.walk(&mut |n| { + let fill = n.appearance.items.iter().find_map(|i| match i { + AppearanceItem::Fill(f) => f.paint.color(), + AppearanceItem::Stroke(_) => None, + }); + if fill.is_some_and(|f| f.to_rgb().iter().zip(c.to_rgb()).all(|(a, b)| (a - b).abs() < 1e-4)) + && let Some(p) = n.path_data() + { + out.push(p.clone()); + } + }); + out +} + +fn bounds_of(paths: &[PathData]) -> Rect { + paths.iter().filter_map(|p| p.bounds()).reduce(|a, b| a.union(b)).unwrap() +} + +fn close(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) +} + +fn surfaces(n: &Node) -> Vec { + map_surfaces_at(Some(&document()), n, None, 0).unwrap() +} + +/// Which way round the "Corner" symbol reads in `art`: positive when its blue square is to the +/// right of its red one and its green one below, as the symbol is drawn, at any turn; negative +/// when it is mirrored. +fn handedness(art: &Node) -> f64 { + let at = |c: Color| bounds_of(&filled(art, c)).center(); + (at(BLUE) - at(RED)).cross(at(GREEN) - at(RED)) +} + +#[test] +fn the_surfaces_are_the_caps_then_each_wall_then_each_bevel() { + let kinds = |n: &Node| surfaces(n).iter().map(|s| s.kind).collect::>(); + let (front, back) = (SurfaceKind::End(PlanarFace::Front), SurfaceKind::End(PlanarFace::Back)); + let solid = object(CLASSIC_EXTRUDE, json!({})); + assert_eq!(kinds(&solid), [vec![front, back], vec![SurfaceKind::Wall; 4]].concat()); + // Each wall runs from corner to corner of the square and is as deep as the solid. + for wall in surfaces(&solid).iter().skip(2) { + assert!((wall.width - 100.0).abs() < 1e-6 && (wall.height - 50.0).abs() < 1e-6, "{wall:?}"); + } + assert_eq!(kinds(&object(CLASSIC_EXTRUDE, json!({"cap": false}))), vec![SurfaceKind::Wall; 4]); + let beveled = object(CLASSIC_EXTRUDE, json!({"bevel": "classic"})); + assert_eq!(kinds(&beveled), [vec![front, back], vec![SurfaceKind::Wall; 4], vec![SurfaceKind::Bevel; 4]].concat()); + // With no depth the art is a plane, which has its front only. + assert_eq!(kinds(&object(CLASSIC_EXTRUDE, json!({"depth": 0}))), vec![front]); + // An outline with no corner has one wall. + let mut round = Node::path(NodeId(7), shapes::ellipse(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::basic(Paint::solid(RED), Paint::None, 0.0)); + round.appearance.effects.push(crate::new_effect(CLASSIC_EXTRUDE, &json!({})).unwrap()); + assert_eq!(kinds(&round), vec![front, back, SurfaceKind::Wall]); + // Revolve (Classic) has its side, and Rotate (Classic) takes no maps. + assert_eq!(kinds(&object(CLASSIC_REVOLVE, json!({}))), vec![SurfaceKind::Side]); + assert_eq!(map_surfaces_at(Some(&document()), &object(CLASSIC_ROTATE, json!({})), None, 0), None); + // Seen straight on, only the front cap is turned toward the viewer. + let seen: Vec = surfaces(&solid).iter().map(|s| s.visible).collect(); + assert_eq!(seen, [true, false, false, false, false, false]); +} + +#[test] +fn a_bevel_as_deep_as_the_solid_leaves_no_walls_and_its_bevels_take_their_maps() { + let (front, back) = (SurfaceKind::End(PlanarFace::Front), SurfaceKind::End(PlanarFace::Back)); + let solid = |maps: Value| object(CLASSIC_EXTRUDE, json!({"depth": 10, "bevel": "classic", "bevelHeight": 10, "mapArt": maps})); + let kinds: Vec = surfaces(&solid(json!([]))).iter().map(|s| s.kind).collect(); + assert_eq!(kinds, [vec![front, back], vec![SurfaceKind::Bevel; 4]].concat()); + // Seen straight on, the front bevels draw the art mapped onto them. + let bevels: Vec = (3..=6).map(|k| json!({"surface": k, "symbol": "Mark"})).collect(); + let art = solid_art_in(Some(&document()), &solid(json!(bevels))).unwrap(); + assert!(!filled(&art, RED).is_empty()); +} + +#[test] +fn a_map_on_the_front_cap_draws_the_symbol_at_its_offset_scales_and_turn() { + let d = document(); + let map = |m: Value| solid_art_in(Some(&d), &object(CLASSIC_EXTRUDE, json!({"mapArt": [m]}))).unwrap(); + // Without a map nothing red is drawn. + assert!(filled(&solid_art_in(Some(&d), &object(CLASSIC_EXTRUDE, json!({}))).unwrap(), RED).is_empty()); + // The art's center is at the center of the cap, its size the symbol's own. + let centered = filled(&map(json!({"surface": 1, "symbol": "Mark"})), RED); + assert!(close(bounds_of(¢ered), Rect::new(45.0, 45.0, 55.0, 55.0)), "{:?}", bounds_of(¢ered)); + // An offset moves it, and each scale sizes one side. + let moved = filled(&map(json!({"surface": 1, "symbol": "Mark", "x": 10, "y": -5, "scaleX": 200, "scaleY": 300})), RED); + assert!(close(bounds_of(&moved), Rect::new(50.0, 30.0, 70.0, 60.0)), "{:?}", bounds_of(&moved)); + // A quarter turn swaps the sides. + let turned = filled(&map(json!({"surface": 1, "symbol": "Mark", "scaleX": 200, "rotation": 90})), RED); + assert!(close(bounds_of(&turned), Rect::new(45.0, 40.0, 55.0, 60.0)), "{:?}", bounds_of(&turned)); + // The art is clipped to the cap. + let past = filled(&map(json!({"surface": 1, "symbol": "Mark", "x": 50})), RED); + assert_eq!(past.len(), 1); + let art = map(json!({"surface": 1, "symbol": "Mark", "x": 50})); + let mut clipped = false; + art.walk(&mut |n| clipped |= matches!(&n.kind, NodeKind::Group { clip: true, .. })); + assert!(clipped); +} + +#[test] +fn a_map_on_a_side_wall_reads_the_right_way_round_from_outside() { + let d = document(); + let all_walls: Vec = (3..=6).map(|k| json!({"surface": k, "symbol": "Corner"})).collect(); + for turn in [-90.0, 90.0] { + // Seen from one side, one wall faces the viewer: it alone carries its map. + let n = object(CLASSIC_EXTRUDE, json!({"rotationY": turn, "mapArt": all_walls})); + let art = solid_art_in(Some(&d), &n).unwrap(); + assert_eq!(filled(&art, RED).len(), 1, "one wall is seen at {turn}"); + // The wall is 100 along the outline and 50 deep: the art keeps its size at its middle. + let whole = bounds_of(&[filled(&art, RED), filled(&art, BLUE), filled(&art, GREEN)].concat()); + assert!((whole.width() - 30.0).abs() < 1e-6 && (whole.height() - 30.0).abs() < 1e-6, "{whole:?}"); + assert!((whole.center().x - 50.0).abs() < 1e-6 && (whole.center().y - 50.0).abs() < 1e-6, "{whole:?}"); + assert!(handedness(&art) > 0.0, "the art is mirrored at {turn}"); + } + // The walls seen from above and below read the right way round too. + for turn in [-90.0, 90.0] { + let n = object(CLASSIC_EXTRUDE, json!({"rotationX": turn, "mapArt": all_walls})); + assert!(handedness(&solid_art_in(Some(&d), &n).unwrap()) > 0.0, "the art is mirrored at {turn}"); + } +} + +#[test] +fn a_wall_beside_a_bevel_is_laid_out_at_its_own_length() { + let d = document(); + // A bevel 10 wide added around the square sets each wall 10 out, so each wall is 120 long; a + // bevel takes the length of the wall it sits above. Carved in, the walls are the square's own. + for (inside, length) in [(false, 120.0), (true, 100.0)] { + let solid = object(CLASSIC_EXTRUDE, json!({"bevel": "classic", "bevelHeight": 10, "bevelInside": inside})); + for side in surfaces(&solid).iter().skip(2) { + assert!((side.width - length).abs() < 1e-6, "inside {inside}: {side:?}"); + } + // Seen from one side, the art on the wall that faces the viewer keeps its size. + let walls: Vec = (3..=6).map(|k| json!({"surface": k, "symbol": "Corner"})).collect(); + let n = object(CLASSIC_EXTRUDE, json!({"bevel": "classic", "bevelHeight": 10, "bevelInside": inside, "rotationY": 90, "mapArt": walls})); + let art = solid_art_in(Some(&d), &n).unwrap(); + let whole = bounds_of(&[filled(&art, RED), filled(&art, BLUE), filled(&art, GREEN)].concat()); + assert!((whole.width() - 30.0).abs() < 1e-6 && (whole.height() - 30.0).abs() < 1e-6, "inside {inside}: {whole:?}"); + } +} + +#[test] +fn art_on_a_facet_with_a_curved_edge_is_clipped_to_that_edge() { + let quad = vec![Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(10.0, 10.0), Point::new(0.0, 10.0)]; + // The facet's top edge follows a curve that bows into the quad, down to y = 2. + let mut curved = BezPath::new(); + curved.move_to((0.0, 0.0)); + curved.curve_to((10.0 / 3.0, 8.0 / 3.0), (20.0 / 3.0, 8.0 / 3.0), (10.0, 0.0)); + curved.line_to((10.0, 10.0)); + curved.line_to((0.0, 10.0)); + curved.close_path(); + let facet = Facet { + contours: vec![quad.clone()], + depth: 0.0, + brightness: 1.0, + illumination: [1.0; 3], + normal: [0.0, 0.0, 1.0], + rgb_gradient: None, + outline: Some(PathData::from_bezpath(&curved)), + side: true, + away: false, + end: None, + plane: None, + surface: None, + cell: None, + }; + let cell = MapCell { surface: 0, page: quad.clone(), uv: quad.clone() }; + let whole = Rect::new(0.0, 0.0, 10.0, 10.0); + let art = Unrolled { + polygons: vec![quad], + boxes: vec![whole], + bounds: whole, + rule: FillRule::NonZero, + paint: Paint::solid(RED), + opacity: 1.0, + blend: Default::default(), + place: Affine::IDENTITY, + }; + let (mut budget, mut copies) = (MapBudget::default(), 0); + let out = cell_art(NodeId(1), &[art], &cell, &facet, &|c| c, &mut budget, &mut copies).unwrap(); + let area: f64 = out.iter().filter_map(|n| n.path_data()).map(|p| vectorcraft_geom::kurbo::Shape::area(&p.to_bezpath()).abs()).sum(); + let want = vectorcraft_geom::kurbo::Shape::area(&curved).abs(); + assert!((area - want).abs() < 1e-2, "{area} drawn, {want} inside the curved edge"); +} + +#[test] +fn art_on_a_facet_whose_curved_edge_bows_out_covers_the_whole_facet() { + let quad = vec![Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(10.0, 10.0), Point::new(0.0, 10.0)]; + // The facet's top edge follows a curve that bows out of the quad, up to y = -2. + let mut curved = BezPath::new(); + curved.move_to((0.0, 0.0)); + curved.curve_to((10.0 / 3.0, -8.0 / 3.0), (20.0 / 3.0, -8.0 / 3.0), (10.0, 0.0)); + curved.line_to((10.0, 10.0)); + curved.line_to((0.0, 10.0)); + curved.close_path(); + let facet = Facet { + contours: vec![quad.clone()], + depth: 0.0, + brightness: 1.0, + illumination: [1.0; 3], + normal: [0.0, 0.0, 1.0], + rgb_gradient: None, + outline: Some(PathData::from_bezpath(&curved)), + side: true, + away: false, + end: None, + plane: None, + surface: None, + cell: None, + }; + let cell = MapCell { surface: 0, page: quad.clone(), uv: quad }; + // Art that covers the facet and more. + let cover = vec![Point::new(-5.0, -5.0), Point::new(15.0, -5.0), Point::new(15.0, 15.0), Point::new(-5.0, 15.0)]; + let whole = Rect::new(-5.0, -5.0, 15.0, 15.0); + let art = Unrolled { + polygons: vec![cover], + boxes: vec![whole], + bounds: whole, + rule: FillRule::NonZero, + paint: Paint::solid(RED), + opacity: 1.0, + blend: Default::default(), + place: Affine::IDENTITY, + }; + let (mut budget, mut copies) = (MapBudget::default(), 0); + let out = cell_art(NodeId(1), &[art], &cell, &facet, &|c| c, &mut budget, &mut copies).unwrap(); + let area: f64 = out.iter().filter_map(|n| n.path_data()).map(|p| vectorcraft_geom::kurbo::Shape::area(&p.to_bezpath()).abs()).sum(); + let want = vectorcraft_geom::kurbo::Shape::area(&curved).abs(); + assert!((area - want).abs() < 1e-2, "{area} drawn, {want} inside the curved edge"); +} + +#[test] +fn the_bounds_tests_of_contours_away_from_a_cell_count_as_cuts() { + let quad = vec![Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(10.0, 10.0), Point::new(0.0, 10.0)]; + let facet = Facet { + contours: vec![quad.clone()], + depth: 0.0, + brightness: 1.0, + illumination: [1.0; 3], + normal: [0.0, 0.0, 1.0], + rgb_gradient: None, + outline: None, + side: true, + away: false, + end: None, + plane: None, + surface: None, + cell: None, + }; + let cell = MapCell { surface: 0, page: quad.clone(), uv: quad }; + // Small contours on either side of the cell: the piece's bounds reach across it, but no + // contour's own bounds do. + let polygons: Vec> = (0..2000) + .map(|k| { + let x = if k % 2 == 0 { -1000.0 } else { 1000.0 }; + vec![Point::new(x, 0.0), Point::new(x + 1.0, 0.0), Point::new(x + 1.0, 1.0)] + }) + .collect(); + let boxes: Vec = polygons.iter().filter_map(|p| box_of(p)).collect(); + let art = Unrolled { + polygons, + boxes, + bounds: Rect::new(-1000.0, 0.0, 1001.0, 1.0), + rule: FillRule::NonZero, + paint: Paint::solid(RED), + opacity: 1.0, + blend: Default::default(), + place: Affine::IDENTITY, + }; + let mut budget = MapBudget { cuts: MAX_SURFACE_CUTS - 10, ..MapBudget::default() }; + assert!(cell_art(NodeId(1), &[art], &cell, &facet, &|c| c, &mut budget, &mut 0).is_none()); +} + +#[test] +fn a_map_on_the_back_cap_reads_the_right_way_round_from_behind() { + let d = document(); + let n = object(CLASSIC_EXTRUDE, json!({"rotationY": 180, "mapArt": [{"surface": 1, "symbol": "Mark"}, {"surface": 2, "symbol": "Corner"}]})); + let art = solid_art_in(Some(&d), &n).unwrap(); + // Only the back cap is seen, and it carries its own map's art. + assert_eq!(filled(&art, RED).len(), 1); + assert_eq!((filled(&art, BLUE).len(), filled(&art, GREEN).len()), (1, 1)); + assert!(handedness(&art) > 0.0); +} + +#[test] +fn art_past_the_shared_limits_leaves_out_the_mapped_art_of_every_solid() { + let mut d = document(); + // A zigzag of half the straight sides one 3D effect's mapped art may draw. + let mut b = BezPath::new(); + b.move_to((0.0, 0.0)); + for i in 1..=MAX_ELEMENTS / 2 { + b.line_to((i as f64 * 0.00005, (i % 2) as f64)); + } + b.close_path(); + let half = Node::path(NodeId(0), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(RED), Paint::None, 0.0)); + d.symbols.push(Symbol { dynamic: false, name: "Half".into(), art: Arc::new(half) }); + let gray = Color::rgb(0.5, 0.5, 0.5); + // A group of two squares: the first solid's front is surface 1, the second's surface 7. + let art = |maps: Value, invisible: bool| { + let members = + vec![Arc::new(square(8, Rect::new(0.0, 0.0, 100.0, 100.0), gray)), Arc::new(square(9, Rect::new(200.0, 0.0, 300.0, 100.0), gray))]; + let mut g = Node::group(NodeId(7), members); + let p = json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "surface": "none", "mapInvisible": invisible, "mapArt": maps}); + g.appearance.effects.push(crate::new_effect(CLASSIC_EXTRUDE, &p).unwrap()); + solid_art_in(Some(&d), &g).unwrap() + }; + // One solid's art fits. + assert!(!filled(&art(json!([{"surface": 1, "symbol": "Half"}]), false), RED).is_empty()); + // Both together are past the limit: no solid draws its art, and with Invisible Geometry every + // solid's faces draw. + let both = json!([{"surface": 1, "symbol": "Half"}, {"surface": 7, "symbol": "Half"}]); + assert!(filled(&art(both.clone(), false), RED).is_empty()); + let hidden = art(both, true); + assert!(filled(&hidden, RED).is_empty()); + let faces = bounds_of(&filled(&hidden, gray)); + assert!(faces.x0 < 1.0 && faces.x1 > 299.0, "{faces:?}"); +} + +#[test] +fn a_wall_under_a_perspective_maps_its_art_whole() { + let d = document(); + let all_walls: Vec = (3..=6).map(|k| json!({"surface": k, "symbol": "Mark"})).collect(); + let n = object(CLASSIC_EXTRUDE, json!({"rotationY": -60, "perspectiveAngle": 90, "mapArt": all_walls})); + let art = solid_art_in(Some(&d), &n).unwrap(); + // The wall is one flat face: the square maps onto it as one four-cornered area, not as two + // pieces that meet along the face's diagonal. + let marks = filled(&art, RED); + assert_eq!(marks.len(), 1); + let mark = &marks[0]; + assert_eq!((mark.subpaths.len(), mark.subpaths[0].anchors.len()), (1, 4), "{mark:?}"); + // Nearer the viewer the square's side is longer. + let side = |i: usize| mark.subpaths[0].anchors[i].p.distance(mark.subpaths[0].anchors[(i + 1) % 4].p); + let uneven = (side(0) - side(2)).abs().max((side(1) - side(3)).abs()); + assert!(uneven > 0.05, "{} {} {} {}", side(0), side(1), side(2), side(3)); +} + +#[test] +fn shade_artwork_and_invisible_geometry_change_what_is_drawn() { + let d = document(); + let params = |extra: Value| { + let mut p = json!({"surface": "diffuse", "rotationY": -60, "lightIntensity": 0, "ambient": 20, "mapArt": [{"surface": 1, "symbol": "Mark"}]}); + p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + solid_art_in(Some(&d), &object(CLASSIC_EXTRUDE, p)).unwrap() + }; + // Unshaded, the art keeps its own color on a shaded face. + assert_eq!(filled(¶ms(json!({})), RED).len(), 1); + // Shaded, it darkens toward black with its face. + let shaded = params(json!({"mapShade": true})); + assert!(filled(&shaded, RED).is_empty()); + let mut darkest = 1.0f32; + shaded.walk(&mut |n| { + for item in &n.appearance.items { + if let AppearanceItem::Fill(f) = item + && let Some([r, g, b]) = f.paint.color().map(|c| c.to_rgb()) + && g < 1e-4 + && b < 1e-4 + && r > 0.0 + { + darkest = darkest.min(r); + } + } + }); + assert!(darkest < 0.999, "the art is as dark as its face: {darkest}"); + // With Invisible Geometry only the art is drawn. + let count = |art: &Node| { + let mut paths = 0; + art.walk(&mut |n| paths += usize::from(n.path_data().is_some() && !n.appearance.items.is_empty())); + paths + }; + assert!(count(¶ms(json!({}))) > 1); + assert_eq!(count(¶ms(json!({"mapInvisible": true}))), 1); + // Without a map Invisible Geometry leaves the solid as it is, and Wireframe draws no art. + let plain = object(CLASSIC_EXTRUDE, json!({"mapInvisible": true})); + assert!(count(&solid_art_in(Some(&d), &plain).unwrap()) > 0); + assert!(filled(¶ms(json!({"surface": "wireframe"})), RED).is_empty()); +} + +#[test] +fn a_map_past_the_surfaces_draws_nothing_and_a_missing_symbol_is_left_out() { + let d = document(); + let art = |maps: Value| solid_art_in(Some(&d), &object(CLASSIC_EXTRUDE, json!({"mapArt": maps}))).unwrap(); + assert!(filled(&art(json!([{"surface": 7, "symbol": "Mark"}])), RED).is_empty()); + assert!(filled(&art(json!([{"surface": 1, "symbol": "Gone"}])), RED).is_empty()); + // A hollow solid's first surface is its first wall, so the cap's map draws nothing there. + let hollow = object(CLASSIC_EXTRUDE, json!({"cap": false, "mapArt": [{"surface": 1, "symbol": "Mark"}]})); + assert!(filled(&solid_art_in(Some(&d), &hollow).unwrap(), RED).is_empty()); + assert_eq!(missing(&d, &json!({"mapArt": [{"surface": 1, "symbol": "Gone"}]})), Some("Gone".to_string())); + assert_eq!(missing(&d, &json!({"mapArt": [{"surface": 1, "symbol": "Mark"}]})), None); +} + +#[test] +fn the_points_drawn_on_earlier_surfaces_leave_the_next_symbol_its_own_allowance() { + let d = document(); + let art = MapArt::of(Some(&d), CLASSIC_EXTRUDE, &json!({"mapArt": [{"surface": 3, "symbol": "Mark"}]})).unwrap(); + let wall = SolidSurface { kind: SurfaceKind::Wall, width: 100.0, height: 50.0, center: None }; + // Earlier surfaces drew more points on their faces than one symbol may take cut into pieces. + let mut budget = MapBudget { points: MAX_ELEMENTS + 1, ..MapBudget::default() }; + let pieces = art.unrolled(&art.maps[0], &wall, &mut budget).expect("the symbol is cut into pieces"); + assert_eq!(pieces.len(), 1); +} + +#[test] +fn art_past_the_paint_copies_allowance_leaves_the_allowance_to_later_art() { + let d = document(); + let mut b = BezPath::new(); + b.move_to((100.0, 0.0)); + b.line_to((100.0, 100.0)); + let path = PathData::from_bezpath(&b); + let gray = Paint::solid(Color::rgb(0.5, 0.5, 0.5)); + let n = Node::path(NodeId(7), path.clone(), Appearance::basic(Paint::None, gray.clone(), 1.0)); + let p = crate::merged_params( + CLASSIC_REVOLVE, + &json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "surface": "none", "offset": 40, "mapArt": [{"surface": 1, "symbol": "Mark"}]}), + ); + let art = MapArt::of(Some(&d), CLASSIC_REVOLVE, &p).unwrap(); + let bounds = path.bounds().unwrap(); + let options = vectorcraft_three_d::Revolve { map_surface: true, ..crate::revolve::options_of(CLASSIC_REVOLVE, &p) }; + let (width, height) = vectorcraft_three_d::revolve_surface_size(&path, bounds, options).unwrap(); + let layout = SolidLayout { first: 0, surfaces: vec![SolidSurface { kind: SurfaceKind::Side, width, height, center: None }], ends: None }; + let facets = vectorcraft_three_d::revolve_facets(&path, bounds, options).unwrap(); + // The side's art, with the copies of its paint and its points counted from `copies` and + // `budget` already used. + let draw = |copies: &mut usize, budget: &mut MapBudget| { + let mapped = crate::solids::classic::Mapped { art: &art, layout: &layout, budget, copies }; + let blend = vectorcraft_doc::color::BlendMode::Normal; + crate::solids::classic::surface(&n, &facets, &gray, (1.0, blend), &p, Some(mapped), false).0 + }; + let (mut copies, mut budget) = (0, MapBudget::default()); + assert!(!filled(&draw(&mut copies, &mut budget), RED).is_empty()); + assert!(copies > 0 && budget != MapBudget::default()); + // With the allowance used up, the art is left out, and so are the copies and the points it + // would have taken. + let full = crate::revolve::MAX_PAINT_COPIES; + let (mut copies, mut budget) = (full, MapBudget::default()); + assert!(filled(&draw(&mut copies, &mut budget), RED).is_empty()); + assert_eq!(copies, full); + assert_eq!(budget, MapBudget::default()); +} + +fn missing(d: &Document, p: &Value) -> Option { + super::super::missing_symbol(d, p, None) +} + +#[test] +fn revolve_classic_wraps_its_map_around_the_side() { + let d = document(); + let mut b = BezPath::new(); + b.move_to((100.0, 0.0)); + b.line_to((100.0, 100.0)); + let mut n = Node::path(NodeId(7), PathData::from_bezpath(&b), Appearance::basic(Paint::None, Paint::solid(Color::rgb(0.5, 0.5, 0.5)), 1.0)); + let view = + json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "surface": "none", "offset": 40, "mapArt": [{"surface": 1, "symbol": "Corner"}]}); + n.appearance.effects.push(crate::new_effect(CLASSIC_REVOLVE, &view).unwrap()); + let art = crate::revolve_art_in(Some(&d), &n).unwrap(); + // The art is drawn at the middle of the side that faces the viewer, the right way round. + assert!(!filled(&art, RED).is_empty()); + assert!(handedness(&art) > 0.0); + let whole = bounds_of(&[filled(&art, RED), filled(&art, BLUE), filled(&art, GREEN)].concat()); + assert!((whole.center().y - 50.0).abs() < 1.0, "{whole:?}"); + // A map of another surface draws nothing. + n.appearance.effects[0].params["mapArt"] = json!([{"surface": 2, "symbol": "Corner"}]); + assert!(filled(&crate::revolve_art_in(Some(&d), &n).unwrap(), RED).is_empty()); +} + +#[test] +fn invisible_geometry_leaves_out_every_member_of_a_revolved_group() { + let d = document(); + let gray = Color::rgb(0.5, 0.5, 0.5); + let line = |id: u64, x: f64, height: f64| { + let mut b = BezPath::new(); + b.move_to((x, 0.0)); + b.line_to((x, height)); + Arc::new(Node::path(NodeId(id), PathData::from_bezpath(&b), Appearance::basic(Paint::None, Paint::solid(gray), 1.0))) + }; + // The map goes on the side of the longer member; the shorter one has none. + let art = |extra: Value| { + let mut p = + json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "surface": "none", "offset": 40, "mapArt": [{"surface": 1, "symbol": "Mark"}]}); + p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + let mut g = Node::group(NodeId(7), vec![line(8, 100.0, 100.0), line(9, 140.0, 30.0)]); + g.appearance.effects.push(crate::new_effect(CLASSIC_REVOLVE, &p).unwrap()); + crate::revolve_art_in(Some(&d), &g).unwrap() + }; + let shown = art(json!({})); + assert!(!filled(&shown, RED).is_empty() && !filled(&shown, gray).is_empty()); + let hidden = art(json!({"mapInvisible": true})); + assert!(!filled(&hidden, RED).is_empty()); + assert!(filled(&hidden, gray).is_empty(), "no member's faces are drawn"); + // On Wireframe the members are drawn as they are without a map. + let wire = art(json!({"mapInvisible": true, "surface": "wireframe"})); + let mut strokes = 0; + wire.walk(&mut |n| strokes += usize::from(n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(_))))); + assert!(strokes > 0); +} + +#[test] +fn a_revolved_group_past_its_shared_limits_lists_no_surface() { + let gray = Color::rgb(0.5, 0.5, 0.5); + // Profiles of five anchors each; one alone fits Revolve's limits. + let profile = |id: u64, x: f64| { + let mut b = BezPath::new(); + b.move_to((x, 0.0)); + for i in 1..5 { + b.line_to((x + f64::from(i % 2), f64::from(i) * 10.0)); + } + Arc::new(Node::path(NodeId(id), PathData::from_bezpath(&b), Appearance::basic(Paint::None, Paint::solid(gray), 1.0))) + }; + let group = |count: u64| { + let mut g = Node::group(NodeId(7), (0..count).map(|k| profile(k + 8, 100.0 + k as f64 * 0.01)).collect()); + g.appearance.effects.push(crate::new_effect(CLASSIC_REVOLVE, &json!({})).unwrap()); + g + }; + let d = document(); + assert_eq!(map_surfaces_at(Some(&d), &group(2), None, 0).map(|s| s.len()), Some(1)); + // 4,000 of them together are past the anchors the members share. + assert!(map_surfaces_at(Some(&d), &group(4000), None, 0).is_none()); +} + +#[test] +fn an_extruded_group_past_the_faces_of_one_object_lists_no_surface() { + // Polygons of 1,000 corners: each solid alone has about 1,000 faces. + let polygon = |id: u64, x: f64| { + let mut b = BezPath::new(); + for i in 0..1000 { + let a = f64::from(i) * std::f64::consts::TAU / 1000.0; + let p = (x + 40.0 * a.cos(), 40.0 * a.sin()); + if i == 0 { b.move_to(p) } else { b.line_to(p) } + } + b.close_path(); + Arc::new(Node::path(NodeId(id), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(RED), Paint::None, 0.0))) + }; + let group = |count: u64| { + let mut g = Node::group(NodeId(7), (0..count).map(|k| polygon(k + 8, k as f64 * 100.0)).collect()); + g.appearance.effects.push(crate::new_effect(CLASSIC_EXTRUDE, &json!({"drawHiddenFaces": true})).unwrap()); + g + }; + let d = document(); + assert!(map_surfaces_at(Some(&d), &group(2), None, 0).is_some()); + // 200 of them together have more faces than one object draws. + assert!(map_surfaces_at(Some(&d), &group(200), None, 0).is_none()); +} + +#[test] +fn bad_maps_are_refused() { + let d = document(); + let check = |id: &str, p: Value| { + let n = object(id, json!({})); + validate_three_d_in(Some(&d), &n, id, &crate::merged_params(id, &p)) + }; + assert_eq!(check(CLASSIC_EXTRUDE, json!({"mapArt": [{"surface": 3, "symbol": "Mark", "scaleX": 50}]})), Ok(())); + assert_eq!(check(CLASSIC_REVOLVE, json!({"mapArt": [{"surface": 1, "symbol": "Mark"}], "mapShade": true})), Ok(())); + for (p, error) in [ + (json!({"mapArt": {}}), "`mapArt` must be an array"), + (json!({"mapArt": [7]}), "each of `mapArt` must be an object"), + (json!({"mapArt": [{"symbol": "Mark"}]}), "needs `surface`"), + (json!({"mapArt": [{"surface": 0, "symbol": "Mark"}]}), "needs `surface`"), + (json!({"mapArt": [{"surface": 1.5, "symbol": "Mark"}]}), "needs `surface`"), + (json!({"mapArt": [{"surface": 100001, "symbol": "Mark"}]}), "needs `surface`"), + (json!({"mapArt": [{"surface": 1}]}), "needs `symbol`"), + (json!({"mapArt": [{"surface": 1, "symbol": "Mark", "face": "front"}]}), "not `face`"), + (json!({"mapArt": [{"surface": 1, "symbol": "Mark", "scaleX": 0}]}), "scaleX must be a number from 1 to 10000"), + (json!({"mapArt": [{"surface": 1, "symbol": "Mark", "rotation": 361}]}), "rotation must be a number from -360 to 360"), + (json!({"mapArt": [{"surface": 1, "symbol": "Mark", "x": "left"}]}), "x must be a number"), + (json!({"mapArt": [{"surface": 1, "symbol": "Mark"}, {"surface": 1, "symbol": "Corner"}]}), "maps surface 1 more than once"), + (json!({"mapShade": 1}), "`mapShade` must be true or false"), + (json!({"mapInvisible": "yes"}), "`mapInvisible` must be true or false"), + ] { + for id in [CLASSIC_EXTRUDE, CLASSIC_REVOLVE] { + let e = check(id, p.clone()).unwrap_err(); + assert!(e.contains(error), "{id} {p}: {e}"); + } + } + let many: Vec = (1..=65).map(|k| json!({"surface": k, "symbol": "Mark"})).collect(); + assert!(check(CLASSIC_EXTRUDE, json!({"mapArt": many})).unwrap_err().contains("at most 64 maps")); + // Rotate (Classic) has no surface to map onto. + let e = check(CLASSIC_ROTATE, json!({"mapArt": [{"surface": 1, "symbol": "Mark"}]})).unwrap_err(); + assert!(e.contains(MAP_ART_NOT_TAKEN), "{e}"); +} + +#[test] +fn a_mapped_symbol_past_the_limits_of_a_graphics_art_is_refused() { + let mut d = document(); + // A zigzag of more straight sides than one 3D effect's graphics may draw. + let mut b = BezPath::new(); + b.move_to((0.0, 0.0)); + for i in 1..=MAX_ELEMENTS { + b.line_to((i as f64 * 0.001, (i % 2) as f64)); + } + b.close_path(); + let dense = Node::path(NodeId(0), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(RED), Paint::None, 0.0)); + d.symbols.push(Symbol { dynamic: false, name: "Dense".into(), art: Arc::new(dense) }); + for id in [CLASSIC_EXTRUDE, CLASSIC_REVOLVE] { + let p = crate::merged_params(id, &json!({"mapArt": [{"surface": 1, "symbol": "Dense"}]})); + let e = validate_three_d_in(Some(&d), &object(id, json!({})), id, &p).unwrap_err(); + assert!(e.contains("too complex"), "{id}: {e}"); + } + // On a fill, as on the object. + let plain = square(7, Rect::new(0.0, 0.0, 100.0, 100.0), Color::rgb(0.5, 0.5, 0.5)); + let p = crate::merged_params(CLASSIC_REVOLVE, &json!({"mapArt": [{"surface": 1, "symbol": "Dense"}]})); + let e = validate_three_d_at_in(Some(&d), &plain, CLASSIC_REVOLVE, &p, (Some(0), 0)).unwrap_err(); + assert!(e.contains("too complex"), "{e}"); +} + +#[test] +fn a_mapped_symbol_whose_curves_cut_into_too_many_pieces_is_refused() { + let mut d = document(); + // Large circles: a few curves each, but many straight pieces once they are cut. + let loops = |name: &str, count: usize| { + let mut b = BezPath::new(); + for k in 0..count { + let r = 1e5; + let circle = vectorcraft_geom::kurbo::Circle::new((k as f64 * 2.1 * r, 0.0), r); + b.extend(vectorcraft_geom::kurbo::Shape::path_elements(&circle, 0.1)); + } + let art = Node::path(NodeId(0), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(RED), Paint::None, 0.0)); + Symbol { dynamic: false, name: name.into(), art: Arc::new(art) } + }; + d.symbols.push(loops("Loop", 1)); + d.symbols.push(loops("Loops", 400)); + let check = |id: &str, surface: usize, symbol: &str| { + let p = crate::merged_params(id, &json!({"mapArt": [{"surface": surface, "symbol": symbol}]})); + validate_three_d_in(Some(&d), &object(id, json!({})), id, &p) + }; + // Extrude & Bevel's surface 3 is a wall, and Revolve's surface 1 its side. + for (id, surface) in [(CLASSIC_EXTRUDE, 3), (CLASSIC_REVOLVE, 1)] { + assert_eq!(check(id, surface, "Loop"), Ok(()), "{id}"); + let e = check(id, surface, "Loops").unwrap_err(); + assert!(e.contains("too complex"), "{id}: {e}"); + } + // A cap draws the curves as they are, without cutting them. + assert_eq!(check(CLASSIC_EXTRUDE, 1, "Loops"), Ok(())); +} + +#[test] +fn maps_are_set_cleared_and_renamed_with_their_symbols() { + let p = json!({"depth": 20}); + let map = + |surface: usize, symbol: &str| SurfaceMap { surface, symbol: symbol.into(), x: 0.0, y: 0.0, scale_x: 100.0, scale_y: 100.0, rotation: 0.0 }; + let p = with_surface_map(&p, 4, Some(&map(4, "Mark"))); + let p = with_surface_map(&p, 2, Some(&map(2, "Corner"))); + let p = with_surface_map(&p, 4, Some(&map(4, "Corner"))); + // One map for a surface, in the order of the surfaces; the other parameters stay. + assert_eq!(surface_maps(&p), vec![map(2, "Corner"), map(4, "Corner")]); + assert_eq!(p["depth"], json!(20)); + assert_eq!(surface_maps(&with_surface_map(&p, 2, None)), vec![map(4, "Corner")]); + // A file's maps: entries that are not valid and a surface's second map are left out. + let loaded = json!({"mapArt": [{"surface": 1, "symbol": "Mark"}, {"surface": 1, "symbol": "Corner"}, {"surface": 0, "symbol": "Mark"}, 3]}); + assert_eq!(surface_maps(&loaded), vec![map(1, "Mark")]); + // Renaming a symbol renames it in the maps of the effects that take them. + let mut n = object(CLASSIC_EXTRUDE, json!({"mapArt": [{"surface": 1, "symbol": "Mark"}]})); + assert_eq!(super::super::graphic_symbols(&n), vec!["Mark".to_string()]); + assert!(super::super::rename_graphic_symbol(&mut n, "Mark", "Logo")); + assert_eq!(surface_maps(&n.appearance.effects[0].params)[0].symbol, "Logo"); + // Scale to Fit fills the surface: each side by its own scale when the art is square to it. + assert_eq!(map(1, "Mark").fitting_scales(Rect::new(0.0, 0.0, 10.0, 10.0), (100.0, 50.0)), Some((1000.0, 500.0))); + let turned = SurfaceMap { rotation: 90.0, ..map(1, "Mark") }; + assert_eq!(turned.fitting_scales(Rect::new(0.0, 0.0, 10.0, 20.0), (100.0, 50.0)), Some((500.0, 500.0))); + let aslant = SurfaceMap { rotation: 45.0, ..map(1, "Mark") }; + let (sx, sy) = aslant.fitting_scales(Rect::new(0.0, 0.0, 10.0, 10.0), (100.0, 50.0)).unwrap(); + assert!((sx - sy).abs() < 1e-9 && (sx - 50.0 / (20.0 * 0.5f64.sqrt()) * 100.0).abs() < 1e-6, "{sx} {sy}"); + assert_eq!(map(1, "Mark").fitting_scales(Rect::new(0.0, 0.0, 0.0, 10.0), (100.0, 50.0)), None); +} diff --git a/crates/engine/examples/appearance_rows_bench.rs b/crates/engine/examples/appearance_rows_bench.rs new file mode 100644 index 0000000000..13606fb7e2 --- /dev/null +++ b/crates/engine/examples/appearance_rows_bench.rs @@ -0,0 +1,164 @@ +//! `cargo run --release -p vectorcraft-engine --example appearance_rows_bench` prints the time three Appearance row edits +//! take with every path of documents of 2,000, 10,000 and 20,000 squares selected, each square with one fill row and one +//! stroke row. For each size it first times the step that keeps the objects whose shown rows the edit wrote, on the same +//! ids, two ways: each id looked up in the list of written objects (a list of ids, and a list of ids with the kind of row, +//! as the commands held them), and each id looked up in a set built from that list. It checks that both ways keep the +//! same ids in the same order. Then it times the whole `appearance.setItem` (`index` 1, `weight` 2), +//! `appearance.duplicateItem` (`index` 0) and `stroke.set` (`item` 1, `weight` 2) commands, each on a fresh copy of the +//! document made before the clock starts. +//! 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. The two lookup +//! ways run in alternating order. +// 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}; +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) +} + +/// 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` closed 10 pt squares, each with a red fill row and a 1 pt black stroke row, and their ids in paint order. +fn document(n: usize) -> (Document, Vec) { + let mut doc = Document::new(4000.0, 4000.0); + let layer = doc.layers.first().map(|l| l.id); + let mut ids = Vec::with_capacity(n); + for i in 0..n { + let (x, y) = ((i % 200) as f64 * 12.0, (i / 200) 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(); + let looks = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::solid(Color::BLACK), 1.0); + doc.insert(layer, usize::MAX, Node::path(id, path, looks)).unwrap(); + ids.push(id); + } + (doc, ids) +} + +/// The ids among `ids` that `wrote` holds, each looked up in the list: the lookup the row edits made. +fn in_list(ids: Vec, wrote: &[NodeId]) -> Vec { + ids.into_iter().filter(|id| wrote.contains(id)).collect() +} + +/// [`in_list`] with each id looked up in a set built from `wrote`. +fn in_set(ids: Vec, wrote: &[NodeId]) -> Vec { + let wrote: HashSet = wrote.iter().copied().collect(); + ids.into_iter().filter(|id| wrote.contains(id)).collect() +} + +/// The ids among `ids` that `edited` holds with either kind of row, each looked up in the list, as `appearance.setItem` +/// did. +fn in_kind_list(ids: Vec, edited: &[(NodeId, bool)]) -> Vec { + ids.into_iter().filter(|id| edited.iter().any(|(e, _)| e == id)).collect() +} + +/// [`in_kind_list`] with each id looked up in a set built from the ids of `edited`. +fn in_kind_set(ids: Vec, edited: &[(NodeId, bool)]) -> Vec { + let wrote: HashSet = edited.iter().map(|(id, _)| *id).collect(); + ids.into_iter().filter(|id| wrote.contains(id)).collect() +} + +fn row(name: &str, ms: f64) { + println!(" {name:<52} {ms:>10.3} ms"); +} + +/// The medians of `old` and `new` over [`iters`] runs, alternating which goes first; each run filters `ids` `reps` times +/// on copies made before the clock starts and gives the time of one. +fn time_both(ids: &[NodeId], wrote: &W, old: fn(Vec, &W) -> Vec, new: fn(Vec, &W) -> Vec) -> (f64, f64) { + let reps = (200_000 / ids.len()).max(1); + let run = |f: fn(Vec, &W) -> Vec| { + let mut work: Vec> = (0..reps).map(|_| ids.to_vec()).collect(); + ms(|| { + for it in &mut work { + black_box(f(black_box(std::mem::take(it)), wrote)); + } + }) / reps as f64 + }; + let (mut a, mut b) = (vec![], vec![]); + for i in 0..iters() { + if i % 2 == 0 { + a.push(run(old)); + b.push(run(new)); + } else { + b.push(run(new)); + a.push(run(old)); + } + } + (median(a), median(b)) +} + +fn bench(n: usize) { + println!("{n} squares, all selected"); + let (doc, ids) = document(n); + // Every object's topmost stroke row was written, as when every selected object takes the edit. + let edited: Vec<(NodeId, bool)> = ids.iter().map(|id| (*id, false)).collect(); + // A list missing every other id, so lookups that fail are timed too. + let half: Vec = ids.iter().copied().step_by(2).collect(); + for wrote in [&ids, &half] { + assert_eq!(in_list(ids.clone(), wrote), in_set(ids.clone(), wrote), "both ways keep the same ids"); + } + assert_eq!(in_kind_list(ids.clone(), &edited), in_kind_set(ids.clone(), &edited), "both ways keep the same ids"); + let (old, new) = time_both(&ids, ids.as_slice(), in_list, in_set); + row("keep written ids, every id in the list", old); + row("keep written ids, every id in a set", new); + let (old, new) = time_both(&ids, half.as_slice(), in_list, in_set); + row("keep written ids, half the ids in the list", old); + row("keep written ids, half the ids in a set", new); + let (old, new) = time_both(&ids, edited.as_slice(), in_kind_list, in_kind_set); + row("keep written ids, (id, kind) list", old); + row("keep written ids, (id, kind) set", new); + + let all: Vec = ids.iter().map(|id| id.0).collect(); + let commands: [(&str, Value); 3] = [ + ("appearance.setItem", json!({"ids": all, "index": 1, "weight": 2})), + ("appearance.duplicateItem", json!({"ids": all, "index": 0})), + ("stroke.set", json!({"ids": all, "item": 1, "weight": 2})), + ]; + for (cmd, p) in &commands { + let runs = (0..iters()) + .map(|_| { + let mut s = Session::new(); + s.add_document(doc.clone(), None); + let t = ms(|| drop(black_box(s.execute(cmd, p).unwrap()))); + drop(black_box(s)); + t + }) + .collect(); + row(&format!("{cmd}, whole command"), median(runs)); + } +} + +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 359fc8761f..dd0e318f8d 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -48,6 +48,7 @@ mod info; pub(crate) mod inline; mod interactivity; mod intertwine; +pub mod kinsokusets; pub(crate) mod layer; mod layerpanel; pub mod library; @@ -335,6 +336,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(textstyles::specs()); v.extend(fonts::specs()); v.extend(compositefonts::specs()); + v.extend(kinsokusets::specs()); v.extend(fontfiles::specs()); v.extend(help::specs()); v.extend(toast::specs()); @@ -923,6 +925,10 @@ pub use buildcmds::live_paint_gaps; /// Control bar enable it when it changes one). pub use brushsym::reset_transformation_changes; +/// Whether an object is a symbol set (the Symbolism Tools Options' Symbol Set Density applies to +/// the selected ones). +pub use brushsym::is_symbol_set; + /// The Symbols panel's current symbol, as `symbol.list` answers it (the panel reads it on every /// frame without running the command). pub use brushsym::current_symbol; diff --git a/crates/engine/src/cmd/addons/pathtools.rs b/crates/engine/src/cmd/addons/pathtools.rs index 2d1ded312f..586dc9947e 100644 --- a/crates/engine/src/cmd/addons/pathtools.rs +++ b/crates/engine/src/cmd/addons/pathtools.rs @@ -4,11 +4,12 @@ //! ([`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`]), Smooth Bridge ([`bridge`]), Common Tangents -//! ([`tangents`]) and Tangent Circle -//! ([`tangent_circle`]). +//! ([`tangents`]), Tangent Circle ([`tangent_circle`]) and Add Bounding Rectangle and Add +//! Bounding Circle ([`bounding`]). //! Its tools, panels and submenu (Object › Plug-ins › Path Precision Tools) are the tools crate's //! and the UI's. +mod bounding; mod bridge; mod corners; #[cfg(test)] @@ -188,6 +189,7 @@ pub fn specs() -> Vec { v.extend(bridge::specs()); v.extend(tangent_circle::specs()); v.extend(tangents::specs()); + v.extend(bounding::specs()); v } diff --git a/crates/engine/src/cmd/addons/pathtools/bounding.rs b/crates/engine/src/cmd/addons/pathtools/bounding.rs new file mode 100644 index 0000000000..954a4f829a --- /dev/null +++ b/crates/engine/src/cmd/addons/pathtools/bounding.rs @@ -0,0 +1,376 @@ +//! Add Bounding Rectangle and Add Bounding Circle: a live rectangle on the selection's geometric +//! bounding box, or the smallest live circle around its outlines. The circle is the geometry crate's +//! ([`enclosing_circle`](vectorcraft_geom::shapes::enclosing_circle)). + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, LiveShape, Node, NodeId, NodeKind, SymbolBoxes}; +use vectorcraft_geom::kurbo::ParamCurveExtrema; +use vectorcraft_geom::{Affine, CubicBez, FillRule, ParamCurve, PathSeg, Point, Rect, shapes}; + +use super::super::super::edit::{no_symbol_part, selected_roots_to_transform}; +use super::super::super::{CommandSpec, bad, cmd, has_selection, number_or, switch_or}; +use crate::sanity::rect_in_range; +use crate::{Result, Session}; + +#[cfg(test)] +mod tests; + +/// Add Bounding Rectangle's command. +pub(crate) const RECTANGLE: &str = "addon.pathtools.boundingRectangle"; +/// Add Bounding Circle's command. +pub(crate) const CIRCLE: &str = "addon.pathtools.boundingCircle"; + +/// How far a curve may stray from the points the circle is fitted to, in points. The circle's +/// radius grows by as much, so it holds the curves themselves. +const FLATNESS: f64 = 0.01; + +pub(super) fn specs() -> Vec { + vec![ + cmd!( + "addon.pathtools.boundingRectangle", + "Add Bounding Rectangle", + ["Object", "Plug-ins", "Path Precision Tools"], + None, + "{each?: bool (default false: one rectangle around the whole selection; true: one around each selected object), offset?: pt (0 or more; default 0: added on every side)} draw a live rectangle on the geometric bounding box of the selected objects (strokes and effects left out; a path of a compound path selected on its own counts as an object), with the current paint, on top of the current layer or of the isolated group, as other new art; the rectangles are selected; one undo step. An object whose box has no width or no height (a straight horizontal or vertical line) gets no rectangle unless `offset` is more than 0, nor does an object with no bounds (an empty group); with `each` the result's `skipped` counts them. It is an error when no rectangle is left (\"the shape would have no size\" when a rectangle with no size was left out, else \"nothing to enclose\") and when an edge of a rectangle would lie more than 4,000,000 pt from the origin along either axis (\"the shape would reach past the edge of the canvas\"). The menu item Add Bounding Rectangle… opens a dialog with Offset and One per Object (`each`) and a Preview → {id: the first rectangle, ids, skipped?}", + whole_objects, + bounding_rectangle + ), + cmd!( + "addon.pathtools.boundingCircle", + "Add Bounding Circle", + ["Object", "Plug-ins", "Path Precision Tools"], + None, + "{each?: bool (default false: one circle around the whole selection; true: one around each selected object), offset?: pt (0 or more; default 0: added to the radius)} draw the smallest live circle that holds the outlines of the selected objects (paths and compound paths by their curves, clip groups and sublayers that clip their contents by their clipping paths, other sublayers by their shown objects, images by their corners, type and other objects by the corners of their bounding box; strokes and effects left out; a path of a compound path selected on its own counts as an object), with the radius 0.01 pt larger so it holds the curves themselves, with the current paint, on top of the current layer or of the isolated group, as other new art; the circles are selected; one undo step. An object at a single point gets no circle unless `offset` is more than 0, nor does an object with no outline (an empty group); with `each` the result's `skipped` counts them. It is an error when no circle is left (\"the shape would have no size\" when a circle with no size was left out, else \"nothing to enclose\") and when an edge of a circle's bounding box would lie more than 4,000,000 pt from the origin along either axis (\"the shape would reach past the edge of the canvas\"). The menu item Add Bounding Circle… opens a dialog with Offset and One per Object (`each`) and a Preview → {id: the first circle, ids, skipped?}", + whole_objects, + bounding_circle + ), + ] +} + +/// Enabled with a selection that is not an object of a symbol instance's art, which +/// [`selected_roots_to_transform`] refuses. +fn whole_objects(s: &Session) -> std::result::Result<(), String> { + has_selection(s)?; + no_symbol_part(s) +} + +/// The shape a command draws. +#[derive(Clone, Copy, PartialEq)] +enum Kind { + Rectangle, + Circle, +} + +fn bounding_rectangle(s: &mut Session, p: &Value) -> Result { + add(s, p, Kind::Rectangle) +} + +fn bounding_circle(s: &mut Session, p: &Value) -> Result { + add(s, p, Kind::Circle) +} + +fn add(s: &mut Session, p: &Value, kind: Kind) -> Result { + let (c, label) = match kind { + Kind::Rectangle => (RECTANGLE, "Add Bounding Rectangle"), + Kind::Circle => (CIRCLE, "Add Bounding Circle"), + }; + let each = switch_or(p, "each", false, c)?; + let offset = number_or(p, "offset", 0.0, c)?; + if !(offset.is_finite() && offset >= 0.0) { + return Err(bad(c, "`offset` must be 0 or more")); + } + // The objects `object.transform` moves: a path of a compound path selected on its own is one. + let roots = selected_roots_to_transform(s)?; + let d = &s.doc()?.doc; + let symbols = d.symbol_boxes(); + let groups: Vec> = if each { roots.iter().map(|id| vec![*id]).collect() } else { vec![roots] }; + let mut made: Vec = vec![]; + // Objects that get no shape: no outline, or a shape with no size. + let mut skipped = 0; + let mut no_size = false; + // The shapes share the halvings, so the work stays bounded however many objects are selected. + let splits = split_share(groups.len()); + for ids in &groups { + match shape_around(d, &symbols, ids, kind, offset, splits) { + Around::Shape(live) => made.push(live), + Around::NoOutline => skipped += 1, + Around::NoSize => { + skipped += 1; + no_size = true; + } + Around::PastCanvas => return Err(bad(c, "the shape would reach past the edge of the canvas")), + } + } + if made.is_empty() { + return Err(bad(c, if no_size { "the shape would have no size" } else { "nothing to enclose" })); + } + let parent = s.doc()?.target_parent()?; + let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width); + let ids = s.edit(label, |d, sel| { + let mut ids = vec![]; + for live in made { + let kind = NodeKind::Path { path: live.to_path(), rule: FillRule::NonZero, live: Some(Box::new(live)), clipping: false, guide: false }; + let mut n = Node::new(d.alloc_id(), kind); + look.apply(d, &mut n); + ids.push(n.id); + d.insert(parent, usize::MAX, n)?; + } + sel.set(ids.iter().copied()); + Ok(ids) + })?; + let first = ids.first().map_or(0, |id| id.0); + let mut out = json!({ "id": first, "ids": ids.iter().map(|i| i.0).collect::>() }); + if skipped > 0 { + out["skipped"] = json!(skipped); + } + Ok(out) +} + +/// What [`shape_around`] finds. +enum Around { + Shape(LiveShape), + /// The objects have no bounds or no outline. + NoOutline, + /// The rectangle would have no width or no height, or the circle no radius. + NoSize, + /// An edge of the shape would lie more than [`MAX_COORD`](crate::MAX_COORD) from the origin + /// along either axis. + PastCanvas, +} + +/// The live rectangle or circle around `ids`, grown by `offset`. A circle halves its curves as +/// `splits` allows. +fn shape_around(d: &Document, symbols: &SymbolBoxes, ids: &[NodeId], kind: Kind, offset: f64, splits: Splits) -> Around { + match kind { + Kind::Rectangle => { + let Some(r) = d.bounds_of_with(ids, false, symbols) else { return Around::NoOutline }; + let r = r.inflate(offset, offset); + if !rect_in_range(r) { + return Around::PastCanvas; + } + if r.width() <= 0.0 || r.height() <= 0.0 { + return Around::NoSize; + } + Around::Shape(LiveShape::Rectangle { + w: r.width(), + h: r.height(), + radii: [0.0; 4], + kinds: Default::default(), + radii_relative: false, + xf: Affine::translate(r.origin().to_vec2()), + }) + } + Kind::Circle => { + let mut gathered = Gathered::new(); + gathered.splits = splits; + for n in ids.iter().filter_map(|id| d.node(*id)) { + outline_points(n, symbols, &mut gathered, 0); + gathered.compact(); + } + let Some((center, radius)) = shapes::enclosing_circle(&gathered.points) else { return Around::NoOutline }; + if radius + offset <= 0.0 { + return Around::NoSize; + } + let r = radius + FLATNESS + offset; + let b = Rect::new(center.x - r, center.y - r, center.x + r, center.y + r); + if !rect_in_range(b) { + return Around::PastCanvas; + } + Around::Shape(LiveShape::Ellipse { w: b.width(), h: b.height(), pie: (0.0, 360.0), xf: Affine::translate(b.origin().to_vec2()) }) + } + } +} + +/// Adds to `out` points on the outline of `n`, as its geometric bounds measure it: the points of +/// its paths ([`curve_points`]); the clipping path of a clip group or of a sublayer that clips its +/// contents; the shown contents of a sublayer (a layer that an opened file put inside a group); the +/// corners of an image; and the corners of the geometric bounding box of anything else. A group or +/// layer `depth` levels below the selected object that is nested deeper than a document holds +/// ([`vectorcraft_doc::MAX_DEPTH`]) counts by the corners of its geometric bounding box. +fn outline_points(n: &Node, symbols: &SymbolBoxes, out: &mut Gathered, depth: usize) { + let nests = matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. } | NodeKind::Compound { .. }); + if nests && depth >= vectorcraft_doc::MAX_DEPTH { + out.points.extend(n.geometric_bounds_with(symbols).map(corners).into_iter().flatten()); + return; + } + match &n.kind { + NodeKind::Path { path, .. } => { + // The anchors count too, so a path of one anchor, which has no segments, is held. + for p in path.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p)) { + out.points.push(p); + out.compact(); + } + for seg in path.to_bezpath().segments() { + match seg { + PathSeg::Line(l) => out.points.extend([l.p0, l.p1]), + _ => curve_points(seg.to_cubic(), 0, &mut out.points, &mut out.splits), + } + out.compact(); + } + } + NodeKind::Group { children, clip: true } | NodeKind::Layer { children, clip: true, .. } => { + if let Some(c) = children.first() { + outline_points(c, symbols, out, depth + 1); + } + } + NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Compound { .. } => { + let layer = matches!(n.kind, NodeKind::Layer { .. }); + for c in n.editing_children().iter().filter(|c| c.visible || !layer) { + outline_points(c, symbols, out, depth + 1); + out.compact(); + } + } + NodeKind::Image(im) => { + let r = Rect::new(0.0, 0.0, im.width as f64, im.height as f64); + out.points.extend(corners(r).map(|p| im.xf * p)); + } + _ => out.points.extend(n.geometric_bounds_with(symbols).map(corners).into_iter().flatten()), + } +} + +/// Adds to `out` points whose convex hull, grown by [`FLATNESS`], holds the curve `c`: the ends of +/// pieces whose control points lie within [`FLATNESS`] of their chord, and for pieces still curved +/// after [`MAX_SPLITS`] halvings, or when `splits` allows no more ([`Splits::take`]), the corners of +/// [`held`]. A flat piece that ends where it starts adds its control points too, so a small loop is +/// not taken for a single point. A curve with a point that is not finite adds nothing. +fn curve_points(c: CubicBez, depth: u32, out: &mut Vec, splits: &mut Splits) { + if ![c.p0, c.p1, c.p2, c.p3].iter().all(|p| p.is_finite()) { + return; + } + let flat = [c.p1, c.p2].iter().all(|p| distance_to_segment(*p, c.p0, c.p3) <= FLATNESS); + if flat { + out.extend([c.p0, c.p3]); + if c.p0 == c.p3 { + out.extend([c.p1, c.p2]); + } + } else if depth >= MAX_SPLITS || !splits.take(depth) { + out.extend(held(c)); + } else { + let (a, b) = c.subdivide(); + curve_points(a, depth + 1, out, splits); + curve_points(b, depth + 1, out, splits); + } +} + +/// The corners of the convex hull of `c`'s control points cut down to `c`'s bounding box. Each of +/// the two holds the curve, so the part they share holds it too. When the cut leaves nothing, which +/// rounding can cause, it gives the box's corners. +fn held(c: CubicBez) -> Vec { + let b = ParamCurveExtrema::bounding_box(&c); + let mut poly = shapes::convex_hull(vec![c.p0, c.p1, c.p2, c.p3]); + for (x, bound, below) in [(true, b.x0, false), (true, b.x1, true), (false, b.y0, false), (false, b.y1, true)] { + poly = clip(&poly, x, bound, below); + } + if poly.is_empty() { corners(b).to_vec() } else { poly } +} + +/// The convex polygon `poly` cut at `bound` on the x axis (`x`) or the y axis: the part at or below +/// `bound` when `below`, else at or above it. +fn clip(poly: &[Point], x: bool, bound: f64, below: bool) -> Vec { + let v = |p: Point| if x { p.x } else { p.y }; + let inside = |p: Point| if below { v(p) <= bound } else { v(p) >= bound }; + let mut out = vec![]; + for (&a, &b) in poly.iter().zip(poly.iter().cycle().skip(1)) { + if inside(a) { + out.push(a); + } + if inside(a) != inside(b) { + let mut p = a.lerp(b, (bound - v(a)) / (v(b) - v(a))); + if x { + p.x = bound; + } else { + p.y = bound; + } + out.push(p); + } + } + out +} + +/// How many halvings [`curve_points`] makes for one command, over every curve it measures, before +/// it halves each further curve [`MIN_SPLITS`] times only; with `each`, every shape gets an equal +/// share ([`split_share`]). +const TOTAL_SPLITS: usize = 1 << 20; + +/// How many more halvings [`curve_points`] makes for one command once [`TOTAL_SPLITS`] is used up, +/// each within the first [`MIN_SPLITS`] halvings of a curve; with `each`, shared as +/// [`TOTAL_SPLITS`] is. After that, curves count by [`held`] whole. +const EARLY_SPLITS: usize = 7 << 20; + +/// How many times [`curve_points`] halves a curve once [`TOTAL_SPLITS`] is used up: 8 pieces, which +/// keeps the circle fitted to a circle of four curves less than 0.3% larger than that circle. +const MIN_SPLITS: u32 = 3; + +/// The halvings [`curve_points`] may still make. +#[derive(Clone, Copy, Debug, PartialEq)] +struct Splits { + /// Halvings at any depth. + any: usize, + /// Halvings within the first [`MIN_SPLITS`] of a curve, once `any` is used up. + early: usize, +} + +impl Splits { + /// Takes one halving of a piece `depth` halvings into its curve; false when none is left. + fn take(&mut self, depth: u32) -> bool { + if self.any > 0 { + self.any -= 1; + } else if depth < MIN_SPLITS && self.early > 0 { + self.early -= 1; + } else { + return false; + } + true + } +} + +/// The halvings each of `shapes` shapes may make: an equal share of [`TOTAL_SPLITS`] and of +/// [`EARLY_SPLITS`]. +fn split_share(shapes: usize) -> Splits { + let n = shapes.max(1); + Splits { any: TOTAL_SPLITS / n, early: EARLY_SPLITS / n } +} + +/// How many points [`outline_points`] gathers before it keeps only the corners of their convex hull. +const COMPACT_AT: usize = 1 << 16; + +/// Points gathered for a circle, kept down to the corners of their convex hull whenever they grow +/// past `limit`: only the hull decides the circle. The points held stay within about twice the +/// hull's corners, and grow only with the anchors and objects measured and the halvings +/// ([`TOTAL_SPLITS`] and [`EARLY_SPLITS`]). +struct Gathered { + points: Vec, + limit: usize, + /// The halvings [`curve_points`] may still make (one shape's whole share at first). + splits: Splits, +} + +impl Gathered { + fn new() -> Self { + Self { points: vec![], limit: COMPACT_AT, splits: split_share(1) } + } + + /// Keeps only the hull's corners once there are more than `limit` points; the next time waits + /// until there are twice as many as the hull has, so each point is sorted a few times at most. + fn compact(&mut self) { + if self.points.len() > self.limit { + self.points = shapes::convex_hull(std::mem::take(&mut self.points)); + self.limit = (self.points.len() * 2).max(COMPACT_AT); + } + } +} + +/// How many times [`curve_points`] halves a curve at most: up to 1,024 pieces. +const MAX_SPLITS: u32 = 10; + +/// The distance from `p` to the segment from `a` to `b`. +fn distance_to_segment(p: Point, a: Point, b: Point) -> f64 { + let ab = b - a; + let len2 = ab.hypot2(); + let t = if len2 > 0.0 { ((p - a).dot(ab) / len2).clamp(0.0, 1.0) } else { 0.0 }; + (p - (a + ab * t)).hypot() +} + +fn corners(r: Rect) -> [Point; 4] { + [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)] +} diff --git a/crates/engine/src/cmd/addons/pathtools/bounding/tests.rs b/crates/engine/src/cmd/addons/pathtools/bounding/tests.rs new file mode 100644 index 0000000000..15d037aee3 --- /dev/null +++ b/crates/engine/src/cmd/addons/pathtools/bounding/tests.rs @@ -0,0 +1,557 @@ +//! Add Bounding Rectangle and Add Bounding Circle: the box and the smallest circle, the current +//! paint and placement on top of the current layer or the isolated group, `each` and `skipped`, +//! shapes of no size, clip groups and clipping sublayers, paths of compound paths, huge curves and +//! small loops, and the errors that leave the document as it was. + +use serde_json::{Value, json}; +use vectorcraft_doc::{LiveShape, Node, NodeId, NodeKind}; +use vectorcraft_geom::{CubicBez, Point, Rect, Vec2, shapes}; + +use super::{CIRCLE, COMPACT_AT, Gathered, RECTANGLE, Splits}; +use crate::Session; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + s +} + +fn node(s: &Session, id: NodeId) -> Node { + s.doc().unwrap().doc.node(id).unwrap().clone() +} + +fn id_of(v: &Value) -> NodeId { + NodeId(v["id"].as_u64().unwrap()) +} + +fn ids_of(v: &Value) -> Vec { + v["ids"].as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect() +} + +fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId { + id_of(&s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap()) +} + +fn undo_len(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn object_count(s: &Session) -> usize { + let mut n = 0; + s.doc().unwrap().doc.walk(|_| n += 1); + n +} + +/// Whether two rectangles agree to within `tol` on every edge. +fn rect_near(b: Rect, want: Rect, tol: f64) -> bool { + [(b.x0, want.x0), (b.y0, want.y0), (b.x1, want.x1), (b.y1, want.y1)].iter().all(|(a, w)| (a - w).abs() < tol) +} + +/// The live shape of `id`. +fn live(s: &Session, id: NodeId) -> LiveShape { + match &node(s, id).kind { + NodeKind::Path { live: Some(live), .. } => live.as_ref().clone(), + other => panic!("not a live shape: {other:?}"), + } +} + +/// The geometric bounds of `id`. +fn bounds(s: &Session, id: NodeId) -> Rect { + s.doc().unwrap().doc.bounds_of(&[id], false).unwrap() +} + +/// The last child of `parent`, the top of its stacking order. +fn top_of(s: &Session, parent: NodeId) -> NodeId { + node(s, parent).children().unwrap().last().unwrap().id +} + +/// Runs `command` with `p` and checks that it fails and leaves the document as it was. +fn refused(s: &mut Session, command: &str, p: Value) -> String { + let (undo, objects) = (undo_len(s), object_count(s)); + let e = s.execute(command, &p).unwrap_err().to_string(); + assert_eq!((undo_len(s), object_count(s)), (undo, objects), "{p} changed the document"); + e +} + +/// A live rectangle on the selection's geometric bounding box, strokes left out, with the current +/// paint, on top of the current layer, selected; one undo removes it. +#[test] +fn a_bounding_rectangle_is_the_geometric_box_on_top_of_the_layer() { + let mut s = session(); + s.execute("stroke.set", &json!({"weight": 10})).unwrap(); + let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0); + let b = id_of(&s.execute("shape.ellipse", &json!({"x": 100, "y": 50, "width": 60, "height": 80})).unwrap()); + assert_eq!(node(&s, a).appearance.stroke_width(), 10.0, "the strokes reach past the geometric box"); + s.execute("select.none", &json!({})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let (before, undo) = (object_count(&s), undo_len(&s)); + let out = s.execute(RECTANGLE, &json!({})).unwrap(); + let id = id_of(&out); + assert_eq!(ids_of(&out), vec![id]); + assert!(out.get("skipped").is_none(), "{out}"); + assert!(matches!(live(&s, id), LiveShape::Rectangle { .. })); + assert!(rect_near(bounds(&s, id), Rect::new(10.0, 20.0, 160.0, 130.0), 1e-9), "{:?}", bounds(&s, id)); + let layer = s.doc().unwrap().current_layer().unwrap(); + assert_eq!(top_of(&s, layer), id); + assert_eq!(s.doc().unwrap().selection.objects, vec![id]); + assert_eq!(undo_len(&s), undo + 1); + assert_eq!(object_count(&s), before + 1); + // The current paint, as a shape drawn now gets it. + let reference = rect(&mut s, 300.0, 300.0, 5.0, 5.0); + let (n, r) = (node(&s, id), node(&s, reference)); + assert_eq!((n.appearance.fill_paint(), n.appearance.stroke_paint()), (r.appearance.fill_paint(), r.appearance.stroke_paint())); + assert_eq!(n.appearance.stroke_width(), r.appearance.stroke_width()); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(object_count(&s), before); +} + +/// A bounding circle around a right triangle stands on its hypotenuse; around a circle it is that +/// circle, grown by at most the flattening allowance; `offset` grows the radius, and a rectangle's +/// sides, by that much. +#[test] +fn a_bounding_circle_is_the_smallest_circle_around_the_outlines() { + let mut s = session(); + let tri = + id_of(&s.execute("path.create", &json!({"anchors": [{"x": 0, "y": 0}, {"x": 80, "y": 0}, {"x": 0, "y": 60}], "closed": true})).unwrap()); + s.execute("select.set", &json!({"ids": [tri.0]})).unwrap(); + let c = id_of(&s.execute(CIRCLE, &json!({})).unwrap()); + match live(&s, c) { + LiveShape::Ellipse { w, h, pie, .. } => { + assert!((w - 100.02).abs() < 1e-9 && (h - 100.02).abs() < 1e-9 && pie == (0.0, 360.0), "{w} {h}"); + } + other => panic!("not a circle: {other:?}"), + } + assert!(rect_near(bounds(&s, c), Rect::new(-10.01, -20.01, 90.01, 80.01), 1e-9), "{:?}", bounds(&s, c)); + + // A circle of radius 50 and a dot inside it: the bounding circle is the circle itself. + let round = id_of(&s.execute("shape.ellipse", &json!({"x": 200, "y": 200, "width": 100, "height": 100})).unwrap()); + let dot = rect(&mut s, 240.0, 240.0, 2.0, 2.0); + s.execute("select.set", &json!({"ids": [round.0, dot.0]})).unwrap(); + let c = id_of(&s.execute(CIRCLE, &json!({"offset": 5})).unwrap()); + let got = bounds(&s, c); + let want = Rect::new(195.0, 195.0, 305.0, 305.0); + assert!(rect_near(got, want, 0.03), "{got:?}"); + assert!(got.x0 <= want.x0 + 1e-9 && got.x1 >= want.x1 - 1e-9 && got.y0 <= want.y0 + 1e-9 && got.y1 >= want.y1 - 1e-9, "{got:?}"); + + s.execute("select.set", &json!({"ids": [tri.0]})).unwrap(); + let r = id_of(&s.execute(RECTANGLE, &json!({"offset": 4})).unwrap()); + assert!(rect_near(bounds(&s, r), Rect::new(-4.0, -4.0, 84.0, 64.0), 1e-9)); +} + +/// A shape with no size is not drawn: a straight horizontal line gets no rectangle and a path of +/// one anchor no circle, unless `offset` gives them room; with `each` they are counted in +/// `skipped`, and alone they are an error. +#[test] +fn shapes_of_no_size_are_skipped_unless_offset_gives_them_room() { + let mut s = session(); + let line = id_of(&s.execute("path.create", &json!({"anchors": [{"x": 10, "y": 50}, {"x": 90, "y": 50}]})).unwrap()); + let lone = id_of(&s.execute("path.create", &json!({"anchors": [{"x": 50, "y": 70}]})).unwrap()); + let box_ = rect(&mut s, 200.0, 200.0, 10.0, 10.0); + s.execute("select.set", &json!({"ids": [line.0]})).unwrap(); + assert!(refused(&mut s, RECTANGLE, json!({})).contains("the shape would have no size")); + let r = id_of(&s.execute(RECTANGLE, &json!({"offset": 2})).unwrap()); + assert!(rect_near(bounds(&s, r), Rect::new(8.0, 48.0, 92.0, 52.0), 1e-9), "{:?}", bounds(&s, r)); + // The line has length, so its circle has size. + s.execute("select.set", &json!({"ids": [line.0]})).unwrap(); + let c = id_of(&s.execute(CIRCLE, &json!({})).unwrap()); + assert!(rect_near(bounds(&s, c), Rect::new(9.99, 9.99, 90.01, 90.01), 1e-9), "{:?}", bounds(&s, c)); + + s.execute("select.set", &json!({"ids": [lone.0]})).unwrap(); + assert!(refused(&mut s, CIRCLE, json!({})).contains("the shape would have no size")); + let c = id_of(&s.execute(CIRCLE, &json!({"offset": 3})).unwrap()); + assert!(rect_near(bounds(&s, c), Rect::new(46.99, 66.99, 53.01, 73.01), 1e-9), "{:?}", bounds(&s, c)); + + s.execute("select.set", &json!({"ids": [line.0, lone.0, box_.0]})).unwrap(); + let out = s.execute(RECTANGLE, &json!({"each": true})).unwrap(); + assert_eq!((ids_of(&out).len(), out["skipped"].as_u64()), (1, Some(2)), "{out}"); + assert!(rect_near(bounds(&s, id_of(&out)), Rect::new(200.0, 200.0, 210.0, 210.0), 1e-9)); + s.execute("select.set", &json!({"ids": [line.0, lone.0, box_.0]})).unwrap(); + let out = s.execute(CIRCLE, &json!({"each": true})).unwrap(); + assert_eq!((ids_of(&out).len(), out["skipped"].as_u64()), (2, Some(1)), "{out}"); +} + +/// With `each`, every selected object gets a shape of its own, all in one undo step, on top of the +/// layer in the selection's stacking order, and the new shapes are selected. +#[test] +fn each_draws_one_shape_around_each_object() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + let b = rect(&mut s, 100.0, 0.0, 20.0, 30.0); + s.execute("select.set", &json!({"ids": [b.0, a.0]})).unwrap(); + let undo = undo_len(&s); + let out = s.execute(RECTANGLE, &json!({"each": true})).unwrap(); + let ids = ids_of(&out); + assert_eq!(ids.len(), 2); + assert!(rect_near(bounds(&s, ids[0]), Rect::new(0.0, 0.0, 10.0, 10.0), 1e-9)); + assert!(rect_near(bounds(&s, ids[1]), Rect::new(100.0, 0.0, 120.0, 30.0), 1e-9)); + let layer = s.doc().unwrap().current_layer().unwrap(); + let order: Vec = node(&s, layer).children().unwrap().iter().map(|n| n.id).collect(); + assert_eq!(order, vec![a, b, ids[0], ids[1]]); + assert_eq!(s.doc().unwrap().selection.objects.len(), 2); + assert_eq!(undo_len(&s), undo + 1); +} + +/// An object with no outline (an empty group) gets no shape and the result counts it; with only +/// such objects selected the command draws nothing. +#[test] +fn each_counts_the_objects_without_an_outline() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + let empty = s + .edit("Group", |d, _| { + let id = d.alloc_id(); + d.insert(d.default_layer(), 0, Node::group(id, vec![]))?; + Ok(id) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [a.0, empty.0]})).unwrap(); + let out = s.execute(CIRCLE, &json!({"each": true})).unwrap(); + assert_eq!((ids_of(&out).len(), out["skipped"].as_u64()), (1, Some(1)), "{out}"); + s.execute("select.set", &json!({"ids": [a.0, empty.0]})).unwrap(); + let out = s.execute(CIRCLE, &json!({})).unwrap(); + assert!(out.get("skipped").is_none(), "{out}"); + s.execute("select.set", &json!({"ids": [empty.0]})).unwrap(); + assert!(refused(&mut s, RECTANGLE, json!({"each": true})).contains("nothing to enclose")); +} + +/// Curves over a hundred thousand points across are held by their circle: every point along the +/// curves is inside the circle, whose radius is the 0.01 pt allowance larger than the circle around +/// the flattened points. The farthest point of the lopsided arc lies between two flattened points, +/// about 0.001 pt outside the circle around them, so it needs that allowance. +#[test] +fn the_circle_holds_huge_curves() { + let mut s = session(); + let d = "M 0 0 C 0 -90000 120000 -90000 120000 0 C 60000 40000 30000 70000 0 0 Z"; + let blob = id_of(&s.execute("path.create", &json!({"d": d})).unwrap()); + let arc = id_of(&s.execute("path.create", &json!({"d": "M 0 0 C 20 400 380 500 400 0"})).unwrap()); + for big in [blob, arc] { + s.execute("select.set", &json!({"ids": [big.0]})).unwrap(); + let c = id_of(&s.execute(CIRCLE, &json!({})).unwrap()); + let LiveShape::Ellipse { w, xf, .. } = live(&s, c) else { panic!("not a circle") }; + let (center, r) = (xf * Point::new(w / 2.0, w / 2.0), w / 2.0); + let path = node(&s, big).path_data().unwrap().to_bezpath(); + let mut farthest: f64 = 0.0; + for seg in path.segments() { + for i in 0..=4000 { + let p = vectorcraft_geom::ParamCurve::eval(&seg, f64::from(i) / 4000.0); + farthest = farthest.max(p.distance(center)); + } + } + assert!(farthest <= r + 1e-6, "a point {farthest} from the center is outside the circle of radius {r}"); + } +} + +/// Clip groups count by their clipping paths; for art inside one, the shape goes on top of the +/// current layer, never into the clip group. +#[test] +fn clip_groups_count_by_their_clipping_paths() { + let mut s = session(); + let art = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let clip = id_of(&s.execute("shape.ellipse", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap()); + s.execute("select.set", &json!({"ids": [art.0, clip.0]})).unwrap(); + let group = id_of(&s.execute("object.clippingMask.make", &json!({})).unwrap()); + s.execute("select.set", &json!({"ids": [group.0]})).unwrap(); + let id = id_of(&s.execute(CIRCLE, &json!({})).unwrap()); + let b = bounds(&s, id); + assert!((b.width() / 2.0 - 25.01).abs() < 0.03 && b.center().distance(Point::new(35.0, 35.0)) < 0.03, "{b:?}"); + let layer = s.doc().unwrap().current_layer().unwrap(); + assert_eq!(s.doc().unwrap().doc.parent_of(id), Some(layer)); + s.execute("select.set", &json!({"ids": [clip.0]})).unwrap(); + let id = id_of(&s.execute(RECTANGLE, &json!({})).unwrap()); + assert_eq!(s.doc().unwrap().doc.parent_of(id), Some(layer)); + assert!(rect_near(bounds(&s, id), Rect::new(10.0, 10.0, 60.0, 60.0), 1e-6)); +} + +/// A sublayer that clips its contents counts by its clipping path, and the hidden objects of a +/// sublayer are left out; a sublayer inside a selected group (as an opened file can put one there) +/// counts the same way. +#[test] +fn sublayers_count_by_their_clipping_path_and_shown_art() { + let mut s = session(); + let top = s.doc().unwrap().current_layer().unwrap(); + let sub = id_of(&s.execute("layer.newSublayer", &json!({"parent": top.0})).unwrap()); + s.execute("layer.setCurrent", &json!({"id": sub.0})).unwrap(); + let art = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let hidden = rect(&mut s, 300.0, 300.0, 10.0, 10.0); + assert_eq!(s.doc().unwrap().doc.parent_of(art), Some(sub), "the art is in the sublayer"); + s.execute("select.set", &json!({"ids": [hidden.0]})).unwrap(); + s.execute("object.hide", &json!({})).unwrap(); + let d = &s.doc().unwrap().doc; + let (sub_node, symbols) = (d.node(sub).unwrap().clone(), d.symbol_boxes()); + let mut g = Gathered::new(); + super::outline_points(&sub_node, &symbols, &mut g, 0); + let (center, r) = shapes::enclosing_circle(&g.points).unwrap(); + assert!(center.distance(Point::new(50.0, 50.0)) < 1e-9 && (r - 50.0 * 2f64.sqrt()).abs() < 1e-9, "{center:?} {r}"); + + // The top object of the sublayer becomes its clipping path. + s.execute("select.none", &json!({})).unwrap(); + let clip = rect(&mut s, 20.0, 20.0, 10.0, 10.0); + assert_eq!(s.doc().unwrap().doc.parent_of(clip), Some(sub)); + s.execute("select.none", &json!({})).unwrap(); + assert!(s.execute("layer.clippingMask.toggle", &json!({"id": sub.0})).unwrap()["clip"].as_bool().unwrap()); + let d = &s.doc().unwrap().doc; + let sub_node = d.node(sub).unwrap().clone(); + let mut g = Gathered::new(); + super::outline_points(&sub_node, &d.symbol_boxes(), &mut g, 0); + let (center, r) = shapes::enclosing_circle(&g.points).unwrap(); + assert!(center.distance(Point::new(25.0, 25.0)) < 1e-9 && (r - 5.0 * 2f64.sqrt()).abs() < 1e-9, "{center:?} {r}"); + + let group = s + .edit("Group", |d, _| { + let layer = d.remove(sub)?; + let id = d.alloc_id(); + d.insert(Some(top), usize::MAX, Node::group(id, vec![layer]))?; + Ok(id) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [group.0]})).unwrap(); + let c = id_of(&s.execute(CIRCLE, &json!({})).unwrap()); + let b = bounds(&s, c); + assert!(b.center().distance(Point::new(25.0, 25.0)) < 1e-9 && (b.width() / 2.0 - (5.0 * 2f64.sqrt() + 0.01)).abs() < 1e-9, "{b:?}"); +} + +/// A path of a compound path selected on its own is an object, as `object.transform` moves it: +/// the shape goes around that path only, and with `each` each selected path gets a shape. The +/// compound path selected whole is one object. +#[test] +fn a_path_of_a_compound_path_selected_on_its_own_is_an_object() { + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 10.0, 10.0); + let b = rect(&mut s, 120.0, 100.0, 10.0, 20.0); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let compound = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap()); + let members: Vec = node(&s, compound).children().unwrap().iter().map(|n| n.id).collect(); + assert_eq!(members.len(), 2); + for kind in [RECTANGLE, CIRCLE] { + s.execute("select.set", &json!({"ids": [members[0].0]})).unwrap(); + let id = id_of(&s.execute(kind, &json!({})).unwrap()); + let (got, want) = (bounds(&s, id), bounds(&s, members[0])); + if kind == RECTANGLE { + assert!(rect_near(got, want, 1e-9), "{got:?} on {want:?}"); + } else { + let d = want.width().hypot(want.height()) + 0.02; + assert!(got.center().distance(want.center()) < 1e-9 && (got.width() - d).abs() < 1e-9, "{got:?} around {want:?}"); + } + s.execute("select.set", &json!({"ids": [members[0].0, members[1].0]})).unwrap(); + assert_eq!(ids_of(&s.execute(kind, &json!({"each": true})).unwrap()).len(), 2, "{kind}"); + s.execute("select.set", &json!({"ids": [compound.0]})).unwrap(); + assert_eq!(ids_of(&s.execute(kind, &json!({"each": true})).unwrap()).len(), 1, "{kind}"); + } +} + +/// A small closed curve whose handles lie within the 0.01 pt allowance of its one anchor is not a +/// single point: it gets a circle. +#[test] +fn a_small_loop_gets_a_circle() { + let mut s = session(); + let lp = id_of(&s.execute("path.create", &json!({"d": "M 0 0 C 0.005 0 0 0.005 0 0"})).unwrap()); + s.execute("select.set", &json!({"ids": [lp.0]})).unwrap(); + let c = id_of(&s.execute(CIRCLE, &json!({})).unwrap()); + let LiveShape::Ellipse { w, .. } = live(&s, c) else { panic!("not a circle") }; + assert!(w > 0.02, "{w}"); +} + +/// Once the command has used up both kinds of halvings, a curve counts by its control points' hull +/// cut down to its bounding box: the points stay inside both and reach no farther than the curve +/// along either axis, while its handles may. +#[test] +fn a_curve_past_the_halvings_counts_by_its_hull_inside_its_bounding_box() { + // With nothing left, `curve_points` takes no halving, so `none` stays as it is. + let mut none = Splits { any: 0, early: 0 }; + let c = CubicBez::new((0.0, 0.0), (20.0, 400.0), (380.0, 500.0), (400.0, 0.0)); + let b = vectorcraft_geom::kurbo::ParamCurveExtrema::bounding_box(&c); + let mut out = vec![]; + super::curve_points(c, 0, &mut out, &mut none); + assert!(out.len() >= 4 && out.iter().all(|p| b.inflate(1e-9, 1e-9).contains(*p)), "{out:?} in {b:?}"); + assert!(out.iter().any(|p| (p.y - b.y1).abs() < 1e-9), "the curve's lowest point is reached: {out:?}"); + let (center, r) = shapes::enclosing_circle(&out).unwrap(); + for i in 0..=1000 { + let p = vectorcraft_geom::ParamCurve::eval(&c, f64::from(i) / 1000.0); + assert!(p.distance(center) <= r + 1e-9, "{p:?} outside"); + } + // The handle at x = 4,000,000 stays out: the curve reaches x = 16,000,000 / 9. + let reach = CubicBez::new((0.0, 0.0), (4.0e6, 0.0), (0.0, 0.0), (0.0, 0.0)); + out.clear(); + super::curve_points(reach, 0, &mut out, &mut none); + let far = out.iter().map(|p| p.x).fold(0.0, f64::max); + assert!((far - 16.0e6 / 9.0).abs() < 1e-6, "{far}"); + out.clear(); + let mut splits = Splits { any: 3, early: 0 }; + super::curve_points(c, 0, &mut out, &mut splits); + assert_eq!(splits, Splits { any: 0, early: 0 }); + assert!(out.len() > 4, "{out:?}"); +} + +/// The circle fitted to a circle of four curves: less than 0.3% larger with only the early halvings +/// left, and up to about 14% larger by the curves' hulls once those are used up too. +#[test] +fn a_circle_measured_past_the_halvings_stays_close() { + let fitted = |mut splits: Splits| { + let circle = shapes::ellipse(Rect::new(-100.0, -100.0, 100.0, 100.0)).to_bezpath(); + let mut out = vec![]; + for seg in circle.segments() { + super::curve_points(seg.to_cubic(), 0, &mut out, &mut splits); + } + shapes::enclosing_circle(&out).unwrap() + }; + let (center, r) = fitted(Splits { any: 0, early: 1000 }); + assert!(center.to_vec2().hypot() < 0.1 && (100.0..100.3).contains(&r), "{center:?} {r}"); + let (_, r) = fitted(Splits { any: 0, early: 0 }); + assert!((110.0..115.0).contains(&r), "{r}"); +} + +/// Past the halvings at any depth, only the first [`super::MIN_SPLITS`] halvings of a curve take +/// from the early ones; with `each`, every shape gets an equal share of both. +#[test] +fn early_halvings_are_taken_near_the_start_of_a_curve_and_shared() { + let mut s = Splits { any: 1, early: 1 }; + assert!(s.take(super::MIN_SPLITS + 1)); + assert!(!s.take(super::MIN_SPLITS)); + assert!(s.take(0)); + assert!(!s.take(0)); + let whole = Splits { any: super::TOTAL_SPLITS, early: super::EARLY_SPLITS }; + assert_eq!(super::split_share(0), whole); + assert_eq!(super::split_share(1), whole); + assert_eq!(super::split_share(4), Splits { any: super::TOTAL_SPLITS / 4, early: super::EARLY_SPLITS / 4 }); +} + +/// In an isolated group the shape goes on top of the group's art; in an isolated compound path it +/// goes beside the compound path, never into it. +#[test] +fn shapes_go_into_an_isolated_group_but_not_an_isolated_compound_path() { + let mut s = session(); + 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); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let group = id_of(&s.execute("object.group", &json!({})).unwrap()); + s.execute("object.isolate", &json!({"id": group.0})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let id = id_of(&s.execute(RECTANGLE, &json!({})).unwrap()); + assert_eq!(s.doc().unwrap().doc.parent_of(id), Some(group)); + assert_eq!(top_of(&s, group), id); + s.execute("object.exitIsolation", &json!({})).unwrap(); + + let c = rect(&mut s, 100.0, 100.0, 10.0, 10.0); + let e = rect(&mut s, 120.0, 100.0, 10.0, 10.0); + s.execute("select.set", &json!({"ids": [c.0, e.0]})).unwrap(); + let compound = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap()); + s.execute("object.isolate", &json!({"id": compound.0})).unwrap(); + let members: Vec = node(&s, compound).children().unwrap().iter().map(|n| n.id.0).collect(); + s.execute("select.set", &json!({"ids": members})).unwrap(); + let id = id_of(&s.execute(CIRCLE, &json!({})).unwrap()); + let d = &s.doc().unwrap().doc; + assert_ne!(d.parent_of(id), Some(compound), "the circle does not join the compound path"); + assert_eq!(d.parent_of(id), d.parent_of(compound)); + assert_eq!(node(&s, compound).children().unwrap().len(), 2); +} + +/// An offset or each that is not one the commands take is an error, and nothing is drawn; with +/// nothing selected the commands are not available. +#[test] +fn bad_params_and_an_empty_selection_draw_nothing() { + let mut s = session(); + assert!(s.execute(RECTANGLE, &json!({})).is_err(), "nothing selected"); + assert!(s.execute(CIRCLE, &json!({})).is_err(), "nothing selected"); + let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + for command in [RECTANGLE, CIRCLE] { + for p in [json!({"offset": -1}), json!({"offset": "5"}), json!({"each": "yes"})] { + refused(&mut s, command, p); + } + assert!(refused(&mut s, command, json!({"offset": -1})).contains("`offset` must be 0 or more")); + } +} + +/// An offset that would put an edge of the shape more than 4,000,000 pt from the origin along +/// either axis is an error that names the canvas edge, and nothing is drawn; the largest offsets +/// that stay inside are drawn, for the rectangle and for the circle. +#[test] +fn an_offset_past_the_canvas_edge_draws_nothing() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + for command in [RECTANGLE, CIRCLE] { + for offset in [1e308, 4.0e6] { + let e = refused(&mut s, command, json!({ "offset": offset })); + assert!(e.contains("the shape would reach past the edge of the canvas"), "{command} {offset}: {e}"); + } + } + let r = id_of(&s.execute(RECTANGLE, &json!({"offset": 3.99e6})).unwrap()); + assert!(rect_near(bounds(&s, r), Rect::new(-3.99e6, -3.99e6, 3.99e6 + 10.0, 3.99e6 + 10.0), 1e-3)); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let c = id_of(&s.execute(CIRCLE, &json!({"offset": 3.99e6})).unwrap()); + // The circle around the square from (0, 0) to (10, 10), 0.01 pt larger, then the offset. + let radius = 50.0f64.sqrt() + 0.01 + 3.99e6; + assert!(rect_near(bounds(&s, c), Rect::new(5.0 - radius, 5.0 - radius, 5.0 + radius, 5.0 + radius), 1e-3)); +} + +/// The limit holds along each axis on its own: a shape whose right edge would pass 4,000,000 pt is +/// refused although its other edges, and its distance along the other axis, are small. +#[test] +fn one_edge_past_the_canvas_edge_is_enough_to_refuse() { + let mut s = session(); + let a = rect(&mut s, 3_999_980.0, 0.0, 10.0, 10.0); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + for command in [RECTANGLE, CIRCLE] { + let e = refused(&mut s, command, json!({"offset": 20})); + assert!(e.contains("the shape would reach past the edge of the canvas"), "{command}: {e}"); + } + assert!(s.execute(RECTANGLE, &json!({"offset": 5})).is_ok(), "the right edge at 3,999,995 pt is inside"); +} + +/// A large circle close to the canvas edge, whose arcs stay curved after the most halvings, gets a +/// circle within 0.05 pt of the farthest point of its curves, which stays inside the edge. +#[test] +fn a_large_circle_near_the_canvas_edge_gets_a_close_circle() { + let mut s = session(); + let e = id_of(&s.execute("shape.ellipse", &json!({"x": 3_799_950.0, "y": 0.0, "width": 200_000.0, "height": 200_000.0})).unwrap()); + s.execute("select.set", &json!({"ids": [e.0]})).unwrap(); + let c = id_of(&s.execute(CIRCLE, &json!({})).unwrap()); + let LiveShape::Ellipse { w, xf, .. } = live(&s, c) else { panic!("not a circle") }; + let center = xf * Point::new(w / 2.0, w / 2.0); + let mut farthest: f64 = 0.0; + for seg in node(&s, e).path_data().unwrap().to_bezpath().segments() { + for i in 0..=4000 { + farthest = farthest.max(vectorcraft_geom::ParamCurve::eval(&seg, f64::from(i) / 4000.0).distance(center)); + } + } + assert!(w / 2.0 >= farthest && w / 2.0 < farthest + 0.05, "radius {} for curves reaching {farthest}", w / 2.0); +} + +/// The commands are dimmed while an object of a symbol instance's art is selected, which they +/// refuse, and available again once it is not. +#[test] +fn a_selected_symbol_part_dims_the_commands() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let enabled = |s: &Session, id: &str| (crate::find_command(id).unwrap().enabled)(s); + for command in [RECTANGLE, CIRCLE] { + assert!(enabled(&s, command).is_ok(), "{command}"); + } + s.doc_mut().unwrap().selection.symbol_part = Some(vectorcraft_doc::SymbolPart { instance: a, path: vec![0] }); + for command in [RECTANGLE, CIRCLE] { + assert!(enabled(&s, command).is_err(), "{command} with a symbol part selected"); + } + s.doc_mut().unwrap().selection.symbol_part = None; + assert!(enabled(&s, RECTANGLE).is_ok()); +} + +/// Many points keep only their hull's corners, and the circle around them is the one around all +/// of the points. +#[test] +fn gathered_points_keep_their_hull_and_circle() { + let mut g = Gathered::new(); + let c = Point::new(500.0, 300.0); + for i in 0..200_000 { + let angle = f64::from(i) * 0.618; + let r = if i % 1000 == 0 { 250.0 } else { f64::from(i % 200) }; + g.points.push(c + Vec2::from_angle(angle) * r); + g.compact(); + } + assert!(g.points.len() <= COMPACT_AT + 1, "{} points kept", g.points.len()); + let (center, radius) = shapes::enclosing_circle(&g.points).unwrap(); + assert!(center.distance(c) < 1e-6 && (radius - 250.0).abs() < 1e-6, "{center:?} {radius}"); +} diff --git a/crates/engine/src/cmd/addons/pathtools/tangents.rs b/crates/engine/src/cmd/addons/pathtools/tangents.rs index e45e736109..e47c009062 100644 --- a/crates/engine/src/cmd/addons/pathtools/tangents.rs +++ b/crates/engine/src/cmd/addons/pathtools/tangents.rs @@ -31,7 +31,7 @@ pub(super) fn specs() -> Vec { "Common Tangents", ["Object", "Plug-ins", "Path Precision Tools"], None, - "{tangents?: \"external\" (both paths on the same side of each line) | \"internal\" (the lines that run between them) | \"all\" (\"all\"), centerline?: bool (false: true also adds the line joining the two centers, an ellipse's center or a path's center of area), ids?: [id, id] (default: the selection)} add the common tangent lines of two convex closed paths as separate open paths, each from where it touches the first path to where it touches the second (the whole stretch where a straight side lies along it), stroked with the current stroke color and weight (black when the stroke is None) and unfilled, directly above the upper of the two, as one undo step; the new lines are selected. An ellipse drawn with the Ellipse tool, turned or scaled, is measured as an exact ellipse; any other path must be closed, have one outline, bend the same way all around and have at most 10000 segments. Separate paths have two external and two internal tangents; overlapping paths only external ones; one path inside the other has none. Paths that touch, from outside or from inside, share one tangent there instead: a line centered on the point where they touch and as long as the narrower path is wide along it; paths that meet at a corner or along a shared stretch of outline get one such line, at the middle of the directions that touch both. Paths count as touching when the gap between them is less than a billionth of the larger of their sizes and the distance between their centers. One of the two may be a point (a path of one anchor): the lines then run from the point to where they touch the path, two when the point lies outside it (one that lies along a straight side covers the whole side), one when the point lies on its outline, that is, less than the touching tolerance from it, with the point's distance from the path's center in place of the distance between centers (centered on the point and as long as the path is wide along it, or the whole straight side the point lies on), none when it lies inside; every `tangents` value gives the same lines, counted as internal when `tangents` is \"internal\" and as external otherwise, and the centerline runs from the point to the path's center; two points are refused. When there is no tangent of the kind asked for, nothing changes and the result has a `warning` → {ids, external, internal, centerline (its id or null), warning?}", + "{tangents?: \"external\" (both paths on the same side of each line) | \"internal\" (the lines that run between them) | \"all\" (\"all\"), centerline?: bool (false: true also adds the line joining the two centers, an ellipse's center or a path's center of area), ids?: [id, id] (default: the selection)} add the common tangent lines of two convex closed paths as separate open paths, each from where it touches the first path to where it touches the second (the whole stretch where a straight side lies along it), stroked with the current stroke color and weight (black when the stroke is None) and unfilled, directly above the upper of the two, as one undo step; the new lines are selected. An ellipse drawn with the Ellipse tool, turned or scaled, is measured as an exact ellipse; any other path must be closed, have one outline, bend the same way all around and have at most 10000 segments. Separate paths have two external and two internal tangents; overlapping paths only external ones; one path inside the other has none. Paths that touch, from outside or from inside, share one tangent there instead: a line centered on the point where they touch and as long as the narrower path is wide along it; paths that meet at a corner or along a shared stretch of outline get one such line, at the middle of the directions that touch both. Paths count as touching when the gap between them is at most a billionth of the larger of their sizes and the distance between their centers. One of the two may be a point (a path of one anchor): the lines then run from the point to where they touch the path, two when the point lies outside it (one that lies along a straight side covers the whole side), one when the point lies on its outline, that is, at most the touching tolerance from it, with the point's distance from the path's center in place of the distance between centers (centered on the point and as long as the path is wide along it, or the whole straight side the point lies on), none when it lies inside; every `tangents` value gives the same lines, counted as internal when `tangents` is \"internal\" and as external otherwise, and the centerline runs from the point to the path's center; two points are refused. When there is no tangent of the kind asked for, nothing changes and the result has a `warning` → {ids, external, internal, centerline (its id or null), warning?}", has_selection, common_tangents )] diff --git a/crates/engine/src/cmd/addons/pathtools/tests.rs b/crates/engine/src/cmd/addons/pathtools/tests.rs index 7d11eedd1a..8cd83bacfd 100644 --- a/crates/engine/src/cmd/addons/pathtools/tests.rs +++ b/crates/engine/src/cmd/addons/pathtools/tests.rs @@ -7,7 +7,7 @@ use serde_json::{Value, json}; use vectorcraft_doc::{LiveCorners, LiveShape, NodeId}; use vectorcraft_geom::shapes::CornerKind; use vectorcraft_geom::{AnchorKind, PathData, Point, SubPath}; -use vectorcraft_tools::{PointerEvent, PointerKind}; +use vectorcraft_tools::{Action, Overlay, PointerEvent, PointerKind}; use crate::{Session, ViewInfo}; @@ -1055,6 +1055,37 @@ fn the_slide_tool_previews_and_commits_one_step() { assert_eq!(at(&s), Point::new(200.0, 100.0)); } +/// The Tangent Circle tool's release draws the circle and then tells the tool, which forgets the +/// first segment. When the command fails the session does not tell the tool, so the first segment +/// stays picked: the circle shows again over the second segment. The second click draws it in one +/// undo step. +#[test] +fn the_tangent_circle_tool_keeps_its_first_segment_when_drawing_fails() { + let mut s = session(); + line(&mut s, &[(100.0, 100.0), (300.0, 100.0)], false); + line(&mut s, &[(100.0, 140.0), (300.0, 140.0)], false); + let view = ViewInfo { smart_guides: false, ..ViewInfo::default() }; + s.select_tool("tangentCircle", view).unwrap(); + let at = |s: &mut Session, kind, x, y| s.pointer(&PointerEvent::new(kind, x, y), view); + let shown = |s: &mut Session| { + at(s, PointerKind::Move, 200.0, 139.0).unwrap(); + s.overlays(view).iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text.starts_with("R: 20.00"))) + }; + at(&mut s, PointerKind::Down, 150.0, 101.0).unwrap(); + at(&mut s, PointerKind::Up, 150.0, 101.0).unwrap(); + assert!(shown(&mut s), "the first segment is picked"); + // The tool's release with a command that fails: three points on one line. + let n = steps(&s); + let failing = Action::Exec("shape.circleThroughPoints".into(), json!({"points": [[0, 0], [10, 0], [20, 0]]})); + assert!(s.apply_actions(vec![failing, Action::Notify("tangentCircle.drawn".into())]).is_err()); + assert_eq!(steps(&s), n, "nothing drawn"); + assert!(shown(&mut s), "the first segment is still picked"); + at(&mut s, PointerKind::Down, 200.0, 139.0).unwrap(); + at(&mut s, PointerKind::Up, 200.0, 139.0).unwrap(); + assert_eq!(steps(&s), n + 1, "one undo step"); + assert!(!shown(&mut s), "the first segment is forgotten once the circle is drawn"); +} + fn ids(v: &Value) -> Vec { v["ids"].as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect() } diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index 84596eb53c..1b14e25391 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -772,7 +772,7 @@ fn edit_items_writing_then( // The objects whose rows `f` edited: on type, no row means its characters. let mut rows = Vec::new(); // The objects where `f` wrote the topmost visible row of its kind. - let mut wrote = Vec::new(); + let mut wrote = HashSet::new(); // The row of each object `f` wrote: its index, else the topmost row of the kind. let mut written = Vec::new(); for (id, item) in ids.iter().zip(&per) { @@ -785,7 +785,7 @@ fn edit_items_writing_then( rows.push(*id); } if index.is_none_or(|i| is_top_shown(n, i)) { - wrote.push(*id); + wrote.insert(*id); } written.extend(index.or_else(|| n.appearance.items.iter().rposition(|it| it.is_fill() == fill)).map(|at| (*id, at))); } @@ -1341,7 +1341,8 @@ fn set_item(s: &mut Session, p: &Value) -> Result { let mut rows = top_paint_changed(&before, d, &ids); rows.extend(painted_rows(d, written)); let painted = super::graph::capture_series_top_paints(d, &rows); - let reached = shown_rows_edited(&before, d, reached, |id| edited.iter().any(|(e, _)| *e == id)); + let wrote: HashSet = edited.iter().map(|(id, _)| *id).collect(); + let reached = shown_rows_edited(&before, d, reached, |id| wrote.contains(&id)); let labels = capture_row_edits(&before, d, &reached); // A graph line keeps what was written to its topmost visible row, also when it already showed it. let tops: Vec<(NodeId, usize)> = ids.iter().zip(&per).filter_map(|(id, at)| Some((*id, *at.first()?))).collect(); @@ -1503,7 +1504,7 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result { } super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &ids)); let mut rows = top_paint_changed(&before, d, &ids); - let top_copies: Vec = added.iter().map(|(id, _)| *id).collect(); + let top_copies: HashSet = added.iter().map(|(id, _)| *id).collect(); rows.extend(painted_rows(d, added)); super::graph::capture_series_top_paints(d, &rows); capture_row_edits(&before, d, &shown_rows_edited(&before, d, reached, |id| top_copies.contains(&id))); diff --git a/crates/engine/src/cmd/assets.rs b/crates/engine/src/cmd/assets.rs index 05c2fda1d7..d253c4803f 100644 --- a/crates/engine/src/cmd/assets.rs +++ b/crates/engine/src/cmd/assets.rs @@ -80,7 +80,7 @@ pub fn specs() -> Vec { "Export 3D Assets", [], None, - "{assets?: [asset id…] (default every 3D asset), folder?, zip?, textureSize?: 128…4096 (default 1024: the pixels along the longer side of each face's texture)} each 3D asset's object as a mesh file in its format (assets.set3DFormat), named after the asset: USDA or USDZ, glTF 2.0 (one .gltf, its buffer embedded) or OBJ with its .mtl (whitespace and # in an OBJ's name become _). Every solid of the object (the fill's, each stroke's, a group's members') is a mesh with a material in the color it is painted; faces turned away from the viewer are included, at the object's 3D rotation, y up, about the point it turns about, in points (glTF: meters). The graphics mapped onto a plane or onto Extrude & Bevel's front or back cap (threeD.mapGraphic) are a PNG texture of that face: its color with the graphics drawn over it, flat and unlit, on a mesh of the face's own with texture coordinates; glTF embeds it, USDZ stores it after the layer, and OBJ and USDA write it beside them as -texture-1.png… (whitespace, # and @ become _); a face that is not opaque keeps its opacity in the texture's alpha, and an OBJ also gets -texture-1-opacity.png…, the alpha as gray levels for its map_d. Graphics on Revolve's side are not exported. Files that would share a name get -2, -3…; an object with a hole that crosses its face's outline or another hole, or with more than 2,000,000 triangles, or textures of more than 67,108,864 pixels in one export, is refused → {files: [path…]} (no folder: {files: [{name, dataBase64}]}, or with zip one zip as {name, dataBase64, files})", + "{assets?: [asset id…] (default every 3D asset), folder?, zip?, textureSize?: 128…4096 (default 1024: the pixels along the longer side of each face's texture)} each 3D asset's object as a mesh file in its format (assets.set3DFormat), named after the asset: USDA or USDZ, glTF 2.0 (one .gltf, its buffer embedded) or OBJ with its .mtl (whitespace and # in an OBJ's name become _). Every solid of the object (the fill's, each stroke's, a group's members') is a mesh with a material in the color it is painted; faces turned away from the viewer are included, at the object's 3D rotation, y up, about the point it turns about, in points (glTF: meters). The graphics mapped onto a plane or onto Extrude & Bevel's front or back cap (threeD.mapGraphic) are a PNG texture of that face: its color with the graphics drawn over it, flat and unlit, on a mesh of the face's own with texture coordinates; glTF embeds it, USDZ stores it after the layer, and OBJ and USDA write it beside them as -texture-1.png… (whitespace, # and @ become _); a face that is not opaque keeps its opacity in the texture's alpha, and an OBJ also gets -texture-1-opacity.png…, the alpha as gray levels for its map_d. Graphics on Revolve's side (in a group, the side of the member with the longest profile) are a texture of the side unrolled as the canvas lays it out, on a mesh of the side's triangles; its end caps and cut sides stay plain. Files that would share a name get -2, -3…; an object with a hole that crosses its face's outline or another hole, or with more than 2,000,000 triangles, or textures of more than 67,108,864 pixels in one export, is refused → {files: [path…]} (no folder: {files: [{name, dataBase64}]}, or with zip one zip as {name, dataBase64, files})", has_doc, export_3d ), diff --git a/crates/engine/src/cmd/brushlib.rs b/crates/engine/src/cmd/brushlib.rs index dc5a619adb..944534bb15 100644 --- a/crates/engine/src/cmd/brushlib.rs +++ b/crates/engine/src/cmd/brushlib.rs @@ -177,6 +177,7 @@ pub const BUILTIN: &[BuiltinBrushLibrary] = &[ BuiltinBrushLibrary { id: "bristle-brushes", name: "Bristle Brushes", make: bristle_brushes }, BuiltinBrushLibrary { id: "pattern-borders", name: "Pattern Borders", make: pattern_borders }, BuiltinBrushLibrary { id: "scatter-shapes", name: "Scatter Shapes", make: scatter_shapes }, + BuiltinBrushLibrary { id: "stipple", name: "Stipple", make: stipple }, BuiltinBrushLibrary { id: "game-trails", name: "Game Trails", make: game_trails }, BuiltinBrushLibrary { id: "energy-beams", name: "Energy Beams", make: energy_beams }, BuiltinBrushLibrary { id: "dry-media", name: "Dry Media", make: dry_media }, @@ -627,6 +628,44 @@ fn scatter_shapes() -> BrushLibrary { built("Scatter Shapes", doc, brushes) } +/// Stipple: original dot-based scatter brushes for fine and broad shading along a path. +fn stipple() -> BrushLibrary { + let dot = |x: f64, y: f64, r: f64, opacity: f32| { + Node::path( + NodeId(0), + shapes::ellipse(Rect::new(x - r, y - r, x + r, y + r)), + Appearance { + items: vec![AppearanceItem::Fill(FillLayer { opacity, ..FillLayer::new(Paint::solid(Color::BLACK)) })], + ..Default::default() + }, + ) + }; + let base = Scatter { colorization: Colorization::Tints, ..Default::default() }; + let brushes = vec![ + scatter( + "Fine Stipple", + dot(0.0, 0.0, 0.8, 1.0), + Scatter { size: (70.0, 110.0), spacing: (80.0, 130.0), scatter: (-100.0, 100.0), ..base.clone() }, + ), + scatter( + "Dense Stipple", + group(vec![dot(-1.7, -1.4, 1.0, 1.0), dot(1.5, 0.5, 0.8, 1.0), dot(-0.5, 1.8, 0.65, 1.0)]), + Scatter { size: (80.0, 120.0), spacing: (55.0, 90.0), scatter: (-70.0, 70.0), ..base.clone() }, + ), + scatter( + "Soft Stipple", + group(vec![dot(-1.2, -0.8, 1.0, 0.45), dot(1.2, 1.1, 0.7, 0.35)]), + Scatter { size: (55.0, 135.0), spacing: (80.0, 140.0), scatter: (-140.0, 140.0), ..base.clone() }, + ), + scatter( + "Bold Stipple", + group(vec![dot(-1.5, -1.0, 1.8, 1.0), dot(1.6, 1.3, 1.4, 1.0)]), + Scatter { size: (80.0, 125.0), spacing: (75.0, 115.0), scatter: (-95.0, 95.0), ..base }, + ), + ]; + built("Stipple", Document::new(100.0, 100.0), brushes) +} + /// Game Trails: art brushes for motion lines and impact streaks (original game HUD / VFX art). fn game_trails() -> BrushLibrary { let speed = { diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index c026a1086e..6c0f651c00 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -27,11 +27,15 @@ use crate::EngineError; /// Whether Reset Transformation changes a symbol instance. pub use symbols::reset_transformation_changes; +/// Whether an object is a symbol set. +pub use symbols::is_symbol_set; + /// The Symbols panel's current symbol, as `symbol.list` answers it. pub use symbols::current_symbol; mod brushes; mod dynamic; +mod symbolism; mod symbols; pub(crate) use brushes::{apply_brush, brush_targets, stroke_paint}; @@ -41,6 +45,7 @@ use brushes::{ }; pub(crate) use dynamic::{edit_part, fit_parts, part_only, selected_part}; use dynamic::{symbol_instance_reset, symbol_instance_select_part, symbol_instance_set_appearance}; +use symbolism::symbol_set_density; use symbols::selected_instances; pub(crate) use symbols::{ expand_instances_under, expandable_instances, instance_in_place, natural_size, normalize, place_xf, set_natural_size, store_symbol, @@ -165,7 +170,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, 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}", + "{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|stylusWheel 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°; stylusWheel from value − variation at one end of an airbrush pen's finger wheel to value + variation at the other; 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|stylusWheel 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°; stylusWheel: a at one end of an airbrush pen's finger wheel to b at the other), 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|stylusWheel, 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°; stylusWheel: width at one end of the finger wheel to width_max at the other; 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 ), @@ -220,7 +225,7 @@ pub fn specs() -> Vec { "Symbol Options…", [], None, - "{name?, newName?, registration?: 0..8, exportType?: movieClip|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static|dynamic, alignToPixelGrid?: bool} rename a symbol (its instances and the graphics mapped onto 3D objects follow the new name) and/or set Symbol Options › Registration, Export Type, 9-slice guides (nineSliceGuides [left, top, right, bottom] fractions in from each edge, each -16..16, with left + right < 1 and top + bottom < 1), Symbol Type (a dynamic symbol's instances may change the appearance of objects in its art and stay linked; making it static drops those changes) and Align to Pixel Grid (on: the horizontal and vertical straight segments of the paths in the symbol's art snap to whole points, or half points for an odd centered stroke, at the symbol's natural size, its stroke weights become whole points, and every instance placed at that size, reflected across one axis or not, moves to whole points and goes back to them after each move; a scaled, rotated (a half turn included) or sheared instance, and an instance in another symbol's art, is left where it is; the art snaps again after it is edited); alignToPixelGrid alone with the value the symbol already has changes nothing and adds no undo step; default name: current → {name, registration, exportType, nineSlice, type, alignToPixelGrid}", + "{name?, newName?, registration?: 0..8, exportType?: movieClip|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static|dynamic, alignToPixelGrid?: bool} rename a symbol (its instances and the graphics and Map Art maps on 3D objects follow the new name) and/or set Symbol Options › Registration, Export Type, 9-slice guides (nineSliceGuides [left, top, right, bottom] fractions in from each edge, each -16..16, with left + right < 1 and top + bottom < 1), Symbol Type (a dynamic symbol's instances may change the appearance of objects in its art and stay linked; making it static drops those changes) and Align to Pixel Grid (on: the horizontal and vertical straight segments of the paths in the symbol's art snap to whole points, or half points for an odd centered stroke, at the symbol's natural size, its stroke weights become whole points, and every instance placed at that size, reflected across one axis or not, moves to whole points and goes back to them after each move; a scaled, rotated (a half turn included) or sheared instance, and an instance in another symbol's art, is left where it is; the art snaps again after it is edited); alignToPixelGrid alone with the value the symbol already has changes nothing and adds no undo step; default name: current → {name, registration, exportType, nineSlice, type, alignToPixelGrid}", has_doc, symbol_options ), @@ -338,7 +343,7 @@ pub fn specs() -> Vec { "Select All Unused", [], None, - "{} → {names: [the symbols nothing places, in panel order]} (the Symbols panel selects them): instances in the art (opacity masks included), graphics mapped onto 3D objects (threeD.mapGraphic), graph designs, pattern tiles (with the tiles that pattern editing's Cancel puts back) and brush art count, and so do instances in the art of a symbol that is used", + "{} → {names: [the symbols nothing places, in panel order]} (the Symbols panel selects them): instances in the art (opacity masks included), graphics and Map Art maps on 3D objects (threeD.mapGraphic, threeD.mapArt), graph designs, pattern tiles (with the tiles that pattern editing's Cancel puts back) and brush art count, and so do instances in the art of a symbol that is used", has_doc, symbol_unused ), @@ -357,16 +362,25 @@ pub fn specs() -> Vec { "Symbol Sprayer", [], None, - "{points: [[x,y]…], name?, radius?: 40, density?: 1..10 (5), scale?: 1, alt?: bool (remove instances)} spray instances into a symbol set → {id, count}", + "{points: [[x,y]…] (a third number is not used; one that isn't a number is an error), name?, radius?: 40, density?: 1..10 (5), scale?: 1, alt?: bool (remove instances), attributes?: {scrunch?, size?, spin?, screen?, stain?, style?: average|userDefined (average)}, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), style?: name} spray instances into a symbol set → {id, count}. Each of `attributes` says what a new instance takes: average, the mean of the selected set's instances within `radius` of the stroke point (their spacing along the stroke, size, rotation, opacity, and the stain or style of the nearest one that has one at the mean amount), and with none there the symbol's size, no rotation, full opacity and no stain or style; or userDefined: spacing from the symbol's size and `density`, the symbol's size times `scale`, turned the way the stroke runs there (not turned for one point), full opacity, stained in full with `color` (default: the fill color), and the fill of graphic style `style` (default: the first style after the default one) in full; a `style` the document does not have is then an error. The stain and the style are both the instance's fill, and the style replaces the stain. Another key or value in `attributes` is an error", has_doc, symbol_spray ), + cmd!( + "symbol.setDensity", + "Symbol Set Density", + [], + None, + "{from: 1..10, to: 1..10, ids?|id?} space the instances of the selected symbol sets (or those in `ids`) as Symbol Set Density `to` packs them, from the density each set was created at or last given (`from` for a set without one, such as one grouped by hand): each instance moves along the line from the middle of its set's instances, to (1.15 − 0.1·to) / (1.15 − 0.1·from) of its distance from it (each factor at least 0.1), as one undo step, and every set then has density `to`, also one whose instances do not move (one instance, or each locked); a higher density packs them closer, and a locked or hidden instance stays where it is. No undo step is added when no instance moves and every set already has density `to`. A `from` or `to` left out, not a number or outside 1..10, an id naming no object, or no symbol set among the objects is an error → {ids: the sets changed, count: the instances moved}", + has_doc, + symbol_set_density + ), cmd!( "symbol.adjust", "Symbolism Tool", [], None, - "{tool: shift|scrunch|size|spin|stain|screen|style, points: [[x,y]…], radius?: 40, intensity?: 1..10 (5), alt?: bool, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), style?: name} adjust instances near the points (selection, else all) → {count}", + "{tool: shift|scrunch|size|spin|stain|screen|style, points: [[x,y,pressure?]…] (pen pressure 0..1, default 1), radius?: 40, intensity?: 1..10 (5), usePressure?: bool (each point's pressure is the intensity there, in place of `intensity`), method?: userDefined|average|random (userDefined; not used by shift), proportional?: bool (size; true), affectsDensity?: bool (size; false), alt?: bool, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), style?: name} adjust instances near the points (selection, else all) → {count}. `method` userDefined changes each instance by the tool's amount at its distance from the point; random gives each instance its own share of that amount for the whole stroke, from none to twice it (spin: a turn either way); average moves each instance's value toward the mean of the instances within `radius` of the point (scrunch: its distance from their middle toward their mean distance; size: the geometric mean of their sizes; spin: their mean direction; stain and style: their mean amount; screen: their mean opacity), and `alt` does not reverse it; average leaves an instance without a size (a scale of 0) as it is. With `proportional` false a drag resizes along its own direction (a level drag the width, an upright one the height; the first point takes the direction to the second) and one point resizes both; average resizes both whatever `proportional` is. With `affectsDensity` an instance also moves away from the point as it grows and toward it as it shrinks. An instance counts only when it changes, and no undo step is added when none does (none under the brush, average with each already at the mean, or each already at the tool's limit). A `method` that is none of the three, or a pressure that isn't a number, is an error", has_doc, symbol_adjust ), diff --git a/crates/engine/src/cmd/brushsym/symbolism.rs b/crates/engine/src/cmd/brushsym/symbolism.rs new file mode 100644 index 0000000000..0199b7b13d --- /dev/null +++ b/crates/engine/src/cmd/brushsym/symbolism.rs @@ -0,0 +1,442 @@ +//! What the symbolism commands share: the Method and the Symbol Sprayer options of the Symbolism +//! Tools Options, what an instance shows of the values the tools change ([`Look`]), the mean of +//! those values under the brush ([`mean`]), and `symbol.setDensity`. + +use std::collections::HashMap; + +use super::symbols::{instance_center, is_symbol_set, stored_natural_size}; +use super::{ + Affine, Document, EngineError, HALF, Node, NodeId, NodeKind, Paint, Point, Result, Session, Value, Vec2, bad, ids_json, json, named_ids, +}; + +/// Method: how the Scruncher, Sizer, Spinner, Stainer, Screener and Styler adjust instances. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Method { + /// Gradually, in relation to the position of the pointer. + UserDefined, + /// Toward the mean of the instances under the brush. + Average, + /// By an amount that differs from instance to instance. + Random, +} + +/// The `method` of `symbol.adjust` (User Defined when left out or null). +pub(super) fn method_param(p: &Value, cmd: &str) -> Result { + match p.get("method") { + None | Some(Value::Null) => Ok(Method::UserDefined), + Some(Value::String(s)) if s == "userDefined" => Ok(Method::UserDefined), + Some(Value::String(s)) if s == "average" => Ok(Method::Average), + Some(Value::String(s)) if s == "random" => Ok(Method::Random), + Some(v) => Err(bad(cmd, format!("`method` must be userDefined, average or random, not {v}"))), + } +} + +/// The Symbol Sprayer options: whether each value of a new instance is the average of the +/// instances under the brush (true) or the User Defined value (false). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct SprayModes { + pub scrunch: bool, + pub size: bool, + pub spin: bool, + pub screen: bool, + pub stain: bool, + pub style: bool, +} + +impl SprayModes { + /// Whether any value is an average. + pub fn any_average(self) -> bool { + self.scrunch || self.size || self.spin || self.screen || self.stain || self.style + } +} + +/// The `attributes` of `symbol.spray`: `{scrunch?, size?, spin?, screen?, stain?, style?}`, each +/// `average` (also when left out or null) or `userDefined`. Another key or value is an error. +pub(super) fn spray_modes(p: &Value, cmd: &str) -> Result { + let mut m = SprayModes { scrunch: true, size: true, spin: true, screen: true, stain: true, style: true }; + let map = match p.get("attributes") { + None | Some(Value::Null) => return Ok(m), + Some(Value::Object(map)) => map, + Some(v) => return Err(bad(cmd, format!("`attributes` must be an object, not {v}"))), + }; + for (key, v) in map { + let slot = match key.as_str() { + "scrunch" => &mut m.scrunch, + "size" => &mut m.size, + "spin" => &mut m.spin, + "screen" => &mut m.screen, + "stain" => &mut m.stain, + "style" => &mut m.style, + _ => return Err(bad(cmd, format!("unknown attribute `{key}`"))), + }; + *slot = match v { + Value::Null => true, + Value::String(s) if s == "average" => true, + Value::String(s) if s == "userDefined" => false, + v => return Err(bad(cmd, format!("attribute `{key}` must be average or userDefined, not {v}"))), + }; + } + Ok(m) +} + +/// How far apart the Symbol Sprayer keeps instances at Symbol Set Density `density` (1..10), as a +/// share of the symbol's size: a denser set is packed closer. +pub(super) fn spacing(density: f64) -> f64 { + (1.15 - density * 0.1).max(0.1) +} + +/// The document key that holds each symbol set's Symbol Set Density: `{set id: density}`, written +/// when the Symbol Sprayer creates a set and when `symbol.setDensity` spaces it. +const SET_DENSITY_KEY: &str = "symbolSetDensity"; + +/// The Symbol Set Density symbol set `set` was created at or last given (None when not recorded). +fn set_density_of(d: &Document, set: NodeId) -> Option { + d.unknown.get(SET_DENSITY_KEY)?.get(set.0.to_string())?.as_f64().filter(|v| (1.0..=10.0).contains(v)) +} + +/// Record `density` as the Symbol Set Density of `sets`, and drop the records of ids that are no +/// longer symbol sets. +pub(super) fn record_set_density(d: &mut Document, sets: &[NodeId], density: f64) { + let mut map = match d.unknown.get(SET_DENSITY_KEY) { + Some(Value::Object(m)) => m.clone(), + _ => serde_json::Map::new(), + }; + for set in sets { + map.insert(set.0.to_string(), json!(density)); + } + map.retain(|k, _| k.parse::().ok().and_then(|id| d.node(NodeId(id))).is_some_and(is_symbol_set)); + if map.is_empty() { + d.unknown.remove(SET_DENSITY_KEY); + } else { + d.unknown.insert(SET_DENSITY_KEY.into(), Value::Object(map)); + } +} + +/// What a symbol instance shows of the values the symbolism tools change. +#[derive(Clone, Debug)] +pub(super) struct Look { + pub center: Point, + /// Its size on the page: the side of a square with its area, the same measure for every symbol. + pub size: f64, + /// Its rotation in radians. + pub angle: f64, + pub opacity: f64, + /// The fill the Symbol Stainer or the Symbol Styler gave it, with its amount (0..1). + pub fill: Option<(Paint, f64)>, +} + +/// The [`natural_side`] of each symbol measured so far in one command, so that one measure serves +/// every instance of the symbol. +pub(super) type Sides = HashMap; + +/// The [`Look`] of instance `n` (None for another object, or an instance without a size). +pub(super) fn look(d: &Document, n: &Node, sides: &mut Sides) -> Option { + let NodeKind::SymbolInstance { symbol, xf } = &n.kind else { return None }; + let [a, b, c, e, ..] = xf.as_coeffs(); + let natural = d.symbol_natural_xf(symbol).as_coeffs(); + let (sx, sy) = (natural[0].abs().max(1e-9), natural[3].abs().max(1e-9)); + let scale = ((a * e - b * c) / (sx * sy)).abs().sqrt(); + if !(scale.is_finite() && scale > 0.0) { + return None; + } + let side = match sides.get(symbol) { + Some(side) => *side, + None => *sides.entry(symbol.clone()).or_insert_with(|| natural_side(d, symbol)), + }; + let size = scale * side; + if !(size.is_finite() && size > 0.0) { + return None; + } + Some(Look { + center: instance_center(n)?, + size, + angle: b.atan2(a), + opacity: f64::from(n.opacity), + fill: n.appearance.fill().map(|f| (f.paint.clone(), f64::from(f.opacity))), + }) +} + +/// The [`Look::size`] of an instance of symbol `name` at the symbol's own size. A symbol without a +/// recorded size draws its art at the art's own size, so its art is measured. +pub(super) fn natural_side(d: &Document, name: &str) -> f64 { + let recorded = stored_natural_size(d, name).is_some_and(|(w, h)| w.is_finite() && h.is_finite() && w > 0.0 && h > 0.0); + // Each side's root first, so that a huge size does not overflow. + let art = (!recorded).then(|| d.symbol_art_bounds(name)).flatten().map(|r| r.width().sqrt() * r.height().sqrt()); + if let Some(side) = art.filter(|s| s.is_finite() && *s > 0.0) { + return side; + } + let natural = d.symbol_natural_xf(name).as_coeffs(); + 2.0 * HALF * natural[0].abs().max(1e-9).sqrt() * natural[3].abs().max(1e-9).sqrt() +} + +/// The mean of the [`Look`]s of the instances under the brush. +#[derive(Clone, Debug)] +pub(super) struct Mean { + /// The geometric mean of the sizes ([`Look::size`]). + pub size: f64, + /// The mean direction of the rotations. + pub angle: f64, + pub opacity: f64, + /// The mean stain or style amount; an instance without one counts as 0. + pub amount: f64, + /// The stain or style of the instance nearest the brush's center that has one. + pub paint: Option, + /// The middle of the instances. + pub middle: Point, + /// Their mean distance from [`Mean::middle`]. + pub reach: f64, + /// The mean distance from each of them to the nearest of the others (None for one instance, or + /// when not asked for). + pub gap: Option, +} + +/// The x (`axis` 0) or y (`axis` 1) of `p`. +fn coord(p: Point, axis: usize) -> f64 { + if axis == 0 { p.x } else { p.y } +} + +/// Arrange `order` (indices into `pts`) as a k-d tree: the middle entry of each slice splits the +/// rest by x at even depths and by y at odd ones, the smaller values before it. +fn kd_build(order: &mut [usize], pts: &[Point], axis: usize) { + if order.len() <= 1 { + return; + } + let mid = order.len() / 2; + let at = |i: &usize| pts.get(*i).map_or(0.0, |p| coord(*p, axis)); + order.select_nth_unstable_by(mid, |a, b| at(a).total_cmp(&at(b))); + let (left, right) = order.split_at_mut(mid); + kd_build(left, pts, 1 - axis); + kd_build(right.get_mut(1..).unwrap_or_default(), pts, 1 - axis); +} + +/// The distance from `pts[i]` to the nearest of the others in k-d tree `order`, if nearer than +/// `best`. Instances on top of each other end the search: none can be nearer. +fn kd_nearest(order: &[usize], pts: &[Point], axis: usize, i: usize, best: &mut f64) { + let (Some(&j), Some(&p)) = (order.get(order.len() / 2), pts.get(i)) else { return }; + let Some(&q) = pts.get(j) else { return }; + if j != i { + *best = best.min(p.distance(q)); + } + if *best == 0.0 { + return; + } + let (left, right) = order.split_at(order.len() / 2); + let right = right.get(1..).unwrap_or_default(); + let diff = coord(p, axis) - coord(q, axis); + let (near, far) = if diff < 0.0 { (left, right) } else { (right, left) }; + kd_nearest(near, pts, 1 - axis, i, best); + // The other side holds nothing nearer than the split line. + if diff.abs() < *best { + kd_nearest(far, pts, 1 - axis, i, best); + } +} + +/// For each of `looks`, the distance to the nearest of the others (infinite for one alone), found +/// through a k-d tree of their centers. +fn nearest_gaps(looks: &[&Look]) -> Vec { + let pts: Vec = looks.iter().map(|l| l.center).collect(); + let mut order: Vec = (0..pts.len()).collect(); + kd_build(&mut order, &pts, 0); + (0..pts.len()) + .map(|i| { + let mut best = f64::INFINITY; + kd_nearest(&order, &pts, 0, i, &mut best); + best + }) + .collect() +} + +/// The [`Mean`] of `looks`, the instances under a brush centered on `at` (None for none), with +/// [`Mean::gap`] when `with_gap` is set. +pub(super) fn mean(looks: &[&Look], at: Point, with_gap: bool) -> Option { + if looks.is_empty() { + return None; + } + let n = looks.len() as f64; + let (mut log_size, mut sin, mut cos, mut opacity, mut amount, mut middle) = (0.0, 0.0, 0.0, 0.0, 0.0, Vec2::ZERO); + let mut paint: Option<(&Paint, f64)> = None; + for l in looks { + log_size += l.size.ln(); + sin += l.angle.sin(); + cos += l.angle.cos(); + opacity += l.opacity; + middle += l.center.to_vec2(); + if let Some((p, o)) = &l.fill { + amount += o; + let far = l.center.distance(at); + if paint.is_none_or(|(_, nearest)| far < nearest) { + paint = Some((p, far)); + } + } + } + let middle = (middle / n).to_point(); + // Rotations that cancel out have no mean direction: the first instance's stands for it. + let angle = if sin.hypot(cos) > 1e-9 { sin.atan2(cos) } else { looks[0].angle }; + // One instance under the brush has no spacing there. + let gap = (with_gap && looks.len() > 1).then(|| nearest_gaps(looks).iter().sum::() / n); + Some(Mean { + size: (log_size / n).exp(), + angle, + opacity: opacity / n, + amount: amount / n, + paint: paint.map(|(p, _)| p.clone()), + middle, + reach: looks.iter().map(|l| l.center.distance(middle)).sum::() / n, + gap, + }) +} + +/// `angle` (radians) brought into −π..π. +pub(super) fn wrap_angle(angle: f64) -> f64 { + let turn = std::f64::consts::TAU; + let a = angle.rem_euclid(turn); + if a > std::f64::consts::PI { a - turn } else { a } +} + +/// The instances of a symbol set by where they are, to find those under a brush without looking at +/// every one for every point of a stroke. +pub(super) struct Grid { + cell: f64, + looks: Vec, + cells: HashMap<(i64, i64), Vec>, +} + +fn key(p: Point, cell: f64) -> (i64, i64) { + ((p.x / cell).floor() as i64, (p.y / cell).floor() as i64) +} + +/// The indices in the cell of `at`, then in the eight around it. Saturating: a point far out on the +/// canvas has a key at the end of the range. +fn around(cells: &HashMap<(i64, i64), Vec>, at: Point, cell: f64) -> impl Iterator + '_ { + let (cx, cy) = key(at, cell); + let ring = (cx.saturating_sub(1)..=cx.saturating_add(1)) + .flat_map(move |x| (cy.saturating_sub(1)..=cy.saturating_add(1)).map(move |y| (x, y))) + .filter(move |c| *c != (cx, cy)); + std::iter::once((cx, cy)).chain(ring).flat_map(move |c| cells.get(&c).into_iter().flatten().copied()) +} + +impl Grid { + /// `looks` in cells `cell` points wide (the brush's radius). + pub fn new(looks: Vec, cell: f64) -> Self { + let cell = cell.max(1.0); + let mut cells: HashMap<(i64, i64), Vec> = HashMap::new(); + for (i, l) in looks.iter().enumerate() { + cells.entry(key(l.center, cell)).or_default().push(i); + } + Self { cell, looks, cells } + } + + /// The mean of the instances within `radius` (at most the cell width) of `at`, with + /// [`Mean::gap`] when `with_gap` is set. + pub fn mean(&self, at: Point, radius: f64, with_gap: bool) -> Option { + let near: Vec<&Look> = + around(&self.cells, at, self.cell).filter_map(|i| self.looks.get(i)).filter(|l| l.center.distance(at) <= radius).collect(); + mean(&near, at, with_gap) + } +} + +/// `symbol.setDensity {from, to, ids?|id?}`: space the instances of the selected symbol sets as +/// Symbol Set Density `to` packs them, from the density each set was created at or last given +/// (`from` for a set without one): each instance moves along the line from the middle of its set's +/// instances, to [`spacing`]`(to) / `[`spacing`]` of the set's density` of its distance from it. +/// Every selected set then has density `to`, also one whose instances do not move. One undo step, +/// and none when no instance moves and every set already has density `to`. +pub(super) fn symbol_set_density(s: &mut Session, p: &Value) -> Result { + const C: &str = "symbol.setDensity"; + let density = |key: &str| match p.get(key) { + Some(v) => v.as_f64().filter(|d| (1.0..=10.0).contains(d)).ok_or_else(|| bad(C, format!("`{key}` must be a number from 1 to 10, not {v}"))), + None => Err(bad(C, format!("missing `{key}`"))), + }; + let (from, to) = (density("from")?, density("to")?); + crate::cmd::edit::refuse_symbol_part(s)?; + let st = s.doc()?; + let d = &st.doc; + let named = named_ids(p)?; + let ids: Vec = named.clone().unwrap_or_else(|| st.selection.objects.clone()); + if let Some(missing) = named.iter().flatten().find(|id| d.node(**id).is_none()) { + return Err(EngineError::Other(format!("no object {}", missing.0))); + } + let editable = d.editable(); + let mut sets: Vec = vec![]; + for id in ids { + if d.node(id).is_some_and(is_symbol_set) && editable(id) && !sets.contains(&id) { + sets.push(id); + } + } + if sets.is_empty() { + return Err(EngineError::Other("no symbol set selected".into())); + } + let mut moves: Vec<(NodeId, Vec2)> = vec![]; + let mut changed: Vec = vec![]; + for set in &sets { + // A set packs from the density it was created at or last given, else from `from`. + let own = set_density_of(d, *set); + let ratio = spacing(to) / spacing(own.unwrap_or(from)); + // A set takes density `to` even when none of its instances moves (one instance, or each + // locked or on top of the others), so a later change packs it from `to`. + let restamp = own != Some(to); + let centers: Vec<(NodeId, Point)> = + d.node(*set).and_then(|n| n.children()).into_iter().flatten().filter_map(|c| Some((c.id, instance_center(c)?))).collect(); + if centers.len() < 2 { + if restamp { + changed.push(*set); + } + continue; + } + let middle = (centers.iter().fold(Vec2::ZERO, |sum, (_, c)| sum + c.to_vec2()) / centers.len() as f64).to_point(); + let before = moves.len(); + // A locked or hidden instance stays where it is. + moves.extend( + centers.iter().filter(|(id, _)| editable(*id)).map(|(id, c)| (*id, (*c - middle) * (ratio - 1.0))).filter(|(_, v)| v.hypot() > 1e-9), + ); + if moves.len() > before || restamp { + changed.push(*set); + } + } + drop(editable); + if !changed.is_empty() { + s.edit("Symbol Set Density", |d, _| { + for (id, v) in &moves { + if let Some(n) = d.node_mut(*id) { + n.transform(Affine::translate(*v), false); + } + } + record_set_density(d, &changed, to); + Ok(()) + })?; + } + Ok(json!({ "ids": ids_json(&changed), "count": moves.len() })) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn at(x: f64, y: f64) -> Look { + Look { center: Point::new(x, y), size: 20.0, angle: 0.0, opacity: 1.0, fill: None } + } + + /// The distance from each instance in `from` to the nearest other one in `refs`, measured + /// against every other instance. + fn brute(refs: &[&Look], from: impl Iterator) -> Vec { + from.map(|i| (0..refs.len()).filter(|j| *j != i).map(|j| refs[i].center.distance(refs[j].center)).fold(f64::INFINITY, f64::min)).collect() + } + + /// The gaps are each instance's distance to its nearest neighbor, measured against every other + /// instance: close pairs whose members are far apart in the order, instances on top of each + /// other, instances far from all others, many instances close together, and many on one line. + #[test] + fn nearest_gaps_match_measuring_every_pair() { + let mut looks: Vec = (0..300).map(|i| at(f64::from(i % 20) * 9.0, f64::from(i / 20) * 7.0)).collect(); + // The second member of each pair comes 300 places later. + looks.extend((0..300).map(|i| at(f64::from(i % 20) * 9.0 + 0.5, f64::from(i / 20) * 7.0))); + looks.extend([at(500.0, 500.0), at(500.0, 500.0), at(900.0, 40.0)]); + // 400 instances within one point of each other, and 200 on one upright line. + looks.extend((0..400).map(|i| at(700.0 + f64::from(i % 20) * 0.05, 700.0 + f64::from(i / 20) * 0.05))); + looks.extend((0..200).map(|i| at(-50.0, f64::from(i) * 1.5))); + let refs: Vec<&Look> = looks.iter().collect(); + assert_eq!(nearest_gaps(&refs), brute(&refs, 0..refs.len())); + assert_eq!(nearest_gaps(&refs[..1]), [f64::INFINITY]); + assert_eq!(nearest_gaps(&refs[..0]), Vec::::new()); + } +} diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs index f5245bc9af..6f1b96b52f 100644 --- a/crates/engine/src/cmd/brushsym/symbols.rs +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -1,4 +1,5 @@ use super::dynamic::{fit_overrides, type_id, type_param}; +use super::symbolism::{Grid, Mean, Method, Sides, look, mean, method_param, natural_side, record_set_density, spacing, spray_modes, wrap_angle}; use super::{ Affine, AppearanceItem, Arc, CURRENT_SYMBOL, Color, Document, EngineError, FillLayer, HALF, Node, NodeId, NodeKind, Paint, Point, Result, SIZES_KEY, Session, Symbol, SymbolExportType, SymbolNineSlice, SymbolRegistration, Value, Vec2, bad, brush, color_param, ids_json, json, @@ -906,16 +907,40 @@ pub(super) fn symbol_select_instances(s: &mut Session, p: &Value) -> Result Result> { + Ok(samples(p, cmd)?.into_iter().map(|(q, _)| q).collect()) +} + +/// The stroke's points, each with its pen pressure: the third number of `[x, y, pressure]`, kept +/// within 0..1, and 1 for a point that gives none (or null). A pressure that isn't a number is an +/// error. +fn samples(p: &Value, cmd: &str) -> Result> { let a = p.get("points").and_then(Value::as_array).ok_or_else(|| bad(cmd, "missing points [[x,y]…]"))?; - let v: Vec = a.iter().filter_map(|q| Some(Point::new(q.get(0)?.as_f64()?, q.get(1)?.as_f64()?))).collect(); - if v.is_empty() || v.iter().any(|q| !q.x.is_finite() || !q.y.is_finite()) { + let mut v = Vec::with_capacity(a.len()); + for q in a { + let (Some(x), Some(y)) = (q.get(0).and_then(Value::as_f64), q.get(1).and_then(Value::as_f64)) else { continue }; + let pressure = match q.get(2) { + None | Some(Value::Null) => 1.0, + Some(f) => f.as_f64().filter(|f| f.is_finite()).ok_or_else(|| bad(cmd, format!("a point's pressure must be a number, not {f}")))?, + }; + v.push((Point::new(x, y), pressure.clamp(0.0, 1.0))); + } + if v.is_empty() || v.iter().any(|(q, _)| !q.x.is_finite() || !q.y.is_finite()) { return Err(bad(cmd, "points must be finite [x,y] pairs")); } Ok(v) } +/// The fill of the graphic style `p` names with `style`, else of the document's first style after +/// the default one. +fn style_paint(d: &Document, p: &Value) -> Option { + match str_param(p, "style") { + Some(n) => d.graphic_styles.iter().find(|g| g.name == n).map(|g| g.appearance.fill_paint()), + None => d.graphic_styles.get(1).or(d.graphic_styles.first()).map(|g| g.appearance.fill_paint()), + } +} + /// Deterministic per-point jitter in [-1, 1]² (so previews re-applied on the snapshot agree). -fn jitter(i: usize, q: Point) -> (f64, f64, f64) { +pub(super) fn jitter(i: usize, q: Point) -> (f64, f64, f64) { let mut h: u64 = 0xcbf2_9ce4_8422_2325 ^ i as u64; for v in [(q.x * 16.0).round() as i64 as u64, (q.y * 16.0).round() as i64 as u64] { h ^= v; @@ -926,7 +951,8 @@ fn jitter(i: usize, q: Point) -> (f64, f64, f64) { (f(0), f(1), f(2)) } -fn is_symbol_set(n: &Node) -> bool { +/// Whether `n` is a symbol set: the group the Symbol Sprayer sprays instances into. +pub fn is_symbol_set(n: &Node) -> bool { matches!(n.kind, NodeKind::Group { clip: false, .. }) && n.name.as_deref() == Some("Symbol Set") } @@ -939,6 +965,20 @@ pub(super) fn symbol_spray(s: &mut Session, p: &Value) -> Result { let density = number_or(p, "density", 5.0, C)?.clamp(1.0, 10.0); let scale = number_or(p, "scale", 1.0, C)?.clamp(0.01, 100.0); let alt = switch_or(p, "alt", false, C)?; + let modes = spray_modes(p, C)?; + crate::cmd::paint::check_keep_model(p, C)?; + let stain = match color_param(p, "color", C)? { + Some(c) => crate::cmd::paint::new_color(s, p, c), + None => s.paint.fill.color().unwrap_or(Color::BLACK), + }; + if let Some(v) = p.get("style").filter(|v| !v.is_string()) { + return Err(bad(C, format!("`style` must be a graphic style's name, not {v}"))); + } + let style = style_paint(&st.doc, p); + // Style: User Defined uses the style `style` names, so one the document does not have is an error. + if let Some(n) = str_param(p, "style").filter(|_| !modes.style && style.is_none()) { + return Err(bad(C, format!("unknown graphic style `{n}`"))); + } let size = natural_size(&st.doc, &name); let set = st.selection.objects.first().copied().filter(|id| st.selection.len() == 1 && st.doc.node(*id).is_some_and(is_symbol_set)); // Only a new Symbol Set needs a layer that takes new art. @@ -965,26 +1005,82 @@ pub(super) fn symbol_spray(s: &mut Session, p: &Value) -> Result { } return Ok(json!({ "count": n })); } - // Keep instances at least this far apart along the stroke (denser = closer). - let min_gap = size.0.max(size.1) * scale * (1.15 - density * 0.1).max(0.1); - let mut placed: Vec = vec![]; + let side = natural_side(&st.doc, &name); + // The symbol's longest side as drawn at its own size: its art's, when it has no recorded size. + let recorded = stored_natural_size(&st.doc, &name).filter(|(w, h)| w.is_finite() && h.is_finite() && *w > 0.0 && *h > 0.0); + let extent = match recorded { + Some((w, h)) => w.max(h), + None => { + let art = st.doc.symbol_art_bounds(&name).map(|r| r.width().max(r.height())); + art.filter(|e| e.is_finite() && *e > 0.0).unwrap_or(size.0.max(size.1)) + } + }; + // The scale a new instance is placed at, before the User Defined size jitter. Size: Average is + // the mean size on the page under the brush, of any symbol, or the symbol's own size with none + // there (not `scale`). + let placed_scale = |near: Option<&Mean>| { + if modes.size { near.map(|m| m.size / side).filter(|k| k.is_finite() && *k > 0.0).unwrap_or(1.0) } else { scale } + }; + // The instances the selected set has, for the values a new one takes as their average. + let existing = set.filter(|_| modes.any_average()).map(|g| { + let d = &st.doc; + let mut sides = Sides::new(); + let looks = d.node(g).and_then(|n| n.children()).into_iter().flatten().filter_map(|c| look(d, c, &mut sides)).collect(); + Grid::new(looks, radius) + }); + // Each instance to add: where, the mean of the set's instances under the brush there, and the + // direction of the stroke there (None while the pointer has not moved). + let mut placed: Vec<(Point, Option, Option)> = vec![]; for (i, q) in pts.iter().enumerate() { let (jx, jy, _) = jitter(i, *q); let c = Point::new(q.x + jx * radius * 0.5, q.y + jy * radius * 0.5); - if placed.last().is_some_and(|l| l.distance(c) < min_gap) && i > 0 { + let near = existing.as_ref().and_then(|g| g.mean(*q, radius, modes.scrunch)); + // Keep instances at least this far apart along the stroke (denser = closer), by the size + // the instance is placed at. + let min_gap = extent * placed_scale(near.as_ref()) * spacing(density); + // Scrunch: Average spaces new instances as the ones under the brush are spaced. + let gap = near.as_ref().and_then(|m| m.gap).filter(|_| modes.scrunch).unwrap_or(min_gap); + if placed.last().is_some_and(|(l, ..)| l.distance(c) < gap) && i > 0 { continue; } - placed.push(c); + let along = pts.get(i + 1).unwrap_or(q).to_vec2() - pts.get(i.saturating_sub(1)).unwrap_or(q).to_vec2(); + placed.push((c, near, (along.hypot() > 1e-9).then_some(along))); } let count = placed.len(); let reg = s.doc()?.doc.symbol_registration(&name); let id = s.edit("Symbol Sprayer", |d, sel| { let mut nodes = vec![]; - for (i, c) in placed.iter().enumerate() { + for (i, (c, near, along)) in placed.iter().enumerate() { let (_, _, js) = jitter(i + 7, *c); - let k = scale * (1.0 + js * 0.1); + let near = near.as_ref(); + // User Defined: the symbol's own size, turned the way the stroke runs, opaque, stained + // with the fill color and given the style, each in full. Size: Average has no size jitter. + let k = if modes.size { placed_scale(near) } else { scale * (1.0 + js * 0.1) }; + let angle = if modes.spin { near.map_or(0.0, |m| m.angle) } else { along.map_or(0.0, |v| v.atan2()) }; + let turn = Affine::translate(c.to_vec2()) * Affine::rotate(angle) * Affine::translate(-c.to_vec2()); let id = d.alloc_id(); - nodes.push(Node::new(id, NodeKind::SymbolInstance { symbol: name.clone(), xf: place_xf(*c, size, reg) * Affine::scale(k) })); + let mut n = Node::new(id, NodeKind::SymbolInstance { symbol: name.clone(), xf: turn * place_xf(*c, size, reg) * Affine::scale(k) }); + if modes.screen + && let Some(m) = near + { + n.opacity = (m.opacity as f32).clamp(0.0, 1.0); + } + // The stain and the style are both the instance's fill: the style, set last, replaces + // the stain, an averaged one too when the instances under the brush have a fill. + let averaged = near.filter(|m| m.amount > 0.0).and_then(|m| Some((m.paint.clone()?, m.amount as f32))); + let mut fill = if modes.stain { averaged.clone() } else { Some((Paint::solid(stain), 1.0)) }; + if modes.style { + fill = averaged.or(fill); + } else if let Some(paint) = style.as_ref().filter(|p| !matches!(p, Paint::None)) { + // A style without a fill (the default style) gives none. + fill = Some((paint.clone(), 1.0)); + } + if let Some((paint, amount)) = fill { + let mut f = FillLayer::new(paint); + f.opacity = amount.clamp(0.0, 1.0); + n.appearance.items.insert(0, AppearanceItem::Fill(f)); + } + nodes.push(n); } let gid = match set { Some(g) => { @@ -1001,13 +1097,18 @@ pub(super) fn symbol_spray(s: &mut Session, p: &Value) -> Result { gid } }; + // A new set has the density it is sprayed at; more instances sprayed into a set leave the + // density the set has. + if set.is_none() { + record_set_density(d, &[gid], density); + } sel.set([gid]); Ok(gid) })?; Ok(json!({ "id": id.0, "count": count })) } -fn instance_center(n: &Node) -> Option { +pub(super) fn instance_center(n: &Node) -> Option { match &n.kind { NodeKind::SymbolInstance { xf, .. } => Some(*xf * Point::ZERO), _ => None, @@ -1021,10 +1122,15 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { return Err(bad(C, format!("unknown tool `{tool}`"))); } crate::cmd::paint::check_keep_model(p, C)?; - let pts = points(p, C)?; + let pts = samples(p, C)?; let radius = number_or(p, "radius", 40.0, C)?.clamp(1.0, 2000.0); let intensity = number_or(p, "intensity", 5.0, C)?.clamp(1.0, 10.0) / 10.0; let alt = switch_or(p, "alt", false, C)?; + let use_pressure = switch_or(p, "usePressure", false, C)?; + let proportional = switch_or(p, "proportional", true, C)?; + let affects_density = switch_or(p, "affectsDensity", false, C)?; + // The Symbol Shifter has no Method. + let method = if tool == "shift" { method_param(p, C).map(|_| Method::UserDefined)? } else { method_param(p, C)? }; // Refused while an object of a dynamic instance's art is selected: the instance stays as it is. crate::cmd::edit::refuse_symbol_part(s)?; let st = s.doc()?; @@ -1032,10 +1138,7 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { Some(c) => crate::cmd::paint::new_color(s, p, c), None => s.paint.fill.color().unwrap_or(Color::BLACK), }; - let style_paint = match str_param(p, "style") { - Some(n) => st.doc.graphic_styles.iter().find(|g| g.name == n).map(|g| g.appearance.fill_paint()), - None => st.doc.graphic_styles.get(1).or(st.doc.graphic_styles.first()).map(|g| g.appearance.fill_paint()), - }; + let style_paint = style_paint(&st.doc, p); let candidates: Vec = { let d = &st.doc; let mut v = vec![]; @@ -1065,62 +1168,165 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { "screen" => "Symbol Screener", _ => "Symbol Styler", }; - let count = s.edit(label, |d, _| { + // Random: each instance's share of the tool's change, from none of it to twice it, the same + // for the whole stroke (and for every preview of it). + let first = pts.first().map_or(Point::ZERO, |(q, _)| *q); + let share = |id: NodeId| if method == Method::Random { jitter(id.0 as usize, first).0 + 1.0 } else { 1.0 }; + // No undo step when no instance changes (none under the brush, or Average with each at the mean). + let count = crate::cmd::colorcmds::edit_if_changed(s, label, |orig, d| { let mut touched = std::collections::BTreeSet::new(); - for (j, q) in pts.iter().enumerate() { - let delta = if j > 0 { *q - pts[j - 1] } else { Vec2::ZERO }; + let mut sides = Sides::new(); + for (j, (q, pressure)) in pts.iter().enumerate() { + let delta = if j > 0 { *q - pts[j - 1].0 } else { Vec2::ZERO }; + // Use Pressure Pen: the pen's pressure at the point is the intensity there. + let strength = if use_pressure { *pressure } else { intensity }; + // Average: the mean of the instances under the brush, as they are at this point. + let target = (method == Method::Average) + .then(|| { + let under = |n: &&Node| instance_center(n).is_some_and(|c| c.distance(*q) <= radius); + let looks: Vec<_> = candidates.iter().filter_map(|id| d.node(*id).filter(under).and_then(|n| look(d, n, &mut sides))).collect(); + mean(&looks.iter().collect::>(), *q, false) + }) + .flatten(); for id in &candidates { - let Some(n) = d.node_mut(*id) else { continue }; - let Some(c) = instance_center(n) else { continue }; + let Some(c) = d.node(*id).and_then(instance_center) else { continue }; let dist = c.distance(*q); if dist > radius { continue; } - let w = intensity * (1.0 - dist / radius).max(0.0); + let w = strength * (1.0 - dist / radius).max(0.0); if w <= 0.0 { continue; } - touched.insert(*id); + // Average needs the instance's own values, so it leaves an instance without a size + // as it is; the other methods change it as before. + // The instance's own values are read for Average only. + let own = (method == Method::Average).then(|| d.node(*id).and_then(|n| look(d, n, &mut sides))).flatten(); + let avg = match (method, &target, own) { + (Method::Average, Some(t), Some(cur)) => Some((t, cur)), + // No mean under the brush (every instance there without a size), or none of + // its own. + (Method::Average, ..) => continue, + _ => None, + }; + // Average leaves an instance that already has the mean as it is. + let at_mean = avg.as_ref().is_some_and(|(t, cur)| match tool.as_str() { + "scrunch" => { + let out = (c - t.middle).hypot(); + out <= 1e-9 || (t.reach - out).abs() < 1e-9 + } + "size" => (t.size / cur.size - 1.0).abs() < 1e-9, + "spin" => wrap_angle(t.angle - cur.angle).abs() < 1e-9, + "stain" | "style" => { + (t.amount - cur.fill.as_ref().map_or(0.0, |f| f.1)).abs() < 1e-6 && (cur.fill.is_some() || t.paint.is_none()) + } + "screen" => (t.opacity - cur.opacity).abs() < 1e-6, + _ => false, + }); + if at_mean { + continue; + } + let Some(n) = d.node_mut(*id) else { continue }; + // Counted only when it changes: Random can give an instance no share of the change. + let before = n.clone(); let about = |m: Affine| Affine::translate(c.to_vec2()) * m * Affine::translate(-c.to_vec2()); + let share = share(*id); match tool.as_str() { "shift" => n.transform(Affine::translate(delta * w.min(1.0)), false), "scrunch" => { - let v = (*q - c) * (0.15 * w) * if alt { -1.0 } else { 1.0 }; + let v = match &avg { + // Toward the instances' mean distance from their middle. + Some((t, _)) => { + let out = c - t.middle; + if out.hypot() > 1e-9 { out * ((t.reach - out.hypot()) / out.hypot() * w.min(1.0)) } else { Vec2::ZERO } + } + None => (*q - c) * (0.15 * w * share) * if alt { -1.0 } else { 1.0 }, + }; n.transform(Affine::translate(v), false); } "size" => { - let k = 1.0 + 0.08 * w; - n.transform(about(Affine::scale(if alt { 1.0 / k } else { k })), false); + let k = match &avg { + Some((t, cur)) => (t.size / cur.size).powf(w.min(1.0)), + None => (1.0 + 0.08 * w).powf(if alt { -share } else { share }), + }; + // Without Proportional Resizing a drag resizes along its own direction: a + // level drag the width, an upright one the height. A click resizes both. + // The first point of a drag takes the direction to the second. + let along = if j > 0 { delta } else { pts.get(1).map_or(Vec2::ZERO, |(next, _)| *next - *q) }; + let (kx, ky) = if proportional || avg.is_some() || along.hypot() <= 1e-9 { + (k, k) + } else { + let level = along.x.abs() / (along.x.abs() + along.y.abs()); + (k.powf(2.0 * level), k.powf(2.0 * (1.0 - level))) + }; + n.transform(about(Affine::scale_non_uniform(kx, ky)), false); + // Resizing Affects Density: instances move away from the brush's center as + // they grow and toward it as they shrink. + if affects_density { + n.transform(Affine::translate((c - *q) * ((kx * ky).sqrt() - 1.0)), false); + } } "spin" => { - // Turn towards the drag direction; a click spins a little. - let a = if delta.hypot() > 1e-9 { (c - *q).cross(delta).signum() * 0.1 * w } else { 0.05 * w }; - n.transform(about(Affine::rotate(if alt { -a } else { a })), false); + let a = match (&avg, method) { + (Some((t, cur)), _) => wrap_angle(t.angle - cur.angle) * w.min(1.0), + // A turn either way, whichever way the drag runs. + (None, Method::Random) => 0.1 * w * (share - 1.0), + // Turn towards the drag direction; a click spins a little. + (None, _) if delta.hypot() > 1e-9 => (c - *q).cross(delta).signum() * 0.1 * w, + (None, _) => 0.05 * w, + }; + n.transform(about(Affine::rotate(if alt && avg.is_none() { -a } else { a })), false); } "stain" | "style" => { let paint = if tool == "style" { style_paint.clone().unwrap_or(Paint::solid(color)) } else { Paint::solid(color) }; - if tool == "style" && alt { - n.appearance.items.clear(); - continue; - } - let cur = n.appearance.fill().filter(|f| f.paint == paint).map(|f| f.opacity).unwrap_or(0.0); - let step = if tool == "style" { 1.0 } else { 0.15 * w as f32 }; - let o = if alt { (cur - step).max(0.0) } else { (cur + step).min(1.0) }; + let (paint, o) = match &avg { + // Toward the mean amount, keeping the stain or style the instance has. + Some((t, look)) => { + let (own, cur) = look.fill.clone().map_or((None, 0.0), |(p, o)| (Some(p), o)); + (own.or(t.paint.clone()).unwrap_or(paint), (cur + (t.amount - cur) * w.min(1.0)) as f32) + } + // Alt with the Symbol Styler removes the instance's appearance. + None if tool == "style" && alt => { + n.appearance.items.clear(); + (paint, 0.0) + } + None => { + let cur = n.appearance.fill().filter(|f| f.paint == paint).map(|f| f.opacity).unwrap_or(0.0); + let step = match (tool.as_str(), method) { + // Random: the instance's share of the style, scaled by the + // brush strength there. + ("style", Method::Random) => (share / 2.0 * w.min(1.0)) as f32, + ("style", _) => 1.0, + _ => (0.15 * w * share) as f32, + }; + (paint, if alt { cur - step } else { cur + step }) + } + }; n.appearance.items.retain(|i| !matches!(i, AppearanceItem::Fill(_))); if o > 0.0 { let mut f = FillLayer::new(paint); - f.opacity = o; + f.opacity = o.min(1.0); n.appearance.items.insert(0, AppearanceItem::Fill(f)); } } _ => { - let step = (0.1 * w) as f32; - n.opacity = if alt { (n.opacity + step).min(1.0) } else { (n.opacity - step).max(0.05) }; + let step = (0.1 * w * share) as f32; + n.opacity = match &avg { + // The mean may be below the 5% the Screener otherwise stops at. + Some((t, _)) => (n.opacity + ((t.opacity - f64::from(n.opacity)) * w.min(1.0)) as f32).clamp(0.0, 1.0), + None if alt => (n.opacity + step).min(1.0), + None => (n.opacity - step).max(0.05), + }; } } + if *n != before { + touched.insert(*id); + } } } - Ok(touched.len()) + // An instance the stroke moved away and back again is not counted. + touched.retain(|id| d.node(*id) != orig.node(*id)); + Ok((touched.len(), !touched.is_empty())) })?; Ok(json!({ "count": count })) } diff --git a/crates/engine/src/cmd/buildcmds.rs b/crates/engine/src/cmd/buildcmds.rs index b739ca5f7e..904e80df61 100644 --- a/crates/engine/src/cmd/buildcmds.rs +++ b/crates/engine/src/cmd/buildcmds.rs @@ -145,7 +145,7 @@ pub fn specs() -> Vec { "Make", ["Object", "Image Trace"], None, - "{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, split into at least colorDetail colors where the image has that many before colors that look alike merge (less than 5 apart in Oklab × 100 and thoroughly mixed, or less than 1.5 and mixed in patches), automatic: flat art with its own colours, else as many as the tones need without fullTone's least count, merging close RGB colors, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px (an area smaller than this joins the color it shares the longest border with; when that color is far from its own and the area is 2 px or more, or a single pixel whose longest border is not tied between colors, it joins the neighboring color nearest its pixels among those sharing at least a tenth of that border), method: \"abutting\"|\"overlapping\" (abutting with fills, not mode logo: a \"Seam Fills\" clip group under the paths holds strokes along the edges two filled paths share, 1.5 image pixels wide (VectorCraft's own width), in the color of the lower path (on an image stretched more one way than another, each stroke's outline in image pixels as a filled path), clipped to the image's box within the traced paths' box; paths that became live shapes get none; the paths are not changed), ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), ignoreBackground: false (with ignoreWhite: only the areas of the ignored color that reach the image's edge are left out), keepColors?: [\"#rrggbb\"…] (not mode logo: only the palette colors within about 30 levels of a listed color are traced; empty: every color), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused, judged by the image's own colors also when logoColors are named), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at; or a keepColors color matches none the trace found, or nothing was traced)}", + "{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, split into at least colorDetail colors where the image has that many before colors that look alike merge (less than 5 apart in Oklab × 100 and thoroughly mixed, or less than 1.5 and mixed in patches), automatic: flat art with its own colours, else as many as the tones need without fullTone's least count, merging close RGB colors, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px (an area smaller than this joins the color it shares the longest border with; when that color is far from its own and the area is 2 px or more, or a single pixel whose longest border is not tied between colors, it joins the neighboring color nearest its pixels among those sharing at least a tenth of that border), method: \"abutting\"|\"overlapping\" (abutting with fills, not mode logo: a \"Seam Fills\" clip group under the paths holds strokes along the edges two filled paths share, 1.5 image pixels wide (VectorCraft's own width), in the color of the lower path (on an image stretched more one way than another, each stroke's outline in image pixels as a filled path), clipped to the image's box within the traced paths' box; paths that became live shapes get none; the paths are not changed), ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), ignoreBackground: false (with ignoreWhite: only the areas of the ignored color that reach the image's edge are left out), keepColors?: [\"#rrggbb\"…] (not mode logo: only the palette colors within about 30 levels of a listed color are traced; empty: every color), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused, judged by the image's own colors also when logoColors are named), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult; the Split view keeps the traced object's divider, else 0.5, and imageTrace.setView sets it), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at; or a keepColors color matches none the trace found, or nothing was traced)}", has_selection_or_ids, |s, p| trace_make(s, p, false) ), @@ -181,7 +181,7 @@ pub fn specs() -> Vec { "Image Trace View", [], None, - "{id?|ids?: Image Trace objects (default: selection), view: \"tracingResult\"|\"tracingResultWithOutlines\"|\"outlines\"|\"outlinesWithSourceImage\"|\"sourceImage\"} how they draw on screen; exports, printing and Expand keep the tracing result → {ids, view}", + "{id?|ids?: Image Trace objects (default: selection), view: \"tracingResult\"|\"tracingResultWithOutlines\"|\"outlines\"|\"outlinesWithSourceImage\"|\"sourceImage\"|\"split\" (the source image on the part of the image left of a divider across it, and the tracing result everywhere else), split?: 0-1 (the divider: the fraction of the source image's width, from its left edge, that shows the image; kept as it was when omitted, 0.5 for a new one)} how they draw on screen; exports, printing and Expand keep the tracing result, and tracing again keeps the view and the divider → {ids, view, split (view split: the first object's divider)}", has_selection_or_ids, trace_set_view ), diff --git a/crates/engine/src/cmd/buildcmds/live_paint.rs b/crates/engine/src/cmd/buildcmds/live_paint.rs index 02ba081477..f943766452 100644 --- a/crates/engine/src/cmd/buildcmds/live_paint.rs +++ b/crates/engine/src/cmd/buildcmds/live_paint.rs @@ -37,7 +37,7 @@ fn check_live_paint_takes(d: &Document, roots: &[NodeId]) -> Result<()> { fn make_live(d: &mut Document, sel: &mut Selection, roots: &[NodeId]) -> Result<(NodeId, usize, usize)> { check_live_paint_takes(d, roots)?; if roots.iter().any(|r| d.node(*r).is_some_and(is_live_paint)) { - return merge_live(d, sel, roots); + return merge_live(d, sel, roots, false); } let mut sources = vec![]; for r in roots { @@ -178,8 +178,10 @@ impl Carried { /// Add the other `roots` (back → front) to the first Live Paint group among them, which keeps its /// id, the paint of its faces and edges, and its own properties apart from the Gap Options, which -/// are merged; returns (group, faces, edges). -fn merge_live(d: &mut Document, sel: &mut Selection, roots: &[NodeId]) -> Result<(NodeId, usize, usize)> { +/// are merged; returns (group, faces, edges). When the groups and paths hold no path outline +/// between them, `keep_empty` leaves the group with its paths in its sources group and no faces or +/// edges; without it, that is an error. +fn merge_live(d: &mut Document, sel: &mut Selection, roots: &[NodeId], keep_empty: bool) -> Result<(NodeId, usize, usize)> { let target = roots .iter() .copied() @@ -212,7 +214,14 @@ fn merge_live(d: &mut Document, sel: &mut Selection, roots: &[NodeId]) -> Result // Merge applies the Gap Options' merge rules to the groups' options, bottom-most first. let groups: Vec = roots.iter().filter_map(|r| d.node(*r)).filter(|n| is_live_paint(n)).map(Node::gap_options).collect(); let options = merged_gap_options(&groups); - let (children, nf, ne) = build_children(d, sources, options.max_gap())?; + let (children, nf, ne) = if keep_empty && source_shapes(&sources).0.is_empty() { + let mut src = Node::group(d.alloc_id(), sources); + src.name = Some(SOURCES_NAME.into()); + src.visible = false; + (vec![Arc::new(src)], 0, 0) + } else { + build_children(d, sources, options.max_gap())? + }; // The group keeps its name, lock, visibility, transparency, appearance, opacity mask, graphic // style link and the rest; its children are made again and its Gap Options set to the merged ones. let mut g = old; @@ -266,7 +275,7 @@ pub(super) fn lp_merge(s: &mut Session, p: &Value) -> Result { if let Some(reply) = lone_live_group(s, &roots)? { return Ok(reply); } - let (id, faces, edges) = s.edit("Merge Live Paint", |d, sel| merge_live(d, sel, &roots))?; + let (id, faces, edges) = s.edit("Merge Live Paint", |d, sel| merge_live(d, sel, &roots, false))?; Ok(json!({ "id": id.0, "faces": faces, "edges": edges })) } @@ -301,7 +310,7 @@ pub(crate) fn merge_drawn_in_isolation(s: &mut Session, g: NodeId) -> Result = std::iter::once(g).chain(drawn).collect(); - s.edit("Merge Live Paint", |d, sel| merge_live(d, sel, &roots))?; + s.edit("Merge Live Paint", |d, sel| merge_live(d, sel, &roots, false))?; Ok(true) } @@ -346,12 +355,31 @@ fn enclosing_live_paints(d: &Document, g: NodeId) -> Vec { out } +/// Whether a shown row whose parent is `parent`, among Live Paint group `g`'s paths, gives `g` faces +/// and edges: every group between it and `g`'s sources group is shown. +fn shown_in_sources(d: &Document, parent: Option, g: NodeId) -> bool { + let src = d.node(g).and_then(b::sources).map(|s| s.id); + let mut at = parent; + while let Some(x) = at { + if Some(x) == src { + return true; + } + if !d.node(x).is_some_and(|n| n.visible) { + return false; + } + at = d.parent_of(x); + } + true +} + /// What moving rows in the Layers panel (`layer.move`, `node.move`) does to Live Paint groups. /// Rows that go into a Live Paint group from elsewhere are added to it as `livePaint.merge` adds /// paths. Rows that go into or leave a group's paths (its sources group) change those paths, and /// the group's faces and edges are made again from them, keeping the paint of the faces and edges /// that stay, and so are those of every Live Paint group that holds a changed group among its -/// paths. Rows moved within one group's paths, or among a group's own children, change no faces. +/// paths. Rows moved within one group's paths change no faces unless a shown row goes into or out +/// of a hidden group there; rows moved among a group's own children change no faces. A group's +/// sources group itself stays in the group. pub(crate) struct LivePaintMove { /// The Live Paint group the rows go into, and for each row whether it joins the group's paths. join: Option<(NodeId, Vec)>, @@ -365,16 +393,29 @@ pub(crate) struct LivePaintMove { impl LivePaintMove { /// Plan moving `rows` (with `copy`, copies of them) into `parent`, before anything changes. /// Refuses rows Live Paint can't take ([`b::live_paint_takes`]) that would go among a group's - /// paths, with the message Make and Merge give. + /// paths, with the message Make and Merge give, and a group's sources group moved out of the + /// group. pub(crate) fn plan(d: &Document, rows: &[NodeId], parent: Option, copy: bool) -> Result { + if !copy { + for r in rows { + if let Some(g) = d.parent_of(*r) + && parent != Some(g) + && d.node(g).filter(|n| is_live_paint(n)).and_then(b::sources).is_some_and(|s| s.id == *r) + { + return Err(EngineError::Other("a Live Paint group's sources group stays in the group: move the paths in it instead".into())); + } + } + } let to = spot_in(d, parent); let from: Vec = rows.iter().map(|r| if copy { Spot::Outside } else { spot_in(d, d.parent_of(*r)) }).collect(); let mut rebuild = vec![]; - for f in &from { - if let Spot::Source(g) = *f - && *f != to - && !rebuild.contains(&g) - { + for (r, f) in rows.iter().zip(&from) { + let Spot::Source(g) = *f else { continue }; + // A shown row that goes into or out of a hidden group among the same paths starts or + // stops giving the group faces and edges. + let shown_changes = + *f == to && d.node(*r).is_some_and(|n| n.visible) && shown_in_sources(d, d.parent_of(*r), g) != shown_in_sources(d, parent, g); + if (*f != to || shown_changes) && !rebuild.contains(&g) { rebuild.push(g); } } @@ -444,7 +485,9 @@ impl LivePaintMove { for g in groups { if Some(g) == join_group { let roots: Vec = std::iter::once(g).chain(joined.iter().copied()).collect(); - merge_live(d, sel, &roots)?; + // Rows that join a group with no path outline among them keep the move: the group + // is left with no faces or edges, as when its last path leaves it. + merge_live(d, sel, &roots, true)?; } else if d.node(g).is_some() { rebuild_paths(d, g)?; } diff --git a/crates/engine/src/cmd/buildcmds/trace.rs b/crates/engine/src/cmd/buildcmds/trace.rs index 203fd62338..90c505cfb6 100644 --- a/crates/engine/src/cmd/buildcmds/trace.rs +++ b/crates/engine/src/cmd/buildcmds/trace.rs @@ -58,6 +58,12 @@ fn view_param(cmd: &str, p: &Value) -> Result> { v.as_str().and_then(TraceView::from_id).map(Some).ok_or_else(|| bad(cmd, format!("view must be one of {}", ids()))) } +/// The `split` param (the Split view's divider, 0 to 1), if given. +fn split_param(cmd: &str, p: &Value) -> Result> { + let Some(v) = p.get("split").filter(|v| !v.is_null()) else { return Ok(None) }; + v.as_f64().filter(|f| (0.0..=1.0).contains(f)).map(Some).ok_or_else(|| bad(cmd, "split must be a number from 0 to 1")) +} + /// A saved Image Trace preset ([`crate::Prefs::trace_presets`]): a name and its settings. #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] @@ -1026,9 +1032,14 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result Result> { pub(super) fn trace_set_view(s: &mut Session, p: &Value) -> Result { const C: &str = "imageTrace.setView"; let view = view_param(C, p)?.ok_or_else(|| bad(C, "view is required"))?; + let split = split_param(C, p)?; let targets = trace_targets(s, p)?; let d = &s.doc()?.doc; - if targets.iter().all(|g| d.node(*g).is_some_and(|n| n.trace_view() == view)) { - return Ok(json!({ "ids": ids_json(&targets), "view": view.id() })); + let result = |d: &vectorcraft_doc::Document| { + let mut r = json!({ "ids": ids_json(&targets), "view": view.id() }); + if view == TraceView::Split + && let Some(n) = targets.first().and_then(|g| d.node(*g)) + { + r["split"] = json!(split.unwrap_or_else(|| n.trace_split())); + } + r + }; + if targets.iter().all(|g| d.node(*g).is_some_and(|n| n.trace_view() == view && split.is_none_or(|f| n.trace_split() == f))) { + return Ok(result(d)); } s.edit("Image Trace View", |d, _| { for g in &targets { let n = d.node_mut(*g).ok_or(EngineError::NoNode(*g))?; + if n.extras_if_any().and_then(|e| e.trace.as_deref()).is_none_or(|t| !t.is_object()) { + n.extras_mut().trace = Some(Box::new(json!({ "preset": "Custom" }))); + } if let Some(t) = n.extras_if_any().and_then(|e| e.trace.as_deref_mut()).and_then(Value::as_object_mut) { t.insert("view".into(), json!(view.id())); - } else { - n.extras_mut().trace = Some(Box::new(json!({ "preset": "Custom", "view": view.id() }))); + if let Some(f) = split { + t.insert("split".into(), json!(f)); + } } } Ok(()) })?; - Ok(json!({ "ids": ids_json(&targets), "view": view.id() })) + Ok(result(&s.doc()?.doc)) } pub(super) fn trace_release(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/cmd/clipboard.rs b/crates/engine/src/cmd/clipboard.rs index 4e086569ae..c42289ccc7 100644 --- a/crates/engine/src/cmd/clipboard.rs +++ b/crates/engine/src/cmd/clipboard.rs @@ -47,10 +47,19 @@ pub fn specs() -> Vec { "Swatch Conflicts", [], None, - "{} → {swatches: [{name, document, clipboard, spot}]} the global or spot swatches the copied objects use whose name the active document gives another colour (`document`/`clipboard`: #rrggbb): Paste asks Merge or Add for each (pass the answer as edit.paste* {swatchConflict}). Pasting back into the document the objects came from raises none", + "{profileMismatch?: as edit.paste} → {swatches: [{name, document, clipboard, spot}]} the global or spot swatches the copied objects use whose name the active document gives another colour (`document`/`clipboard`: #rrggbb, the pasted colour as the paste brings it, converted when profileMismatch or the policy converts it): Paste asks Merge or Add for each (pass the answer as edit.paste* {swatchConflict}). Pasting back into the document the objects came from raises none, unless the paste converts its colours", has_doc, conflicts ), + cmd!( + query "clipboard.profileMismatch", + "Paste Profile Mismatch", + [], + None, + "{sourceDocument?, ids?: as edit.dropSelection, allArtboards?: false (true: for edit.pasteOnAllArtboards, which leaves the background colors of copied artboards behind)} → {mismatches: [{model: \"rgb\"|\"cmyk\", clipboard, document, default: \"preserveNumbers\"|\"convert\", convertible}]} the color models whose colors the copied objects (with sourceDocument and ids: the objects edit.dropSelection drops) use and whose profile in the document they were copied from (its assigned profile, else the working space then; an assigned profile removed since: the working space) is not the active document's: Paste keeps their numbers or converts them into the document's profile as edit.paste* and edit.dropSelection {profileMismatch} say, else as the model's policy of edit.colorSettings does (convert: converts; the others: keeps the numbers). convertible: false when either profile is not available (removed with color.removeProfile): the colors then keep their numbers whatever the choice, and default is preserveNumbers. With askMismatchPaste on, the desktop app asks first. Objects from outside an open document have none", + has_doc, + profile_mismatch + ), ]; v.extend(flavours::specs()); v @@ -100,6 +109,15 @@ pub struct Clipboard { /// The selected ruler guides copied with (or without) the objects (#3226), as canvas guides on /// no layer: pasting puts them on the layer new art goes to, moved as the objects are. pub guides: Vec, + /// The RGB and CMYK profiles the objects' colors showed through in the document they were + /// copied from (its assigned profiles, else the working spaces then), by name; none for objects + /// from outside an open document. Paste compares them with the destination's + /// ([`super::colormgmt::paste_mismatches`]). + pub source_profiles: Option<[String; 2]>, + /// The colors were converted for this paste ([`super::colormgmt::paste_profiles`]): back in the + /// source document its resources of the same names are compared with them, as another + /// document's are, while its layers are still found by id. + pub colors_converted: bool, } /// The layer an object was copied from, as Paste Remembers Layers finds it again: the top-level @@ -264,6 +282,7 @@ impl Clipboard { pub fn from_node(st: &DocState, node: Node) -> Self { let mut clip = Self::gather(&st.doc, vec![node]); clip.source_doc = Some(st.uid); + clip.source_profiles = Some(super::colormgmt::effective_profiles(&st.doc)); clip } @@ -335,6 +354,7 @@ impl Clipboard { source_artboard: board.and_then(|i| d.artboards.get(i)).map(|a| a.rect), source_layers, source_doc: Some(st.uid), + source_profiles: Some(super::colormgmt::effective_profiles(d)), ..Self::gather(d, nodes) } } @@ -369,7 +389,7 @@ impl Clipboard { /// The swatch name conflicts pasting into `st` raises, as (pasted, document) swatches: none /// back in the document the objects came from. pub fn swatch_conflicts<'a>(&'a self, st: &'a DocState) -> Vec<(&'a Swatch, &'a Swatch)> { - if self.source_doc == Some(st.uid) { + if self.source_doc == Some(st.uid) && !self.colors_converted { return vec![]; } self.conflicts(&st.doc, &self.used()) @@ -419,6 +439,56 @@ impl Clipboard { d } + /// The clipboard with every color of its objects and of the resources it carries (swatches, + /// symbols, patterns, graphic styles, brushes, character and paragraph styles, the background + /// colors of copied artboards) mapped by `conv`, as Document Color Mode maps a document's + /// ([`super::colormgmt::convert_art_and_style_colors`]). + /// Images keep their pixels. + pub(crate) fn with_colors(&self, conv: &dyn Fn(&vectorcraft_color::Color) -> vectorcraft_color::Color) -> Self { + let mut d = self.to_document(); + // Only what the clipboard carries: not the swatches, graphic styles and brushes every new + // document starts with. + d.swatches = self.swatches.clone().into(); + d.swatch_groups = Default::default(); + d.graphic_styles = self.graphic_styles.clone().into(); + vectorcraft_brush::store(&mut d, &self.brushes); + // Not the stand-in document's own artboard and Document Setup colors: only what the + // clipboard carries is mapped. + super::colormgmt::convert_art_and_style_colors(&mut d, conv); + // `to_document` puts the objects in its one layer. + let nodes = d.layers.first().and_then(|l| l.children()).map(|ch| ch.iter().map(|n| (**n).clone()).collect()).unwrap_or_default(); + Self { + nodes, + symbols: d.symbols.clone(), + patterns: d.patterns.clone(), + swatches: d.swatches.to_vec(), + graphic_styles: d.graphic_styles.to_vec(), + char_styles: d.char_styles.to_vec(), + para_styles: d.para_styles.to_vec(), + brushes: vectorcraft_brush::library(&d), + images: self.images.clone(), + symbol_options: self.symbol_options.clone(), + source_artboard: self.source_artboard, + source_layers: self.source_layers.clone(), + source_doc: self.source_doc, + // The background colors of copied artboards map too. + artboards: self + .artboards + .iter() + .map(|a| { + let mut a = a.clone(); + if let Some(c) = a.color.as_mut() { + *c = conv(c); + } + a + }) + .collect(), + guides: self.guides.clone(), + source_profiles: self.source_profiles.clone(), + colors_converted: self.colors_converted, + } + } + /// The objects as standalone SVG (`None` when there are none). pub fn svg(&self) -> Option { if !self.has_art() { @@ -486,17 +556,33 @@ fn import_svg(s: &mut Session, p: &Value) -> Result { Ok(json!({ "count": s.load_clipboard(clip, p)? })) } -fn conflicts(s: &mut Session, _: &Value) -> Result { +fn conflicts(s: &mut Session, p: &Value) -> Result { let hex = |w: &Swatch| w.paint.color().map(|c| c.to_hex()); - let list: Vec = s - .clipboard - .swatch_conflicts(s.doc()?) + // The swatches as the paste brings them: converted from another profile when it converts. + let profile = super::colormgmt::PasteProfile::param(p, "clipboard.conflicts")?; + let st = s.doc()?; + let (converted, _) = super::colormgmt::paste_profiles(&s.clipboard, &st.doc, profile, true); + let list: Vec = converted + .as_ref() + .unwrap_or(&s.clipboard) + .swatch_conflicts(st) .into_iter() .map(|(c, t)| json!({"name": c.name, "document": hex(t), "clipboard": hex(c), "spot": c.spot})) .collect(); Ok(json!({ "swatches": list })) } +fn profile_mismatch(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "clipboard.profileMismatch"; + // With `sourceDocument` and `ids`, the objects a drop brings, else the clipboard's. + let dropped = if p.get("sourceDocument").is_some() || p.get("ids").is_some() { Some(super::edit::drop_clip(s, p, CMD)?) } else { None }; + let clip = dropped.as_ref().unwrap_or(&s.clipboard); + // Paste on All Artboards leaves the copied artboards, and so their backgrounds, behind. + let all_artboards = super::switch_or(p, "allArtboards", false, CMD)?; + let list: Vec = super::colormgmt::paste_mismatches(clip, &s.doc()?.doc, !all_artboards).iter().map(|m| m.to_json()).collect(); + Ok(json!({ "mismatches": list })) +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/engine/src/cmd/clipboard/resources.rs b/crates/engine/src/cmd/clipboard/resources.rs index 0a98ddd9bc..583341f2a4 100644 --- a/crates/engine/src/cmd/clipboard/resources.rs +++ b/crates/engine/src/cmd/clipboard/resources.rs @@ -20,12 +20,14 @@ use std::sync::Arc; use serde_json::{Map, Value, json}; use vectorcraft_brush::Brush; use vectorcraft_color::{Color, Paint, Swatch}; +use vectorcraft_doc::text::{KINSOKU_NAME_MAX, KINSOKU_SETS_MAX}; use vectorcraft_doc::{ - Appearance, AppearanceItem, Document, Effect, GraphicStyle, Node, NodeKind, PatternDef, Symbol, SymbolExportType, SymbolNineSlice, - SymbolRegistration, TextStyleDef, + Appearance, AppearanceItem, Document, Effect, GraphicStyle, Kinsoku, KinsokuSet, Node, NodeKind, PatternDef, Symbol, SymbolExportType, + SymbolNineSlice, SymbolRegistration, TextStyleDef, }; use super::super::brushsym::{set_natural_size, stored_natural_size}; +use super::super::typecmd::refresh_bounds; use super::super::patterncmds::add_pattern; use super::super::{EngineError, Result, bad, unique_name}; @@ -517,6 +519,36 @@ fn copy_of(base: &str, name: &str) -> bool { name == base || name.strip_prefix(base).and_then(|r| r.strip_prefix(' ')).is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit())) } +/// The `i`th numbered copy of a Kinsoku Shori set's name `base` ("name 2"), within +/// [`KINSOKU_NAME_MAX`]: when it would be too long, the number takes the place of the name's last +/// characters, and spaces left at the end of what remains are dropped. +fn numbered_kinsoku_name(base: &str, i: usize) -> String { + let number = format!(" {i}"); + let head: String = base.chars().take(KINSOKU_NAME_MAX.saturating_sub(number.chars().count())).collect(); + format!("{}{number}", head.trim_end()) +} + +/// [`unique_name`] for a pasted Kinsoku Shori set among `sets` (a document's custom sets, any +/// case), with names that fit [`KINSOKU_NAME_MAX`] ([`numbered_kinsoku_name`]). +fn unique_kinsoku_name(base: &str, sets: &[KinsokuSet]) -> String { + let taken = |n: &str| KinsokuSet::named(sets, n).is_some(); + if !taken(base) { + return base.to_string(); + } + (2..).map(|i| numbered_kinsoku_name(base, i)).find(|n| !taken(n)).unwrap_or_else(|| base.to_string()) +} + +/// Is `name` (any case) the Kinsoku Shori set name `base` or a numbered copy of it, as +/// [`unique_kinsoku_name`] names one? +fn kinsoku_copy_of(base: &str, name: &str) -> bool { + KinsokuSet::same_name(base, name) + || name.rsplit_once(' ').is_some_and(|(_, n)| { + !n.is_empty() + && n.bytes().all(|b| b.is_ascii_digit()) + && n.parse::().is_ok_and(|i| i >= 2 && KinsokuSet::same_name(&numbered_kinsoku_name(base, i), name)) + }) +} + /// The document's own resource for pasted resource `name`, among the document's `names`: the /// one of that name when `same` holds for it (or, pasting back into the source document, at all), /// else a numbered copy of it (added by an earlier paste) that is the same. `None`: add it. @@ -600,6 +632,9 @@ struct Relink { styles: BTreeMap, /// Swatch (its name in the document) → the colour linked colours show at 100 %. colors: BTreeMap, + /// A custom Kinsoku set the pasted paragraphs and paragraph styles hold → the document's set + /// they take, or none (Hard) when the document has no room for it ([`Clipboard::import_kinsoku_sets`]). + kinsoku: HashMap>>, /// Leave graphic style links as they are ([`Clipboard::show_merged_colors`]). keep_styles: bool, } @@ -646,11 +681,19 @@ impl Relink { } } } - // A 3D effect's mapped graphics follow their symbols' names in the document. Each name is - // looked up once, so renames that chain (A to B, B to C) do not apply twice. + // A 3D effect's mapped graphics and Map Art maps follow their symbols' names in the + // document. Each name is looked up once, so renames that chain (A to B, B to C) do not + // apply twice. let items = a.items.iter_mut().flat_map(|i| i.effects_mut().iter_mut()); - for e in a.effects.iter_mut().chain(items).filter(|e| vectorcraft_render::effects::takes_graphics(&e.id)) { - let list = e.params.get_mut(vectorcraft_render::effects::GRAPHICS).and_then(Value::as_array_mut); + for e in a.effects.iter_mut().chain(items) { + let key = if vectorcraft_render::effects::takes_graphics(&e.id) { + vectorcraft_render::effects::GRAPHICS + } else if vectorcraft_render::effects::takes_map_art(&e.id) { + vectorcraft_render::effects::MAP_ART + } else { + continue; + }; + let list = e.params.get_mut(key).and_then(Value::as_array_mut); for g in list.into_iter().flatten() { if let Some(Value::String(s)) = g.get_mut("symbol") { self.name(Res::Symbol, s); @@ -667,6 +710,17 @@ impl Relink { } } fn attrs(&self, a: &mut Map) { + if let Some(to) = + a.get("kinsoku_set").and_then(|v| serde_json::from_value::(v.clone()).ok()).and_then(|set| self.kinsoku.get(&set)) + { + match to { + Some(set) => a.insert("kinsoku_set".into(), json!(set)), + None => { + a.insert("kinsoku".into(), json!(Kinsoku::Hard)); + a.insert("kinsoku_set".into(), Value::Null) + } + }; + } for k in STYLE_PAINTS { let Some(before) = style_paint(a, k) else { continue }; let mut p = before.clone(); @@ -707,6 +761,10 @@ impl Relink { if let Some(s) = &mut pa.style_name { self.name(Res::ParaStyle, s); } + // A graph draws its labels again from the paragraph attributes it keeps for them. + if let Some(to) = pa.kinsoku_set.as_deref().and_then(|set| self.kinsoku.get(set)) { + pa.kinsoku_set = to.clone(); + } } for r in [&mut l.values_rows, &mut l.categories_rows, &mut l.legend_rows, &mut l.axis_rows, &mut l.ring_rows].into_iter().flatten() { r.paint.fill.iter_mut().chain(r.paint.stroke.iter_mut()).for_each(|p| self.paint(p)); @@ -721,10 +779,21 @@ impl Relink { self.name(Res::CharStyle, s); } } + // Lines break anew when a paragraph's set takes other characters or Hard. + let mut relaid = false; for pa in t.para_styles_mut() { if let Some(s) = &mut pa.style_name { self.name(Res::ParaStyle, s); } + if let Some(set) = pa.kinsoku_set.as_deref() + && let Some(to) = self.kinsoku.get(set) + { + relaid |= to.as_deref().is_none_or(|to| kinsoku_chars(to) != kinsoku_chars(set)); + pa.kinsoku_set = to.clone(); + } + } + if relaid { + refresh_bounds(t); } } NodeKind::Image(im) => self.name(Res::Image, &mut im.key), @@ -738,6 +807,11 @@ impl Relink { } } +/// The characters and sequences of Kinsoku set `s`, without its name. +fn kinsoku_chars(s: &KinsokuSet) -> (&[char], &[char], &[char], &[String]) { + (&s.cannot_start, &s.cannot_end, &s.hanging, &s.inseparable) +} + /// Is `ours` (a document definition's art) the art of `theirs` (a pasted one's) once that is /// relinked by `r`? Graphic style links don't count: they are relinked last. fn same_art(r: &Relink, ours: &[Arc], theirs: &[Arc]) -> bool { @@ -1121,8 +1195,11 @@ impl Clipboard { /// uses, as [`import_text_styles`] places them, so that a style that paints with a pattern added /// under a free name ("Dots 2") is compared and added with that name. An error, with `d` /// unchanged, when a pasted SVG filter finds no free name ([`Self::filter_links`]). + /// `same_doc`: `d` is the document the objects were copied from. With colors converted for the + /// paste ([`Self::colors_converted`]), its color-bearing resources are compared as another + /// document's are, while its image blobs are still the document's own under their keys. pub(crate) fn import_into(&self, d: &mut Document, choices: &SwatchChoices, same_doc: bool) -> Result { - self.import_used(d, &self.used(), choices, same_doc) + self.import_used_with_images(d, &self.used(), choices, same_doc && !self.colors_converted, same_doc) } /// Give the objects' colors linked to a global or spot swatch whose conflict with `d` @@ -1155,10 +1232,24 @@ impl Clipboard { /// other is matched on its own ([`loop_groups`]). Pasted back into its own document /// (`same_doc`), each definition of a loop is the document's of its name. fn import_used(&self, d: &mut Document, used: &Used, choices: &SwatchChoices, same_doc: bool) -> Result { + self.import_used_with_images(d, used, choices, same_doc, same_doc) + } + + /// [`Self::import_used`], with the image blobs matched as those of the document they came + /// from when `same_doc_images`. + fn import_used_with_images( + &self, + d: &mut Document, + used: &Used, + choices: &SwatchChoices, + same_doc: bool, + same_doc_images: bool, + ) -> Result { let mut out = Imported::default(); out.relink.filters = self.filter_links(d, same_doc)?; - self.import_images(d, used, same_doc, &mut out); + self.import_images(d, used, same_doc_images, &mut out); self.import_swatches(d, used, choices, same_doc, &mut out); + self.import_kinsoku_sets(d, used, same_doc, &mut out); let mut defs: Vec> = vec![]; for (r, list) in [(Res::CharStyle, &self.char_styles), (Res::ParaStyle, &self.para_styles)] { defs.extend(list.iter().filter(|s| used.has(r, &s.name)).map(|s| Def::Style(r, s))); @@ -1305,10 +1396,86 @@ impl Clipboard { && out.relink.filters.is_empty() && out.relink.styles.is_empty() && out.relink.colors.is_empty() + && out.relink.kinsoku.is_empty() && used.styles.is_empty()); Ok(out) } + /// Add the custom Kinsoku sets that the pasted paragraphs and the used paragraph styles hold + /// to `d`'s sets, and record in [`Relink::kinsoku`] which set of `d` each one takes. A set + /// takes `d`'s set of its name (in any case) when that has the same characters, or, pasted + /// back into its own document, in any case; else a numbered copy of it ("Tight 2") with the + /// same characters. Any other set is added under a free name that fits [`KINSOKU_NAME_MAX`] + /// ([`unique_kinsoku_name`]), so editing `d`'s set of that name leaves the pasted paragraphs + /// alone. When `d` already holds [`KINSOKU_SETS_MAX`] sets, or the pasted set's own name is + /// longer than a name can be, the paragraphs and styles take Hard. + fn import_kinsoku_sets(&self, d: &mut Document, used: &Used, same_doc: bool, out: &mut Imported) { + let mut found: Vec = vec![]; + let mut seen: HashSet = HashSet::new(); + let mut note = |set: &KinsokuSet| { + if !seen.contains(set) { + seen.insert(set.clone()); + found.push(set.clone()); + } + }; + let mut nodes = |n: &Node| { + // Opacity-mask art included. + vectorcraft_doc::swatches::walk_with_masks(n, &mut |m| { + if let NodeKind::Text(t) = &m.kind { + t.para_styles().filter_map(|p| p.kinsoku_set.as_deref()).for_each(&mut note); + } + // The paragraph attributes a graph keeps for its labels. + if let Some(spec) = m.extras().graph.as_deref() { + let l = &spec.label_styles; + [&l.values_para, &l.categories_para, &l.legend_para] + .into_iter() + .flatten() + .filter_map(|p| p.kinsoku_set.as_deref()) + .for_each(&mut note); + } + }); + }; + self.nodes.iter().for_each(&mut nodes); + self.symbols.iter().filter(|s| used.has(Res::Symbol, &s.name)).for_each(|s| nodes(s.art.as_ref())); + self.patterns.iter().filter(|p| used.has(Res::Pattern, &p.name)).flat_map(|p| p.art.iter()).for_each(|a| nodes(a.as_ref())); + self.brushes.iter().filter(|b| used.has(Res::Brush, &b.name)).flat_map(Brush::art).for_each(&mut nodes); + let styles = self.para_styles.iter().filter(|s| used.has(Res::ParaStyle, &s.name)); + for set in styles.filter_map(|s| s.attrs.get("kinsoku_set")).filter_map(|v| serde_json::from_value::(v.clone()).ok()) { + note(&set); + } + for set in found { + let lower = set.name.to_lowercase(); + let mut copies: Vec<&KinsokuSet> = + d.kinsoku_sets.iter().filter(|x| copy_of(&lower, &x.name.to_lowercase()) || kinsoku_copy_of(&set.name, &x.name)).collect(); + // The set of its name first. + copies.sort_by_key(|x| !KinsokuSet::same_name(&x.name, &set.name)); + let own = copies.first().copied().filter(|x| same_doc && KinsokuSet::same_name(&x.name, &set.name)); + let to = match own.or_else(|| copies.iter().copied().find(|x| kinsoku_chars(x) == kinsoku_chars(&set))) { + Some(x) => { + if !KinsokuSet::same_name(&x.name, &set.name) { + out.renamed.push(json!({"kind": "kinsokuSet", "from": set.name, "to": x.name})); + } + Some(Arc::new(x.clone())) + } + None => { + let name = unique_kinsoku_name(&set.name, &d.kinsoku_sets); + (d.kinsoku_sets.len() < KINSOKU_SETS_MAX && name.chars().count() <= KINSOKU_NAME_MAX).then(|| { + let added = KinsokuSet { name: name.clone(), ..set.clone() }; + d.kinsoku_sets.push(added.clone()); + out.added += 1; + if name != set.name { + out.renamed.push(json!({"kind": "kinsokuSet", "from": set.name, "to": name})); + } + Arc::new(added) + }) + } + }; + if to.as_deref() != Some(&set) { + out.relink.kinsoku.insert(set, to); + } + } + } + /// How the pasted SVG filter effects relink ([`Relink::filters`]). Each names the document's /// filter of its name; one that draws another definition than that filter takes the document's /// filter when pasted back into the document it came from, and elsewhere keeps its own under a diff --git a/crates/engine/src/cmd/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs index 18374f8302..0ac4f8c3b0 100644 --- a/crates/engine/src/cmd/colormgmt.rs +++ b/crates/engine/src/cmd/colormgmt.rs @@ -37,7 +37,7 @@ pub fn specs() -> Vec { "Color Settings…", ["Edit"], Some("Cmd+Shift+K"), - "{rgb?: profile, cmyk?: profile, intent?: \"perceptual\"|\"relative\"|\"saturation\"|\"absolute\", bpc?: bool, rgbPolicy?: \"off\"|\"preserveEmbedded\"|\"convert\", cmykPolicy?: \"off\"|\"preserveEmbedded\"|\"convert\"|\"preserveNumbers\"} set the working spaces and the color management policies → {rgb, cmyk, intent, bpc, rgbPolicy, cmykPolicy, profiles: [{name, kind, builtin}]}. A policy decides what opening a document (document.open, file.newFromTemplate, file.revert) does with an RGB or CMYK profile it is tagged with that is not the working space: preserveEmbedded (default) keeps it; off and preserveNumbers take it off and keep the color numbers; convert converts the colors of that model into the working space with the intent and bpc and takes it off. The open reply's warnings name each profile taken off or converted, and a document a policy changed opens with unsaved changes. The desktop app and vectorcraft-cli keep them in `Color Settings.json` next to the preferences and use them again at the next start (not with VECTORCRAFT_NO_PREFS); saved settings naming a profile that is gone leave the defaults", + "{rgb?: profile, cmyk?: profile, intent?: \"perceptual\"|\"relative\"|\"saturation\"|\"absolute\", bpc?: bool, rgbPolicy?: \"off\"|\"preserveEmbedded\"|\"convert\", cmykPolicy?: \"off\"|\"preserveEmbedded\"|\"convert\"|\"preserveNumbers\", askMismatchOpen?: bool, askMismatchPaste?: bool, askMissingOpen?: bool (all false by default)} set the working spaces, the color management policies and the Ask boxes → {rgb, cmyk, intent, bpc, rgbPolicy, cmykPolicy, askMismatchOpen, askMismatchPaste, askMissingOpen, profiles: [{name, kind, builtin}]}. With askMismatchOpen or askMissingOpen on, the desktop app's File › Open asks what to do when the profile of a document's color mode is not the working space, or it has none (document.open takes the answer as profileChoice; it never asks); with askMismatchPaste on, Paste asks whether colors copied from a document with another profile keep their numbers or convert (edit.paste takes it as profileMismatch; see clipboard.profileMismatch). A policy decides what opening a document (document.open, file.newFromTemplate, file.revert) does with an RGB or CMYK profile it is tagged with that is not the working space: preserveEmbedded (default) keeps it; off and preserveNumbers take it off and keep the color numbers; convert converts the colors of that model into the working space with the intent and bpc and takes it off. The open reply's warnings name each profile taken off or converted, and a document a policy changed opens with unsaved changes. The desktop app and vectorcraft-cli keep them in `Color Settings.json` next to the preferences and use them again at the next start (not with VECTORCRAFT_NO_PREFS); saved settings naming a profile that is gone leave the defaults", always, color_settings ), @@ -183,6 +183,9 @@ fn settings_json(st: &ColorSettings) -> Value { "bpc": st.bpc, "rgbPolicy": st.rgb_policy.id(), "cmykPolicy": st.cmyk_policy.id(), + "askMismatchOpen": st.ask_mismatch_open, + "askMismatchPaste": st.ask_mismatch_paste, + "askMissingOpen": st.ask_missing_open, "profiles": cms::profiles().iter().map(|p| json!({"name": p.name, "kind": p.kind, "builtin": p.builtin})).collect::>(), }) } @@ -225,6 +228,9 @@ fn color_settings(s: &mut Session, p: &Value) -> Result { if let Some(v) = policy_param(p, "cmykPolicy", &Policy::CMYK, C)? { st.cmyk_policy = v; } + st.ask_mismatch_open = switch_or(p, "askMismatchOpen", st.ask_mismatch_open, C)?; + st.ask_mismatch_paste = switch_or(p, "askMismatchPaste", st.ask_mismatch_paste, C)?; + st.ask_missing_open = switch_or(p, "askMissingOpen", st.ask_missing_open, C)?; if st != before { cms::set_active(&st).map_err(|e| bad(C, e.to_string()))?; // Saved for the next start when the app attached a settings file (#6335). @@ -659,39 +665,259 @@ fn convert_colors(d: &mut vectorcraft_doc::Document, conv: &dyn Fn(&Color) -> Co /// by Off and Preserve Numbers and kept by Convert to Working Space, which has nothing to convert /// from. → a note for each profile, and whether `d` changed. pub(crate) fn apply_open_policies(d: &mut vectorcraft_doc::Document) -> (Vec, bool) { + // Without a choice nothing can fail. + apply_open_policies_choosing(d, None).unwrap_or_default() +} + +/// What opening a document can ask about its profile (Edit › Color Settings' Ask When Opening +/// boxes): the profile of its color mode differs from the working space, or it has none. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ProfileIssue { + /// Profile Mismatches: tagged with a profile other than the working space. + Mismatch, + /// Missing Profiles: not tagged with a profile. + Missing, +} + +impl ProfileIssue { + pub fn id(self) -> &'static str { + match self { + ProfileIssue::Mismatch => "mismatch", + ProfileIssue::Missing => "missing", + } + } +} + +/// The answer to a [`ProfileQuestion`] (`document.open`'s `profileChoice`). +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum ProfileChoice { + /// Mismatch: keep the profile (as Preserve Embedded Profiles). + UseEmbedded, + /// Mismatch: convert the colors of that model into the working space and take the profile off + /// (as Convert to Working Space). + Convert, + /// Mismatch: take the profile off and keep the color numbers (as Off). + Discard, + /// Missing: leave the document untagged (it follows the working space). + Leave, + /// Missing: tag the document with the working space of its color mode. + AssignWorking, + /// Missing: tag the document with this profile. + Assign(String), +} + +impl ProfileChoice { + /// The ids `profileChoice` takes. + pub const IDS: [&'static str; 6] = ["useEmbedded", "convert", "discard", "leave", "assignWorking", "assign"]; + + pub fn id(&self) -> &'static str { + match self { + ProfileChoice::UseEmbedded => "useEmbedded", + ProfileChoice::Convert => "convert", + ProfileChoice::Discard => "discard", + ProfileChoice::Leave => "leave", + ProfileChoice::AssignWorking => "assignWorking", + ProfileChoice::Assign(_) => "assign", + } + } + + /// The question kind this choice answers. + pub fn issue(&self) -> ProfileIssue { + match self { + ProfileChoice::UseEmbedded | ProfileChoice::Convert | ProfileChoice::Discard => ProfileIssue::Mismatch, + _ => ProfileIssue::Missing, + } + } + + /// The choice `id` (`profile`, which only `assign` takes, for `assign`), or an error naming + /// `cmd`. + pub fn parse(id: &str, profile: Option<&str>, cmd: &str) -> Result { + let key = "profileChoice"; + let choice = match id { + "useEmbedded" => ProfileChoice::UseEmbedded, + "convert" => ProfileChoice::Convert, + "discard" => ProfileChoice::Discard, + "leave" => ProfileChoice::Leave, + "assignWorking" => ProfileChoice::AssignWorking, + "assign" => match profile.filter(|p| !p.is_empty()) { + Some(p) => ProfileChoice::Assign(cms::canonical_name(p).to_string()), + None => { + let path = "assignProfile"; + return Err(bad(cmd, format!("missing `{path}`"))); + } + }, + _ => return Err(bad(cmd, format!("`{key}` must be one of {}", Self::IDS.join(", ")))), + }; + // `assignProfile` goes with `assign` only. + if profile.is_some() && !matches!(choice, ProfileChoice::Assign(_)) { + let path = "assignProfile"; + return Err(bad(cmd, format!("`{path}` goes with `{key}`: \"assign\" only"))); + } + Ok(choice) + } + + /// `document.open`'s `profileChoice` and `assignProfile` in `p` (`None` when left out). + pub(crate) fn param(p: &Value, cmd: &str) -> Result> { + let profile = text_param(p, "assignProfile", cmd)?; + match text_param(p, "profileChoice", cmd)? { + Some(id) => Self::parse(id, profile, cmd).map(Some), + None if profile.is_some() => { + let path = "profileChoice"; + Err(bad(cmd, format!("missing `{path}`"))) + } + None => Ok(None), + } + } +} + +/// What opening document `d` could ask about the profile of its color mode, with the working +/// settings `st`: none when it is tagged with the working space. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ProfileQuestion { + pub issue: ProfileIssue, + /// The model of the document's color mode. + pub model: ColorMode, + /// The profile the document is tagged with (none when it is missing). + pub profile: Option, + /// The working space of that model. + pub working: String, + /// What the policy of that model does, the choice the prompt starts on. + pub default: ProfileChoice, +} + +impl ProfileQuestion { + /// The question for document `d` under the working settings `st` (whether or not they ask it). + pub fn of(d: &vectorcraft_doc::Document, st: &ColorSettings) -> Option { + let (rgb, cmyk) = doc_profiles(d); + let (tag, working, policy) = match d.color_mode { + ColorMode::Rgb => (rgb, cms::canonical_name(&st.rgb).to_string(), st.rgb_policy), + ColorMode::Cmyk => (cmyk, cms::canonical_name(&st.cmyk).to_string(), st.cmyk_policy), + }; + let (issue, default) = match &tag { + Some(t) if *t == working => return None, + Some(_) => ( + ProfileIssue::Mismatch, + match policy { + Policy::PreserveEmbedded => ProfileChoice::UseEmbedded, + Policy::Convert => ProfileChoice::Convert, + Policy::Off | Policy::PreserveNumbers => ProfileChoice::Discard, + }, + ), + // VectorCraft's own rule: Convert to Working Space starts on assigning the working + // space, the other policies on leaving the document as it is. + None => (ProfileIssue::Missing, if policy == Policy::Convert { ProfileChoice::AssignWorking } else { ProfileChoice::Leave }), + }; + Some(Self { issue, model: d.color_mode, profile: tag, working, default }) + } + + /// Do the settings `st` ask it (the Ask When Opening box of its kind is on)? + pub fn asked(&self, st: &ColorSettings) -> bool { + match self.issue { + ProfileIssue::Mismatch => st.ask_mismatch_open, + ProfileIssue::Missing => st.ask_missing_open, + } + } + + /// The model's name as the UI shows it ("RGB", "CMYK"). + pub fn model_label(&self) -> &'static str { + match self.model { + ColorMode::Rgb => "RGB", + ColorMode::Cmyk => "CMYK", + } + } + + pub fn to_json(&self) -> Value { + json!({ + "issue": self.issue.id(), + "model": self.model_label().to_ascii_lowercase(), + "profile": self.profile, + "working": self.working, + "default": self.default.id(), + }) + } +} + +/// [`apply_open_policies`] with the answer `choice` to the document's [`ProfileQuestion`]: a +/// mismatch choice takes the place of the policy of the document's color mode, and a missing +/// choice tags the document after the policies ran. A choice for the other kind of question, or +/// for a document with none, is not used. → as [`apply_open_policies`]; an error when the profile +/// to assign is not a profile of that model. +pub(crate) fn apply_open_policies_choosing(d: &mut vectorcraft_doc::Document, choice: Option<&ProfileChoice>) -> Result<(Vec, bool)> { let working = cms::working_settings(); + let question = ProfileQuestion::of(d, &working); + let choice = choice.filter(|c| question.as_ref().is_some_and(|q| q.issue == c.issue())); + // A mismatch answer stands in for the policy of the document's color mode. + let chosen = |model: ColorMode, policy: Policy| -> (Policy, bool) { + match choice { + Some(c) if d.color_mode == model => match c { + ProfileChoice::UseEmbedded => (Policy::PreserveEmbedded, true), + ProfileChoice::Convert => (Policy::Convert, true), + ProfileChoice::Discard => (Policy::Off, true), + _ => (policy, false), + }, + _ => (policy, false), + } + }; + let (rgb_policy, rgb_chosen) = chosen(ColorMode::Rgb, working.rgb_policy); + let (cmyk_policy, cmyk_chosen) = chosen(ColorMode::Cmyk, working.cmyk_policy); + // The profile a missing answer assigns, checked before anything changes. + let assign = match (choice, &question) { + (Some(ProfileChoice::AssignWorking), Some(q)) => Some(q.working.clone()), + (Some(ProfileChoice::Assign(name)), Some(q)) => { + let kind = if q.model == ColorMode::Rgb { cms::ProfileKind::Rgb } else { cms::ProfileKind::Cmyk }; + let (key, n) = (q.model_label().to_ascii_lowercase(), name); + let info = cms::profile(name).filter(|p| p.kind == kind).ok_or_else(|| bad("document.open", format!("unknown {key} profile `{n}`")))?; + Some(info.name) + } + _ => None, + }; let (rgb, cmyk) = doc_profiles(d); let mut notes = Vec::new(); // What each model's policy does with its profile: `None` keeps it; `Some` takes it off, after - // converting the colors from the profile it holds. - let mut decide = |label: &str, tag: Option, working: &str, policy: Policy, kind: cms::ProfileKind| -> Option> { - let tag = tag.filter(|t| t != working)?; - let available = cms::profile(&tag).is_some_and(|p| p.kind == kind); - match policy { - Policy::PreserveEmbedded => None, - Policy::Off | Policy::PreserveNumbers => { - notes.push(format!( - "the {label} profile “{tag}” the file is tagged with was not used: Color Settings' {label} policy is {}", - policy.label() - )); - Some(None) - } - Policy::Convert if available => { - notes.push(format!( - "the {label} colors were converted from the profile “{tag}” the file is tagged with into the working space “{working}”" - )); - Some(Some(tag)) - } - Policy::Convert => { - notes.push(format!("the {label} profile “{tag}” the file is tagged with is not available, so its colors were not converted")); - None + // converting the colors from the profile it holds. `by_choice`: the prompt's answer decided. + let mut decide = + |label: &str, tag: Option, working: &str, policy: Policy, by_choice: bool, kind: cms::ProfileKind| -> Option> { + let tag = tag.filter(|t| t != working)?; + let available = cms::profile(&tag).is_some_and(|p| p.kind == kind); + match policy { + Policy::PreserveEmbedded => None, + Policy::Off | Policy::PreserveNumbers if by_choice => { + notes.push(format!("the {label} profile “{tag}” the file is tagged with was discarded, as chosen when it was opened")); + Some(None) + } + Policy::Off | Policy::PreserveNumbers => { + notes.push(format!( + "the {label} profile “{tag}” the file is tagged with was not used: Color Settings' {label} policy is {}", + policy.label() + )); + Some(None) + } + Policy::Convert if available => { + notes.push(format!( + "the {label} colors were converted from the profile “{tag}” the file is tagged with into the working space “{working}”" + )); + Some(Some(tag)) + } + Policy::Convert => { + notes.push(format!("the {label} profile “{tag}” the file is tagged with is not available, so its colors were not converted")); + None + } } + }; + let rgb_do = decide("RGB", rgb, &working.rgb, rgb_policy, rgb_chosen, cms::ProfileKind::Rgb); + let cmyk_do = decide("CMYK", cmyk, &working.cmyk, cmyk_policy, cmyk_chosen, cms::ProfileKind::Cmyk); + let mut changed = false; + if let (Some(name), Some(q)) = (assign, &question) { + let label = q.model_label(); + notes.push(format!("the document was assigned the {label} profile “{name}”, as chosen when it was opened")); + match q.model { + ColorMode::Rgb => d.color_profiles.rgb = Some(name), + ColorMode::Cmyk => d.color_profiles.cmyk = Some(name), } - }; - let rgb_do = decide("RGB", rgb, &working.rgb, working.rgb_policy, cms::ProfileKind::Rgb); - let cmyk_do = decide("CMYK", cmyk, &working.cmyk, working.cmyk_policy, cms::ProfileKind::Cmyk); + changed = true; + } if rgb_do.is_none() && cmyk_do.is_none() { - return (notes, false); + return Ok((notes, changed)); } let (from_rgb, from_cmyk) = (rgb_do.clone().flatten(), cmyk_do.clone().flatten()); if from_rgb.is_some() || from_cmyk.is_some() { @@ -713,7 +939,214 @@ pub(crate) fn apply_open_policies(d: &mut vectorcraft_doc::Document) -> (Vec Color) { + convert_colors(d, conv); + convert_style_colors(d, conv); +} + +/// The RGB and CMYK profiles the colors of `d` show through, by name: those it is assigned, else +/// the working spaces. An assigned profile that is not available (removed since) is the working +/// space, as the document draws through it ([`cms::for_document`]). +pub(crate) fn effective_profiles(d: &vectorcraft_doc::Document) -> [String; 2] { + let working = cms::working_settings(); + let (rgb, cmyk) = doc_profiles(d); + let available = |name: Option, kind: cms::ProfileKind| name.filter(|n| cms::profile(n).is_some_and(|p| p.kind == kind)); + [ + available(rgb, cms::ProfileKind::Rgb).unwrap_or_else(|| cms::canonical_name(&working.rgb).to_string()), + available(cmyk, cms::ProfileKind::Cmyk).unwrap_or_else(|| cms::canonical_name(&working.cmyk).to_string()), + ] +} + +/// What Paste does with the colors of a model when the document they were copied from showed them +/// through another profile than the document they go into (`profileMismatch`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PasteProfile { + /// The colors keep their numbers. + PreserveNumbers, + /// The colors convert from the source profile into the destination's, which keeps their + /// appearance. + Convert, +} + +impl PasteProfile { + pub fn id(self) -> &'static str { + match self { + PasteProfile::PreserveNumbers => "preserveNumbers", + PasteProfile::Convert => "convert", + } + } + + /// What a model's policy does to pasted colors (VectorCraft's own mapping): Convert to Working + /// Space converts them, the other policies keep their numbers. + pub fn of(policy: Policy) -> Self { + if policy == Policy::Convert { PasteProfile::Convert } else { PasteProfile::PreserveNumbers } + } + + /// The `profileMismatch` param of paste command `cmd` (`None` when left out): one choice for + /// both models, or `{rgb?, cmyk?}` with a choice for each (a model left out follows its policy). + pub(crate) fn param(p: &Value, cmd: &str) -> Result> { + let key = "profileMismatch"; + let refuse = || bad(cmd, format!("`{key}` must be one of {}", "preserveNumbers, convert, {rgb?, cmyk?} of those")); + let one = |v: &Value| match v.as_str() { + Some("preserveNumbers") => Ok(PasteProfile::PreserveNumbers), + Some("convert") => Ok(PasteProfile::Convert), + _ => Err(refuse()), + }; + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(Value::Object(o)) => { + if o.keys().any(|k| k != "rgb" && k != "cmyk") { + return Err(refuse()); + } + let model = |m: &str| o.get(m).map(&one).transpose(); + Ok(Some(PasteChoice { rgb: model("rgb")?, cmyk: model("cmyk")? })) + } + Some(v) => { + let c = one(v)?; + Ok(Some(PasteChoice { rgb: Some(c), cmyk: Some(c) })) + } + } + } +} + +/// What Paste does with the mismatched colors of each model (`profileMismatch`); a model without a +/// choice follows its policy ([`PasteProfile::of`]). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct PasteChoice { + pub rgb: Option, + pub cmyk: Option, +} + +impl PasteChoice { + /// The choice for the colors of `model`, if any. + pub fn of(&self, model: ColorMode) -> Option { + match model { + ColorMode::Rgb => self.rgb, + ColorMode::Cmyk => self.cmyk, + } + } +} + +/// A model whose colors a paste brings from another profile than the destination's. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct PasteMismatch { + pub model: ColorMode, + /// The profile the colors showed through where they were copied. + pub from: String, + /// The profile they show through in the document they go into. + pub to: String, + /// What the model's policy does with them; Preserve Numbers when they can't convert. + pub default: PasteProfile, + /// Both profiles are available, so the colors can convert; otherwise they keep their numbers + /// whatever the choice. + pub convertible: bool, +} + +impl PasteMismatch { + pub fn to_json(&self) -> Value { + let model = if self.model == ColorMode::Rgb { "rgb" } else { "cmyk" }; + json!({ "model": model, "clipboard": self.from, "document": self.to, "default": self.default.id(), "convertible": self.convertible }) + } +} + +/// The models whose colors pasting `clip` into `d` brings from another profile: RGB, CMYK or both, +/// each only when the copied objects or the resources they carry hold a color of that model. The +/// background colors of copied artboards count only with `boards` (Paste on All Artboards doesn't +/// paste the artboards). +pub(crate) fn paste_mismatches(clip: &super::clipboard::Clipboard, d: &vectorcraft_doc::Document, boards: bool) -> Vec { + let Some([from_rgb, from_cmyk]) = &clip.source_profiles else { return vec![] }; + let [to_rgb, to_cmyk] = effective_profiles(d); + let working = cms::working_settings(); + let mut out: Vec = + [(ColorMode::Rgb, from_rgb, to_rgb, working.rgb_policy), (ColorMode::Cmyk, from_cmyk, to_cmyk, working.cmyk_policy)] + .into_iter() + .filter(|(_, from, to, _)| cms::canonical_name(from) != cms::canonical_name(to)) + .map(|(model, from, to, policy)| { + let kind = if model == ColorMode::Rgb { cms::ProfileKind::Rgb } else { cms::ProfileKind::Cmyk }; + // Both profiles must be here to convert between them. + let here = |name: &str| cms::profile(name).is_some_and(|p| p.kind == kind); + let convertible = here(from) && here(&to); + let default = if convertible { PasteProfile::of(policy) } else { PasteProfile::PreserveNumbers }; + PasteMismatch { model, from: from.clone(), to, default, convertible } + }) + .collect(); + if out.is_empty() { + return out; + } + // Without the artboards when their backgrounds don't paste. + let without_boards; + let clip = if !boards && !clip.artboards.is_empty() { + without_boards = super::clipboard::Clipboard { artboards: vec![], ..clip.clone() }; + &without_boards + } else { + clip + }; + // Which models the pasted colors use. + let seen = std::cell::Cell::new((false, false)); + let _ = clip.with_colors(&|c: &Color| { + let (rgb, cmyk) = seen.get(); + seen.set((rgb || matches!(c, Color::Rgb { .. }), cmyk || matches!(c, Color::Cmyk { .. }))); + *c + }); + let (rgb, cmyk) = seen.get(); + out.retain(|m| if m.model == ColorMode::Rgb { rgb } else { cmyk }); + out +} + +/// The clipboard `clip` as pasting it into `d` brings it: for each mismatched model +/// ([`paste_mismatches`]), its colors keep their numbers or convert from the source profile into +/// the destination's with the working intent, as `choice` says for that model (default: the +/// model's policy, [`PasteProfile::of`]). A source or destination profile that is not available +/// keeps the numbers. `boards`: as [`paste_mismatches`]. +/// → the converted clipboard (`None` when nothing converts; its resources paste as another +/// document's) and a line for each mismatched model (`{model, clipboard, document, choice}`). +pub(crate) fn paste_profiles( + clip: &super::clipboard::Clipboard, + d: &vectorcraft_doc::Document, + choice: Option, + boards: bool, +) -> (Option, Vec) { + let mismatches = paste_mismatches(clip, d, boards); + let mut report = Vec::new(); + let (mut rgb_on, mut cmyk_on) = (false, false); + for m in &mismatches { + let picked = if m.convertible { choice.and_then(|c| c.of(m.model)).unwrap_or(m.default) } else { PasteProfile::PreserveNumbers }; + if picked == PasteProfile::Convert { + match m.model { + ColorMode::Rgb => rgb_on = true, + ColorMode::Cmyk => cmyk_on = true, + } + } + let mut line = m.to_json(); + if let Some(o) = line.as_object_mut() { + o.remove("default"); + o.remove("convertible"); + o.insert("choice".into(), json!(picked.id())); + } + report.push(line); + } + if !rgb_on && !cmyk_on { + return (None, report); + } + let Some([from_rgb, from_cmyk]) = &clip.source_profiles else { return (None, report) }; + let source = cms::for_document(Some(from_rgb), Some(from_cmyk)); + let dest = doc_cms(d); + let intent = cms::working_settings().intent; + let conv = |c: &Color| match c { + Color::Rgb { .. } if rgb_on => source.convert_into(&dest, c, intent), + Color::Cmyk { .. } if cmyk_on => source.convert_into(&dest, c, intent), + _ => *c, + }; + let mut converted = clip.with_colors(&conv); + // Converted colors are not the source document's own: its resources of the same names are + // compared with them, as another document's are. + converted.colors_converted = true; + (Some(converted), report) } /// The colors of `d` outside its art that [`convert_colors`] leaves, converted with `conv`: each @@ -726,6 +1159,11 @@ fn convert_setting_colors(d: &mut vectorcraft_doc::Document, conv: &dyn Fn(&Colo for c in &mut d.setup.grid_colors { *c = conv(c); } + convert_style_colors(d, conv); +} + +/// The fill and stroke colors of `d`'s character and paragraph styles, converted with `conv`. +fn convert_style_colors(d: &mut vectorcraft_doc::Document, conv: &dyn Fn(&Color) -> Color) { // A tint of a global swatch is the converted swatch's color at its tint, which // [`convert_colors`] already gave it. let bases = global_bases(d); diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 4bf123ea17..89752c1b33 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -1,14 +1,16 @@ //! Creating art: shapes, paths, text. use serde_json::{Value, json}; -use vectorcraft_doc::{Appearance, CharStyle, LiveShape, Node, NodeKind, TextObject}; +use vectorcraft_doc::{Appearance, CharStyle, LiveShape, MAX_COORD, Node, NodeKind, TextObject}; +use vectorcraft_geom::curvature::{self, NoCircle}; use vectorcraft_geom::{Affine, Anchor, AnchorKind, FillRule, PathData, Point, Rect, SubPath, shapes}; use super::newart::NewArt; use super::{ CommandSpec, NodeId, Result, Session, bad, bool_or, check_numbers, check_switches, cmd, color_value, f64_or, f64_req, finite_numbers, has_doc, - number_or, str_param, switch_or, + index_opt, number_or, object_param, str_param, switch_or, }; +use crate::EngineError; pub fn specs() -> Vec { vec![ @@ -75,6 +77,15 @@ pub fn specs() -> Vec { has_doc, circle_through_points ), + cmd!( + "shape.curvatureCircle", + "Curvature Circle", + [], + None, + "{id, subpath?=0, segment, t: 0..1, convex?=false} → {id, cx, cy, radius, nominal}: a circle with the current paint that touches path `id` at `t` on the segment and bends as the path bends there (its circle of curvature), on the side the path bends toward, or on the other side with convex; a segment that is the usual cubic of a circular arc of 90° or less gives a circle of that arc's own radius (nominal: true), on the concave side the arc's own circle; not pixel-aligned even while Align New Objects to Pixel Grid is on; a straight stretch, a cusp, a corner anchor (t 0 or 1 where two segments meet at an angle of more than half a degree and the anchor is not marked smooth with both handles pulled out, or where they turn by 90° or more; segments of no length between them are passed over, and an anchor reached past one is treated as not marked smooth), a guide, or a circle reaching past the canvas is an error, and nothing is drawn", + has_doc, + curvature_circle + ), cmd!("shape.line", "Line Segment", [], None, "{x1, y1, x2, y2, fill?: bool (Fill Line: the current fill, else none)} → {id}", has_doc, line), cmd!( "shape.spiral", @@ -485,6 +496,51 @@ fn selected_anchor_points(s: &Session) -> Result>> { Ok(matches!(points.len(), 2 | 3).then_some(points)) } +/// A live ellipse that touches a path at a point with the path's curvature there +/// ([`curvature::curvature_circle_on`]). One undo step, named as an Ellipse tool drag is. +fn curvature_circle(s: &mut Session, p: &Value) -> Result { + const C: &str = "shape.curvatureCircle"; + let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?; + let si = index_opt(p, "subpath", C)?.unwrap_or(0); + let seg = index_opt(p, "segment", C)?.ok_or_else(|| bad(C, "missing segment"))?; + let t = f64_req(p, "t", C)?; + if !(0.0..=1.0).contains(&t) { + return Err(bad(C, "`t` must be from 0 to 1")); + } + let convex = switch_or(p, "convex", false, C)?; + let found = { + let st = s.doc()?; + let node = st.doc.node(id).ok_or(EngineError::NoNode(id))?; + if node.is_guide() { + return Err(bad(C, "a guide has no curvature circle")); + } + let path = node.path_data().ok_or_else(|| bad(C, format!("object {id} is not a path")))?; + let sp = path.subpaths.get(si).ok_or_else(|| bad(C, "no such subpath"))?; + if seg >= sp.segment_count() { + return Err(bad(C, "no such segment")); + } + curvature::curvature_circle_on(sp, seg, t, convex) + }; + let circle = found.map_err(|e| match e { + NoCircle::Straight => bad(C, "the path is straight there, so no circle matches its curvature"), + NoCircle::Cusp => bad(C, "the path has a cusp there, so it has no single curvature"), + NoCircle::Corner => bad(C, "the path has a corner there, so it has no single curvature"), + })?; + let (center, radius) = (circle.center, circle.radius); + let r = Rect::new(center.x - radius, center.y - radius, center.x + radius, center.y + radius); + if ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.abs() <= MAX_COORD) { + return Err(bad(C, "the circle that matches the path there would reach past the canvas")); + } + let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: Affine::translate(r.origin().to_vec2()) }; + // Not pixel-aligned: the circle stays on the path. + let mut out = add_art_unaligned(s, "Ellipse", path_kind(live.to_path(), Some(live)))?; + out["cx"] = json!(center.x); + out["cy"] = json!(center.y); + out["radius"] = json!(radius); + out["nominal"] = json!(circle.nominal); + Ok(out) +} + /// The whole-number count `p` gives for `key` (`5` or `5.0`), or `default` when it is left out or /// null. A fraction, a negative, a non-finite or a non-number is an error rather than the default. fn count_or(p: &Value, key: &str, default: u64, cmd: &str) -> Result { diff --git a/crates/engine/src/cmd/docinfo.rs b/crates/engine/src/cmd/docinfo.rs index 0456a09321..bb22ae5c16 100644 --- a/crates/engine/src/cmd/docinfo.rs +++ b/crates/engine/src/cmd/docinfo.rs @@ -18,7 +18,7 @@ pub fn specs() -> Vec { "Document Info", ["Window", "Document Info"], None, - "{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document: {…, units (English), unitId: the units' Preferences › Units id (points, millimeters, feetInches, …), rasterEffectsPpi, transparency: {gridSize: small|medium|large, gridColors: [#rrggbb, #rrggbb], gridColorsName (a preset's name or Custom), simulatePaper, flattenerPreset} (File › Document Setup's transparency settings, which the document category lists), selectedArtboards: [{index, name, width, height, x, y}] (while the Artboard tool is the current tool, the artboards it has selected, in the document's units, x and y those of the top-left corner from the ruler origin of its active artboard, which the document category lists after the artboards; else empty)}, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts (the type in opacity masks and in the art of symbols and patterns included; with selectionOnly: the selected type's), fontDetails: [{font, match: exact|style|missingWithFallback|missing, family, style, file, embedding: allowed|editing|previewPrint|forbidden|null}] (each font of fonts, in order: how it was found, the face shown (null when none), that face's file name (null for a built-in face) and what its license allows), images, imageObjects: [{name, width, height, linked, file}] (the image objects in the order Linked Images and Embedded Images list them; file: what a linked image's row shows, null for an embedded one), swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the brushes the art's drawn strokes use, each once; with selectionOnly: those the selected objects' strokes use), brushes: [{name, type: calligraphic|scatter|art|pattern|bristle|null}] (those brushes with their types; null: not in the Brushes panel), panelBrushNames (the Brushes panel's brushes), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient that color a part of it above opacity 0 (a stop at opacity 0 counts only where it mixes with a stop above opacity 0 over a stretch of some width), at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, fills and strokes at an opacity of 0, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients, kinds}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else its kind's name, such as Linear gradient; kinds gives each one's kind, linear|radial|conic|diamond|freeform, when it is named by its kind, else null; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}. An image linked to a file outside the automation read roots has link null, and its Linked Images row names the file alone. brushNames, brushes, spotObjects, patternObjects and gradientObjects leave out hidden objects, objects at an opacity of 0 and the objects inside a hidden group or layer or one at an opacity of 0 (with selectionOnly too), their characters' paints and colorized images included; objects still counts them as paths, groups and the other kinds", + "{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document: {…, units (English), unitId: the units' Preferences › Units id (points, millimeters, feetInches, …), rasterEffectsPpi, transparency: {gridSize: small|medium|large, gridColors: [#rrggbb, #rrggbb], gridColorsName (a preset's name or Custom), simulatePaper, flattenerPreset} (File › Document Setup's transparency settings, which the document category lists), selectedArtboards: [{index, name, width, height, x, y}] (while the Artboard tool is the current tool, the artboards it has selected, in the document's units, x and y those of the top-left corner from the ruler origin of its active artboard, which the document category lists after the artboards; else empty)}, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts (the type in opacity masks and in the art of symbols and patterns included; with selectionOnly: the selected type's), fontUses: [{font, type: truetype|opentype|unknown, uses}] (each font of fonts, in order: truetype or opentype by the outlines (glyf, or CFF or CFF2) of the face its type is drawn in, unknown for a font not installed in the family and style it names; uses: the text objects set in it, each once however many of its runs use the font, the type in a mask or in a symbol's or pattern's art once however many objects show it; the fonts category's rows give them as `TrueType; 2 uses`), fontDetails: [{font, match: exact|style|missingWithFallback|missing, family, style, file, embedding: allowed|editing|previewPrint|forbidden|null}] (each font of fonts, in order: how it was found, the face shown (null when none), that face's file name (null for a built-in face) and what its license allows), images, imageObjects: [{name, width, height, linked, file}] (the image objects in the order Linked Images and Embedded Images list them; file: what a linked image's row shows, null for an embedded one), swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the brushes the art's drawn strokes use, each once; with selectionOnly: those the selected objects' strokes use), brushes: [{name, type: calligraphic|scatter|art|pattern|bristle|null}] (those brushes with their types; null: not in the Brushes panel), panelBrushNames (the Brushes panel's brushes), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient that color a part of it above opacity 0 (a stop at opacity 0 counts only where it mixes with a stop above opacity 0 over a stretch of some width), at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, fills and strokes at an opacity of 0, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients, kinds}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else its kind's name, such as Linear gradient; kinds gives each one's kind, linear|radial|conic|diamond|freeform, when it is named by its kind, else null; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}. An image linked to a file outside the automation read roots has link null, and its Linked Images row names the file alone. brushNames, brushes, spotObjects, patternObjects and gradientObjects leave out hidden objects, objects at an opacity of 0 and the objects inside a hidden group or layer or one at an opacity of 0 (with selectionOnly too), their characters' paints and colorized images included; objects still counts them as paths, groups and the other kinds", has_doc, info ), @@ -144,6 +144,45 @@ fn font_detail(used: &super::fonts::UsedFont) -> (Value, (String, String)) { (entry, (label, detail)) } +/// The type of a font as Fonts lists it: `truetype` or `opentype` by the outlines of the face the +/// type is drawn in (in the version the type names), `unknown` for a font that is not installed in +/// the family and style it names, or whose face holds neither kind of outline. +fn font_type(used: &super::fonts::UsedFont) -> &'static str { + let db = vectorcraft_text::FontDb::global(); + let (family, style, version) = used; + match db.resolve(family, style) { + Some((f, vectorcraft_text::FontMatch::Exact)) => match db.face_version(family, style, version.as_deref()).unwrap_or(f).outline_format() { + Some(vectorcraft_text::OutlineFormat::TrueType) => "truetype", + Some(vectorcraft_text::OutlineFormat::Cff) => "opentype", + None => "unknown", + }, + _ => "unknown", + } +} + +/// A font as Fonts lists it: its `fontUses` entry and its row, which gives the font's type and its +/// number of uses (`uses`: the text objects set in it). +fn font_use(used: &super::fonts::UsedFont, uses: usize) -> (Value, (String, String)) { + let label = super::fonts::font_label(used); + let kind = font_type(used); + let name = match kind { + "truetype" => "TrueType", + "opentype" => "OpenType", + _ => "unknown type", + }; + let count = if uses == 1 { "1 use".to_string() } else { format!("{uses} uses") }; + (json!({ "font": label, "type": kind, "uses": uses }), (label, format!("{name}; {count}"))) +} + +/// Counts text object `t` once for each font its runs are drawn in, a composite font's parts in +/// place of its name ([`super::fonts::run_fonts`]). +fn count_fonts(fonts: &mut BTreeMap, t: &vectorcraft_doc::TextObject) { + let own: BTreeSet = t.runs.iter().flat_map(super::fonts::run_fonts).collect(); + for font in own { + *fonts.entry(font).or_default() += 1; + } +} + /// An image object as Document Info lists it: (name, width, height, linked file). type ImageRow = (String, u32, u32, Option); @@ -221,16 +260,16 @@ fn selected_artboard_rows(d: &Document, picked: &[usize], active: usize) -> (Vec } /// The Document Info categories of `d` (only `category` when given) from `info` (what -/// `document.info` reports), the rows of the artboards the Artboard tool has selected, its fonts -/// and their Font Details rows, its image objects, the rows of the brushes its art uses, the rows -/// of its Repeat objects and the rows of its objects filled or stroked with a spot color, with a -/// pattern and with a gradient. +/// `document.info` reports), the rows of the artboards the Artboard tool has selected, the rows of +/// its fonts and their Font Details rows, its image objects, the rows of the brushes its art uses, +/// the rows of its Repeat objects and the rows of its objects filled or stroked with a spot color, +/// with a pattern and with a gradient. #[allow(clippy::too_many_arguments)] fn sections( d: &Document, info: &Value, selected_artboards: &[(String, String)], - fonts: &BTreeSet, + fonts: &[(String, String)], font_details: &[(String, String)], images: &[ImageRow], brushes: &[(String, String)], @@ -296,7 +335,7 @@ fn sections( "patterns" => pattern_objects.to_vec(), "gradients" => gradient_objects.to_vec(), "symbols" => names("symbols"), - "fonts" => fonts.iter().map(|f| (super::fonts::font_label(f), String::new())).collect(), + "fonts" => fonts.to_vec(), "fontDetails" => font_details.to_vec(), "linkedImages" => { images.iter().filter_map(|(name, w, h, link)| Some((name.clone(), format!("{w} × {h} px — {}", link.as_ref()?)))).collect() @@ -627,7 +666,8 @@ fn info(s: &mut Session, p: &Value) -> Result { // The paths' total length, as Document Info › Objects shows it (the length of a cut line, a // strip of LEDs along the letters, #1958). let mut path_length = 0.0; - let mut fonts = BTreeSet::new(); + // Each font with the number of text objects set in it. + let mut fonts: BTreeMap = BTreeMap::new(); let mut images: BTreeMap = BTreeMap::new(); let mut image_rows: Vec = vec![]; // Whether the request being served may read each linked file (a relative path read from the @@ -702,9 +742,7 @@ fn info(s: &mut Session, p: &Value) -> Result { } NodeKind::Compound { .. } => Some("compoundPaths"), NodeKind::Text(t) => { - for run in &t.runs { - fonts.insert((run.style.font_family.clone(), run.style.font_style.clone(), run.style.font_version.clone())); - } + count_fonts(&mut fonts, t); Some("textObjects") } NodeKind::Image(im) => { @@ -787,12 +825,16 @@ fn info(s: &mut Session, p: &Value) -> Result { } } // The document's fonts include those of the type in opacity masks and in the art of its - // symbols and patterns, as Find Font lists them. + // symbols and patterns, as Find Font lists them. Each of those text objects counts once, however + // many objects show it. if !selection_only { - fonts.extend(super::fonts::art_texts_of(d).into_iter().flat_map(|(_, t, _)| t.runs.iter().map(|r| super::fonts::font_of(&r.style)))); + for (_, t, _) in super::fonts::art_texts_of(d) { + count_fonts(&mut fonts, t); + } } - let font_names: Vec = fonts.iter().map(super::fonts::font_label).collect(); - let (font_entries, font_rows): (Vec, Vec<(String, String)>) = fonts.iter().map(font_detail).unzip(); + let font_names: Vec = fonts.keys().map(super::fonts::font_label).collect(); + let (font_uses, font_use_rows): (Vec, Vec<(String, String)>) = fonts.iter().map(|(f, n)| font_use(f, *n)).unzip(); + let (font_entries, font_rows): (Vec, Vec<(String, String)>) = fonts.keys().map(font_detail).unzip(); // The image objects in walk order, as Linked Images and Embedded Images list them: `file` is a // linked image's row value (its path, or its file name alone when the request may not read it), // and null for an embedded one. @@ -820,6 +862,7 @@ fn info(s: &mut Session, p: &Value) -> Result { "objects": counts, "pathLength": path_length, "fonts": font_names, + "fontUses": font_uses, "fontDetails": font_entries, "images": images, "imageObjects": image_objects, @@ -850,7 +893,7 @@ fn info(s: &mut Session, p: &Value) -> Result { d, &out, &selected_rows, - &fonts, + &font_use_rows, &font_rows, &image_rows, &brush_rows, @@ -1083,6 +1126,92 @@ mod tests { assert_eq!(fonts(&mut s, json!({"selectionOnly": true})), json!(["Source Sans 3 Regular"])); } + /// Fonts gives each font's type and its number of uses: the text objects set in it, each once + /// however many of its runs use the font. The type in a symbol's art counts once however many + /// instances show it, and the type in an opacity mask once. With Selection Only it counts the + /// selected type alone. A font that is not installed has an unknown type. The rows, the report + /// and `fontUses` give the same facts, in the order of `fonts`. + #[test] + fn info_fonts_give_each_font_s_type_and_uses() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let id = |v: Value| NodeId(v["id"].as_u64().unwrap()); + let text = + |s: &mut Session, font: &str, y: f64| id(s.execute("text.create", &json!({"x": 10, "y": y, "text": "Hello", "font": font})).unwrap()); + // Two runs in Source Sans 3 Regular in one text object, a second object in it, and one in Inter. + let twice = text(&mut s, "Source Sans 3", 20.0); + s.execute("text.setRangeStyle", &json!({"id": twice.0, "start": 0, "end": 2, "size": 30})).unwrap(); + assert!(matches!(&s.doc().unwrap().doc.node(twice).unwrap().kind, NodeKind::Text(t) if t.runs.len() == 2)); + let other = text(&mut s, "Source Sans 3", 50.0); + text(&mut s, "Inter", 80.0); + text(&mut s, "Qx Absent Family", 110.0); + // A symbol whose art holds type in Inter, shown by two instances, and a mask holding type in Inter. + let in_symbol = text(&mut s, "Inter", 140.0); + s.execute("symbol.new", &json!({"name": "Mark", "ids": [in_symbol.0]})).unwrap(); + s.execute("symbol.place", &json!({"name": "Mark", "x": 100, "y": 100})).unwrap(); + let masked = id(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()); + let in_mask = text(&mut s, "Inter", 170.0); + s.edit("Mask", |d, _| { + let art = d.remove(in_mask)?; + d.node_mut(masked).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new((*art).clone(), true))); + Ok(()) + }) + .unwrap(); + let i = s.execute("document.info", &json!({"category": "fonts"})).unwrap(); + assert_eq!(i["fonts"], json!(["Inter Regular", "Qx Absent Family Regular", "Source Sans 3 Regular"])); + assert_eq!( + i["fontUses"], + json!([ + {"font": "Inter Regular", "type": "truetype", "uses": 3}, + {"font": "Qx Absent Family Regular", "type": "unknown", "uses": 1}, + {"font": "Source Sans 3 Regular", "type": "truetype", "uses": 2}, + ]) + ); + assert_eq!( + i["sections"][0]["rows"], + json!([ + ["Inter Regular", "TrueType; 3 uses"], + ["Qx Absent Family Regular", "unknown type; 1 use"], + ["Source Sans 3 Regular", "TrueType; 2 uses"], + ]) + ); + let report = s.execute("document.info", &json!({"category": "fonts", "format": "text"})).unwrap()["text"].as_str().unwrap().to_string(); + assert!(report.contains("\nFONTS\nInter Regular: TrueType; 3 uses\nQx Absent Family Regular: unknown type; 1 use\n"), "{report}"); + // Selection Only: the selected type's fonts and uses. + s.execute("select.set", &json!({"ids": [other.0]})).unwrap(); + let i = s.execute("document.info", &json!({"selectionOnly": true, "category": "fonts"})).unwrap(); + assert_eq!(i["fontUses"], json!([{"font": "Source Sans 3 Regular", "type": "truetype", "uses": 1}])); + assert_eq!(i["sections"][0]["rows"], json!([["Source Sans 3 Regular", "TrueType; 1 use"]])); + s.execute("select.none", &json!({})).unwrap(); + let i = s.execute("document.info", &json!({"selectionOnly": true, "category": "fonts"})).unwrap(); + assert_eq!((i["fontUses"].clone(), i["sections"][0]["rows"].clone()), (json!([]), json!([]))); + } + + /// Type set in a composite font counts as a use of the fonts of the parts its characters fall + /// in, as Find Font lists them, not of the composite font's name. + #[test] + fn info_fonts_count_the_parts_of_a_composite_font() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let font = json!({"name": "DI Uses Composite", "parts": { + "kanji": {"font": "Source Sans 3"}, + "roman": {"font": "JetBrains Mono"}, + "numerals": {"font": "Inter"}, + }}); + s.execute("type.compositeFonts.set", &json!({"fonts": [font]})).unwrap(); + s.execute("text.create", &json!({"x": 10, "y": 20, "text": "Ab1", "font": "DI Uses Composite"})).unwrap(); + s.execute("text.create", &json!({"x": 10, "y": 50, "text": "12", "font": "DI Uses Composite"})).unwrap(); + let i = s.execute("document.info", &json!({"category": "fonts"})).unwrap(); + assert_eq!(i["fonts"], json!(["Inter Regular", "JetBrains Mono Regular"])); + assert_eq!( + i["fontUses"], + json!([ + {"font": "Inter Regular", "type": "truetype", "uses": 2}, + {"font": "JetBrains Mono Regular", "type": "truetype", "uses": 1}, + ]) + ); + } + /// Document Info › Objects gives the paths' total length in the document's units (#1958): an /// open line, a closed rectangle's perimeter and a compound path's pieces count, a guide doesn't. #[test] diff --git a/crates/engine/src/cmd/draw2/commands.rs b/crates/engine/src/cmd/draw2/commands.rs index 4e753ce00c..45171f62a1 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\"} (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", + "{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation,wheel]…] (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. An airbrush pen's finger wheel 0..1: the stroke keeps it for brushes with Stylus Wheel variation, a point without one half way; null for what a point lacks. A pressure, tilt, rotation or wheel outside its range, or a point array of more than seven 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 ), @@ -92,7 +92,7 @@ pub fn specs() -> Vec { "Eraser", [], None, - "{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1, tilt −90..90°, barrel rotation 0..360° clockwise; pen values are checked as path.freehand checks them), size?: pt (10; from 0.1 to 1000), angle?: ° (0, −180–180: the tip's long axis counter-clockwise from level), roundness?: % (100, 1–100), angleMode?, roundnessMode?, sizeMode?: \"fixed\" (default) | \"random\" | \"pressure\" | \"tilt\" | \"bearing\" | \"rotation\" (Eraser Tool Options' variation menus; a varied angle turns either way, clockwise or counter-clockwise), angleVariation?: ° (0–180, default 0, either way: clockwise or counter-clockwise), roundnessVariation?: % (0–100, default 0), sizeVariation?: pt (0–1000, default 0)} or {rect: [x, y, width, height] (pt; the Eraser's Alt-drag marquee)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one. A value whose mode is not fixed varies by up to its variation either way: random draws one value for the drag; pressure goes from the value less the variation where the pen presses lightest to the value plus it where it presses hardest (size on pressure as path.blob); tilt from less with the pen lying flat to more with it upright; bearing and rotation from less at −180° to more at 180° of the pen's lean direction or barrel turn. A drag without that pen reading (a mouse) erases at the value itself. An angle or roundness outside its range, an unknown mode, or a variation below 0 or past its range is refused with an error and erases nothing. `rect` in place of `points` erases everything inside the rectangle: closed paths and filled open paths without a visible painted stroke lose its area, and other open paths are cut where they cross its edges; the tip's size, angle, roundness and variations do not apply. A width or height of 0 or less, a value that is not a finite number, or `points` and `rect` together is an error. When nothing is erased, no undo step is added", + "{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] or [[x,y,pressure,tiltX,tiltY,rotation,wheel]…] (pen pressure 0..1, tilt −90..90°, barrel rotation 0..360° clockwise, finger wheel 0..1; pen values are checked as path.freehand checks them), size?: pt (10; from 0.1 to 1000), angle?: ° (0, −180–180: the tip's long axis counter-clockwise from level), roundness?: % (100, 1–100), angleMode?, roundnessMode?, sizeMode?: \"fixed\" (default) | \"random\" | \"pressure\" | \"tilt\" | \"bearing\" | \"rotation\" | \"stylusWheel\" (Eraser Tool Options' variation menus; a varied angle turns either way, clockwise or counter-clockwise), angleVariation?: ° (0–180, default 0, either way: clockwise or counter-clockwise), roundnessVariation?: % (0–100, default 0), sizeVariation?: pt (0–1000, default 0)} or {rect: [x, y, width, height] (pt; the Eraser's Alt-drag marquee)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one. A value whose mode is not fixed varies by up to its variation either way: random draws one value for the drag; pressure goes from the value less the variation where the pen presses lightest to the value plus it where it presses hardest (size on pressure as path.blob); tilt from less with the pen lying flat to more with it upright; bearing and rotation from less at −180° to more at 180° of the pen's lean direction or barrel turn; stylusWheel from less at one end of an airbrush pen's finger wheel travel to more at the other. A drag without that pen reading (a mouse) erases at the value itself. An angle or roundness outside its range, an unknown mode, or a variation below 0 or past its range is refused with an error and erases nothing. `rect` in place of `points` erases everything inside the rectangle: closed paths and filled open paths without a visible painted stroke lose its area, and other open paths are cut where they cross its edges; the tip's size, angle, roundness and variations do not apply. A width or height of 0 or less, a value that is not a finite number, or `points` and `rect` together is an error. When nothing is erased, no undo step is added", has_doc, erase_region ), diff --git a/crates/engine/src/cmd/draw2/common.rs b/crates/engine/src/cmd/draw2/common.rs index 694e6aeca5..36280196b7 100644 --- a/crates/engine/src/cmd/draw2/common.rs +++ b/crates/engine/src/cmd/draw2/common.rs @@ -22,15 +22,17 @@ pub(super) struct Sample { tilt: Option<[f64; 2]>, /// Barrel rotation, degrees clockwise. rotation: Option, + /// The airbrush finger wheel, 0..1. + wheel: Option, } /// The keys of a point's pen values, in the order a point given as an array holds them after its /// x and y. -const PEN_KEYS: [&str; 4] = ["pressure", "tiltX", "tiltY", "rotation"]; +const PEN_KEYS: [&str; 5] = ["pressure", "tiltX", "tiltY", "rotation", "wheel"]; -/// The range each of [`PEN_KEYS`] takes: pressure 0..1, each tilt −90..90 degrees and rotation -/// 0..360 degrees (360 is the same direction as 0). -const PEN_RANGES: [(f64, f64); PEN_KEYS.len()] = [(0.0, 1.0), (-90.0, 90.0), (-90.0, 90.0), (0.0, 360.0)]; +/// The range each of [`PEN_KEYS`] takes: pressure 0..1, each tilt −90..90 degrees, rotation +/// 0..360 degrees (360 is the same direction as 0) and the wheel 0..1. +const PEN_RANGES: [(f64, f64); PEN_KEYS.len()] = [(0.0, 1.0), (-90.0, 90.0), (-90.0, 90.0), (0.0, 360.0), (0.0, 1.0)]; /// Blob Brush and Eraser Tool Options' Size, in points. pub(super) const SIZES: (f64, f64) = (0.1, 1000.0); @@ -61,11 +63,11 @@ pub(super) fn point_entry(v: &Value, cmd: &str) -> Result { } /// [`points_param`] with what a pen read at each point, as far as it is given: -/// `[[x,y,pressure,tiltX,tiltY,rotation]…]` or `[{x,y,pressure,tiltX,tiltY,rotation}…]`. Pressure -/// is 0..1; tilt in degrees, each −90..90 (one of the two without the other is 0); rotation in -/// degrees clockwise, 0..360. A point whose x or y is not a number, whose pressure, tilt or -/// rotation is neither a number nor null or is outside its range, or an array of more than six -/// numbers, is an error. +/// `[[x,y,pressure,tiltX,tiltY,rotation,wheel]…]` or `[{x,y,pressure,tiltX,tiltY,rotation,wheel}…]`. +/// Pressure is 0..1; tilt in degrees, each −90..90 (one of the two without the other is 0); +/// rotation in degrees clockwise, 0..360; the wheel 0..1. A point whose x or y is not a number, +/// whose pressure, tilt, rotation or wheel is neither a number nor null or is outside its range, +/// or an array of more than seven numbers, is an error. pub(super) fn samples_param(p: &Value, key: &str, cmd: &str) -> Result> { let a = p.get(key).and_then(Value::as_array).ok_or_else(|| bad(cmd, format!("missing array `{key}`")))?; let pts: Vec = a @@ -79,7 +81,7 @@ pub(super) fn samples_param(p: &Value, key: &str, cmd: &str) -> Result xy.get(i + 2), @@ -91,9 +93,9 @@ pub(super) fn samples_param(p: &Value, key: &str, cmd: &str) -> Result return Err(bad(cmd, format!("`{key}` must be a number, not {v}"))), }; } - let [pressure, tx, ty, rotation] = pen; + let [pressure, tx, ty, rotation, wheel] = pen; let tilt = (tx.is_some() || ty.is_some()).then(|| [tx, ty].map(|t| t.unwrap_or(0.0))); - Ok(Sample { pt: point_entry(v, cmd)?, pressure, tilt, rotation }) + Ok(Sample { pt: point_entry(v, cmd)?, pressure, tilt, rotation, wheel }) }) .collect::>()?; if pts.is_empty() { @@ -126,6 +128,15 @@ fn stroke_pressure(samples: &[Sample]) -> Option { PressureProfile::from_samples(along(samples).into_iter().zip(samples).map(|(t, s)| (t, s.pressure.unwrap_or(1.0)))) } +/// Where an airbrush pen's finger wheel was set along a freehand stroke, when any of its samples +/// has it; samples without it count as the middle of its travel, which draws a brush's own value. +fn stroke_wheel(samples: &[Sample]) -> Option { + if samples.iter().all(|s| s.wheel.is_none()) { + return None; + } + PressureProfile::from_samples(along(samples).into_iter().zip(samples).map(|(t, s)| (t, s.wheel.unwrap_or(PressureProfile::MID)))) +} + /// A pen that leans less than this many degrees from upright leans no way in particular: its /// bearing is the one before it. const UPRIGHT: f64 = 1.0; @@ -165,24 +176,31 @@ fn stroke_pose(samples: &[Sample]) -> (Option, Option, tilt: Option, bearing: Option, rotation: Option, + wheel: Option, } impl PenRecord { /// What a freehand stroke's samples recorded. pub(super) fn of_samples(samples: &[Sample]) -> Self { let (tilt, bearing, rotation) = stroke_pose(samples); - Self { pressure: stroke_pressure(samples), tilt, bearing, rotation } + Self { pressure: stroke_pressure(samples), tilt, bearing, rotation, wheel: stroke_wheel(samples) } } pub(super) fn of(st: &StrokeLayer) -> Self { - Self { pressure: st.pressure.clone(), tilt: st.tilt.clone(), bearing: st.bearing.clone(), rotation: st.rotation.clone() } + Self { + pressure: st.pressure.clone(), + tilt: st.tilt.clone(), + bearing: st.bearing.clone(), + rotation: st.rotation.clone(), + wheel: st.wheel.clone(), + } } pub(super) fn is_empty(&self) -> bool { *self == Self::default() @@ -195,6 +213,7 @@ impl PenRecord { tilt: PressureProfile::extended(self.tilt.as_ref(), old_len, added.tilt.as_ref(), added_len), bearing: AngleProfile::extended(self.bearing.as_ref(), old_len, added.bearing.as_ref(), added_len), rotation: AngleProfile::extended(self.rotation.as_ref(), old_len, added.rotation.as_ref(), added_len), + wheel: PressureProfile::extended(self.wheel.as_ref(), old_len, added.wheel.as_ref(), added_len), } } /// The record along the path reversed. @@ -204,6 +223,7 @@ impl PenRecord { tilt: self.tilt.as_ref().map(PressureProfile::reversed), bearing: self.bearing.as_ref().map(AngleProfile::reversed), rotation: self.rotation.as_ref().map(AngleProfile::reversed), + wheel: self.wheel.as_ref().map(PressureProfile::reversed), } } /// Keep the record on stroke `st`. @@ -212,6 +232,7 @@ impl PenRecord { st.tilt = self.tilt; st.bearing = self.bearing; st.rotation = self.rotation; + st.wheel = self.wheel; } } diff --git a/crates/engine/src/cmd/draw2/cut.rs b/crates/engine/src/cmd/draw2/cut.rs index d97c18305c..cc543f3e05 100644 --- a/crates/engine/src/cmd/draw2/cut.rs +++ b/crates/engine/src/cmd/draw2/cut.rs @@ -438,7 +438,7 @@ fn erase_rect(s: &mut Session, r: Rect) -> Result { /// The variation modes `path.eraseRegion` takes for each of `angleMode`, `roundnessMode` and /// `sizeMode`. -const ERASER_MODES: &str = "\"fixed\", \"random\", \"pressure\", \"tilt\", \"bearing\" or \"rotation\""; +const ERASER_MODES: &str = "\"fixed\", \"random\", \"pressure\", \"tilt\", \"bearing\", \"rotation\" or \"stylusWheel\""; /// Eraser Tool Options' Angle, Roundness and Size variations: for each of angle (`angleMode` with /// `angleVariation` in degrees, at most 180), roundness (`roundnessMode` with `roundnessVariation` diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index f126ac78ec..5e0231228b 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -115,7 +115,7 @@ pub fn specs() -> Vec { "Drop Artwork", [], None, - "{sourceDocument: uid, ids: [id…], grab: [x,y], at: [x,y]} copy 1–10000 editable source objects from an open document to the active document, preserving the grab point and clipboard, as one undo step", + "{sourceDocument: uid, ids: [id…], grab: [x,y], at: [x,y], profileMismatch?: as edit.paste} copy 1–10000 editable source objects from an open document to the active document, preserving the grab point and clipboard, as one undo step; colors from a document with another RGB or CMYK profile keep their numbers or convert as profileMismatch says, else as edit.colorSettings' policy of their model says (as edit.paste; clipboard.profileMismatch {sourceDocument, ids} lists them, and with askMismatchPaste on the desktop app asks first) → {ids, added, merged, renamed, profileMismatch?}", has_doc, drop_selection ), @@ -180,7 +180,7 @@ pub fn specs() -> Vec { "Paste", ["Edit"], Some("Cmd+V"), - "{center?: [x, y], artboardsAt?: [x, y], dx?, dy?, swatchConflict?} paste centred on `center` (the app passes the view centre), else offset by dx/dy (default: the Paste Offset preference). Pasting brings the image blobs, symbols, patterns, global and spot swatches (with the tint swatches of the tints used), gradient swatches, graphic styles, character and paragraph styles and brushes the objects use; one of the same name that differs comes in renamed. swatchConflict, for a swatch whose name the document gives another colour (clipboard.conflicts): \"merge\" (default: the objects take the document's swatch; legend labels in a pie's wedges that it turns dark or light take a redraw's contrast, unless their fill is their own) | \"add\" (the pasted swatch comes in renamed) | {name: \"merge\"|\"add\"}. With Paste Remembers Layers on (layer.pasteRemembersLayers), objects go back into the layers and sublayers they came from (by the names of the layer and the layers around it in another document; a missing sublayer is made inside its layer; a hidden or locked one is an error and nothing is pasted). Artboards copied with artboard.copy come with their art, together right of the last artboard as they lay, or centered on `artboardsAt` (the Artboard tool's canvas menu passes the right-click point; a value that is not [x, y] is an error) (the other paste commands but Paste on All Artboards: where they were), their art back in the layers it came from, and the Artboard tool, when chosen, selects them. In Draw Inside (view.drawMode) the objects go inside the object drawn into, as new art does, and Paste Remembers Layers doesn't apply; edit.pasteInPlace and edit.pasteOnAllArtboards do the same, and in Draw Behind they go behind the selection as edit.pasteInBack puts them; edit.pasteInFront and edit.pasteInBack ignore the drawing mode → {ids, artboard: the first new artboard's index or null, artboards: the new artboards' indices, added: resources added, merged: conflicts merged, renamed: [{kind, from, to}]}", + "{center?: [x, y], artboardsAt?: [x, y], dx?, dy?, swatchConflict?, profileMismatch?: \"preserveNumbers\"|\"convert\"|{rgb?, cmyk?}} paste centred on `center` (the app passes the view centre), else offset by dx/dy (default: the Paste Offset preference). Pasting brings the image blobs, symbols, patterns, global and spot swatches (with the tint swatches of the tints used), gradient swatches, graphic styles, character and paragraph styles and brushes the objects use; one of the same name that differs comes in renamed. swatchConflict, for a swatch whose name the document gives another colour (clipboard.conflicts): \"merge\" (default: the objects take the document's swatch; legend labels in a pie's wedges that it turns dark or light take a redraw's contrast, unless their fill is their own) | \"add\" (the pasted swatch comes in renamed) | {name: \"merge\"|\"add\"}. profileMismatch, for colors copied from a document whose RGB or CMYK profile is not this document's (clipboard.profileMismatch): \"preserveNumbers\" keeps their numbers, \"convert\" converts them into this document's profile with the working intent, and {rgb?, cmyk?} gives one of those for each model (default, also for a model left out and for null: as the model's policy of edit.colorSettings says; any other value is an error; colors whose source or destination profile is not available keep their numbers, also with \"convert\" (clipboard.profileMismatch's convertible: false); every paste command takes it, and the reply's profileMismatch lists [{model, clipboard, document, choice}]). With Paste Remembers Layers on (layer.pasteRemembersLayers), objects go back into the layers and sublayers they came from (by the names of the layer and the layers around it in another document; a missing sublayer is made inside its layer; a hidden or locked one is an error and nothing is pasted). Artboards copied with artboard.copy come with their art, together right of the last artboard as they lay, or centered on `artboardsAt` (the Artboard tool's canvas menu passes the right-click point; a value that is not [x, y] is an error) (the other paste commands but Paste on All Artboards: where they were), their art back in the layers it came from, and the Artboard tool, when chosen, selects them. In Draw Inside (view.drawMode) the objects go inside the object drawn into, as new art does, and Paste Remembers Layers doesn't apply; edit.pasteInPlace and edit.pasteOnAllArtboards do the same, and in Draw Behind they go behind the selection as edit.pasteInBack puts them; edit.pasteInFront and edit.pasteInBack ignore the drawing mode → {ids, artboard: the first new artboard's index or null, artboards: the new artboards' indices, added: resources added, merged: conflicts merged, renamed: [{kind, from, to}]}", has_clipboard, |s, p| paste(s, p, PasteMode::Offset) ), @@ -189,7 +189,7 @@ pub fn specs() -> Vec { "Paste in Front", ["Edit"], Some("Cmd+F"), - "{swatchConflict?, artboard?: index (the active artboard: the objects go where they were on the artboard they were copied from, on this one), artboards?: [index…] (a copy on each of these artboards, placed as on `artboard`, the copies in artboard order; `artboard` wins when both are given; default while the Artboard tool is chosen with several artboards selected: those; art copied from no artboard keeps its place on the first and its offset to it on the others; an index the document lacks, a repeated one or an empty list is an error)} paste in place just above the top selected object, or on top of the current layer when nothing is selected (resources and layers as edit.paste) → {ids, added, merged, renamed}", + "{swatchConflict?, profileMismatch? (as edit.paste), artboard?: index (the active artboard: the objects go where they were on the artboard they were copied from, on this one), artboards?: [index…] (a copy on each of these artboards, placed as on `artboard`, the copies in artboard order; `artboard` wins when both are given; default while the Artboard tool is chosen with several artboards selected: those; art copied from no artboard keeps its place on the first and its offset to it on the others; an index the document lacks, a repeated one or an empty list is an error)} paste in place just above the top selected object, or on top of the current layer when nothing is selected (resources and layers as edit.paste) → {ids, added, merged, renamed}", has_clipboard, |s, p| paste(s, p, PasteMode::Front) ), @@ -198,7 +198,7 @@ pub fn specs() -> Vec { "Paste in Back", ["Edit"], Some("Cmd+B"), - "{swatchConflict?, artboard?: index, artboards?: [index…] (both as edit.pasteInFront)} paste in place just below the bottom selected object, or at the bottom of the current layer when nothing is selected (resources and layers as edit.paste) → {ids, added, merged, renamed}", + "{swatchConflict?, profileMismatch?, artboard?: index, artboards?: [index…] (as edit.pasteInFront)} paste in place just below the bottom selected object, or at the bottom of the current layer when nothing is selected (resources and layers as edit.paste) → {ids, added, merged, renamed}", has_clipboard, |s, p| paste(s, p, PasteMode::Back) ), @@ -207,7 +207,7 @@ pub fn specs() -> Vec { "Paste in Place", ["Edit"], Some("Cmd+Shift+V"), - "{swatchConflict?, artboard?: index, artboards?: [index…] (both as edit.pasteInFront)} paste where the objects were copied (resources, layers and drawing modes as edit.paste) → {ids, added, merged, renamed}", + "{swatchConflict?, profileMismatch?, artboard?: index, artboards?: [index…] (as edit.pasteInFront)} paste where the objects were copied (resources, layers and drawing modes as edit.paste) → {ids, added, merged, renamed}", has_clipboard, |s, p| paste(s, p, PasteMode::InPlace) ), @@ -216,7 +216,7 @@ pub fn specs() -> Vec { "Paste on All Artboards", ["Edit"], Some("Cmd+Alt+Shift+V"), - "{swatchConflict?} paste a copy on every artboard at the offset the objects had to the artboard they were copied from (resources, layers and drawing modes as edit.paste) → {ids, added, merged, renamed}", + "{swatchConflict?, profileMismatch? (as edit.paste)} paste a copy on every artboard at the offset the objects had to the artboard they were copied from (resources, layers and drawing modes as edit.paste) → {ids, added, merged, renamed}", has_clipboard, |s, p| paste(s, p, PasteMode::AllArtboards) ), @@ -1278,26 +1278,12 @@ fn clear(s: &mut Session, p: &Value) -> Result { /// Document ids scope node ids: two tabs may contain objects with the same node id. fn drop_selection(s: &mut Session, p: &Value) -> Result { const CMD: &str = "edit.dropSelection"; - let uid = u64_req(p, "sourceDocument", CMD)?; + u64_req(p, "sourceDocument", CMD)?; let point = |key: &str| finite_numbers::<2>(&p[key]).ok_or_else(|| bad(CMD, format!("{key} must be [x, y] with finite coordinates"))); let grab = point("grab")?; let at = point("at")?; - let source = s.documents().iter().find(|d| d.uid == uid).ok_or_else(|| bad(CMD, "that document is no longer open"))?; - let key = "ids"; - let values = p[key].as_array().ok_or_else(|| bad(CMD, format!("{key} must be an array of non-negative integer object ids")))?; - if values.is_empty() || values.len() > 10000 { - return Err(bad(CMD, "ids must contain 1–10000 object ids")); - } - let ids = values - .iter() - .map(|value| value.as_u64().map(NodeId).ok_or_else(|| bad(CMD, format!("invalid object id {value}: expected a non-negative integer")))) - .collect::>>()?; - // Validate the entire batch in one walk; node ids are local to the source document. - let paths = source.doc.index_paths(ids.iter().copied()); - if let Some(id) = ids.iter().find(|id| !paths.contains_key(id)) { - return Err(EngineError::NoNode(*id)); - } - let clip = Clipboard::copy(source, &roots_of(&source.doc, ids), false); + let profile = super::colormgmt::PasteProfile::param(p, CMD)?; + let clip = drop_clip(s, p, CMD)?; let bounds = clip.bounds().ok_or_else(|| bad(CMD, "the art has no bounds"))?; let center = bounds.center() + Vec2::new(at[0] - grab[0], at[1] - grab[1]); if !center.x.is_finite() || !center.y.is_finite() { @@ -1305,7 +1291,38 @@ fn drop_selection(s: &mut Session, p: &Value) -> Result { } // A drop preserves the source colours even when the flyer has same-named swatches. let choices = SwatchChoices::parse(PasteMode::Drag.label(), &json!({"swatchConflict": "add"}))?; - paste_clip(s, &json!({"center": [center.x, center.y]}), PasteMode::Drag, &clip, &choices) + // Colors from another profile keep their numbers or convert, as `profileMismatch` says, else as + // the policies say. + let (converted, report) = super::colormgmt::paste_profiles(&clip, &s.doc()?.doc, profile, true); + let mut r = paste_clip(s, &json!({"center": [center.x, center.y]}), PasteMode::Drag, converted.as_ref().unwrap_or(&clip), &choices); + if let Ok(v) = &mut r + && !report.is_empty() + { + v["profileMismatch"] = json!(report); + } + r +} + +/// The objects `ids` of the open document `sourceDocument` that `edit.dropSelection` drops, copied +/// as a clipboard is (errors name command `cmd`). +pub(crate) fn drop_clip(s: &Session, p: &Value, cmd: &str) -> Result { + let uid = u64_req(p, "sourceDocument", cmd)?; + let source = s.documents().iter().find(|d| d.uid == uid).ok_or_else(|| bad(cmd, "that document is no longer open"))?; + let key = "ids"; + let values = p[key].as_array().ok_or_else(|| bad(cmd, format!("{key} must be an array of non-negative integer object ids")))?; + if values.is_empty() || values.len() > 10000 { + return Err(bad(cmd, "ids must contain 1–10000 object ids")); + } + let ids = values + .iter() + .map(|value| value.as_u64().map(NodeId).ok_or_else(|| bad(cmd, format!("invalid object id {value}: expected a non-negative integer")))) + .collect::>>()?; + // Validate the entire batch in one walk; node ids are local to the source document. + let paths = source.doc.index_paths(ids.iter().copied()); + if let Some(id) = ids.iter().find(|id| !paths.contains_key(id)) { + return Err(EngineError::NoNode(*id)); + } + Ok(Clipboard::copy(source, &roots_of(&source.doc, ids), false)) } #[derive(Clone, Copy, PartialEq, Eq)] @@ -1340,10 +1357,23 @@ fn paste(s: &mut Session, p: &Value, mode: PasteMode) -> Result { if mode == PasteMode::Offset { check_numbers(p, &["dx", "dy"], "edit.paste")?; } + let profile = super::colormgmt::PasteProfile::param(p, mode.label())?; // Taken out of the session for the edit (and put back whatever happens). let clip = std::mem::take(&mut s.clipboard); - let r = paste_clip(s, p, mode, &clip, &choices); + // Colors copied from a document with other profiles keep their numbers or convert + // (Edit › Color Settings' policies, or `profileMismatch`). Paste on All Artboards leaves the + // copied artboards, and so their backgrounds, behind. + let (converted, report) = match s.doc() { + Ok(st) => super::colormgmt::paste_profiles(&clip, &st.doc, profile, mode != PasteMode::AllArtboards), + Err(_) => (None, vec![]), + }; + let mut r = paste_clip(s, p, mode, converted.as_ref().unwrap_or(&clip), &choices); s.clipboard = clip; + if let Ok(v) = &mut r + && !report.is_empty() + { + v["profileMismatch"] = json!(report); + } r } @@ -1520,6 +1550,8 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho vec![Affine::IDENTITY] }; let (ids, imported, artboards, into) = s.edit(mode.label(), |d, sel| { + // Converted colors are compared with the document's resources, as another document's are + // (`Clipboard::import_into`); its images are still the document's own. let imported = clip.import_into(d, choices, same_doc)?; // Draw Inside: the clip group of the object drawn into, made on the first paste. let into = inside.map(|t| super::create::draw_inside_group(d, t)).transpose()?; diff --git a/crates/engine/src/cmd/effectcmd/graphics.rs b/crates/engine/src/cmd/effectcmd/graphics.rs index 868f6f5c5c..743101a984 100644 --- a/crates/engine/src/cmd/effectcmd/graphics.rs +++ b/crates/engine/src/cmd/effectcmd/graphics.rs @@ -32,6 +32,15 @@ pub(super) fn specs() -> Vec { has_doc, map_graphic ), + cmd!( + "threeD.mapArt", + "Map Art", + [], + None, + "{surface?: integer (1..the object's surface count: Extrude & Bevel (Classic) numbers each solid's front cap and back cap (none on a hollow solid, cap false), then each side wall from corner to corner of the outline, then the bevel above each wall; Revolve (Classic)'s swept side is surface 1, in a group the side of the member with the longest profile, and the other members take no map), symbol?: name of a document symbol|null (with surface: the symbol mapped onto it; null removes the surface's map, also a map kept past the surface count, and is refused with x, y, scaleX, scaleY, rotation or fit true; omitted: the surface's map keeps its symbol, and a surface with no map is refused), x?: pt, y?: pt (-1000000..1000000; the offset of the art's center from the center of the surface laid out flat; a new map starts at 0, 0), scaleX?: %, scaleY?: % (1..10000; of the symbol's own width and height; a new map starts at 100), rotation?: degrees (-360..360; counterclockwise; a new map starts at 0), fit?: bool (false; true is Scale to Fit: the art is centered and scaled to fill the surface, each side on its own when the art is square to the surface, else in proportion; art with no area keeps its scales), clearAll?: bool (false; true removes every map first, so with surface only that surface's map is left), shade?: bool (Shade Artwork: the mapped art takes the tone and highlight of its face), invisible?: bool (Invisible Geometry: with at least one map, only the mapped art is drawn), index?: int (the 3D effect's position; default: each object's first Extrude & Bevel (Classic) or Revolve (Classic), its own before its fills' and strokes'), item?: appearance item index|null (refused without index; as effect.setParams), ids?|id?} set, edit or remove the art mapped onto the numbered surfaces of each selected object's 3D effect, which must be Extrude & Bevel (Classic) or Revolve (Classic) (Rotate (Classic) takes no map); one of surface, clearAll, shade or invisible is required; the maps are the effect's mapArt, mapShade and mapInvisible parameters; one undo step, and none when nothing changes → {ids: [the objects changed], maps: [the first object's maps]}", + has_doc, + map_art + ), ] } @@ -158,6 +167,178 @@ fn map_graphic(s: &mut Session, p: &Value) -> Result { Ok(json!({ "ids": ids_json(&ids), "graphic": first })) } +/// The effect of `n` that Map Art edits when none is named: its first Extrude & Bevel (Classic) or +/// Revolve (Classic), its own before its fills' and strokes'. +fn first_mapped(n: &Node) -> Option<(Option, usize)> { + let at = |fx: &[Effect]| fx.iter().position(|e| effects::takes_map_art(&e.id)); + at(&n.appearance.effects) + .map(|i| (None, i)) + .or_else(|| n.appearance.items.iter().enumerate().find_map(|(k, item)| at(item.effects()).map(|i| (Some(k), i)))) +} + +/// `threeD.mapArt`: sets, edits or removes the maps of each target's classic 3D effect, after +/// checking that every target takes the change. Nothing is recorded when no target changes. +fn map_art(s: &mut Session, p: &Value) -> Result { + const C: &str = "threeD.mapArt"; + const PLACING: [&str; 6] = ["symbol", "x", "y", "scaleX", "scaleY", "rotation"]; + const KEYS: [&str; 15] = + ["surface", "symbol", "x", "y", "scaleX", "scaleY", "rotation", "fit", "clearAll", "shade", "invisible", "index", "item", "ids", "id"]; + if let Some(key) = p.as_object().and_then(|m| m.keys().find(|k| !KEYS.contains(&k.as_str()))) { + return Err(bad(C, format!("unknown parameter `{key}`"))); + } + if p.get("item").is_some() && p.get("index").is_none() { + return Err(bad(C, "`item` needs `index`")); + } + let surface = match p.get("surface") { + None => None, + Some(v) => Some( + v.as_u64() + .and_then(|n| usize::try_from(n).ok()) + .filter(|n| (1..=effects::MAX_MAP_SURFACE).contains(n)) + .ok_or_else(|| bad(C, "`surface` must be a whole number from 1 to the object's surface count"))?, + ), + }; + let fit = super::super::switch_or(p, "fit", false, C)?; + let clear_all = super::super::switch_or(p, "clearAll", false, C)?; + let flag = |key: &str| -> Result> { + match p.get(key) { + None => Ok(None), + Some(_) => super::super::switch_or(p, key, false, C).map(Some), + } + }; + let (shade, invisible) = (flag("shade")?, flag("invisible")?); + match surface { + None if fit || PLACING.iter().any(|k| p.get(*k).is_some()) => { + return Err(bad(C, "`symbol`, `x`, `y`, `scaleX`, `scaleY`, `rotation` and `fit` need `surface`")); + } + None if !clear_all && shade.is_none() && invisible.is_none() => { + return Err(bad(C, "give `surface`, `clearAll`, `shade` or `invisible`")); + } + _ => {} + } + let removes = p.get("symbol").is_some_and(Value::is_null); + if removes && (fit || PLACING[1..].iter().any(|k| p.get(*k).is_some())) { + return Err(bad(C, "`symbol: null` removes the map: leave out `x`, `y`, `scaleX`, `scaleY`, `rotation` and `fit`")); + } + let d = &s.doc()?.doc; + let targets: Vec<(NodeId, Option, usize)> = if p.get("index").is_some() { + let index = index_param(p, "index", C)?; + let item = item_target(s, p, C)?; + effect_targets(s, p, item, index, C)? + } else { + let mut out = vec![]; + for id in edit_targets(s, p, C)? { + let found = d.node(id).and_then(first_mapped); + let (item, index) = found.ok_or_else(|| bad(C, format!("object {}: {}", id.0, effects::MAP_ART_NOT_TAKEN)))?; + out.push((id, item, index)); + } + out + }; + if targets.is_empty() { + return Err(bad(C, "select an object with a 3D effect")); + } + let mut edits = Vec::with_capacity(targets.len()); + for &(id, item, index) in &targets { + let n = d.node(id).ok_or(EngineError::NoNode(id))?; + let Some(effect) = n.appearance.effects_at(item).and_then(|fx| fx.get(index)).filter(|e| effects::is_three_d(&e.id)) else { + return Err(bad(C, format!("object {} needs a 3D effect at index {index}", id.0))); + }; + if !effects::takes_map_art(&effect.id) { + return Err(bad(C, format!("object {}: {}", id.0, effects::MAP_ART_NOT_TAKEN))); + } + let merged = effects::merged_params(&effect.id, &effect.params); + let mut params = merged.clone(); + if clear_all { + params[effects::MAP_ART] = json!([]); + } + if let Some(surface) = surface { + // Art that can't be built has no surfaces: the effect's own check says why. + let surfaces = match effects::map_surfaces_at(Some(d), n, item, index) { + Some(surfaces) => surfaces, + None => { + effects::validate_three_d_at_in(Some(d), n, &effect.id, &merged, (item, index)).map_err(|e| bad(C, e))?; + vec![] + } + }; + // Read before clearAll empties the list, so with clearAll the surface keeps its map. + let current = effects::surface_maps(&merged).into_iter().find(|m| m.surface == surface); + // A map kept past the surface count (the solid lost surfaces) can still be removed. + let flat = surfaces.get(surface - 1); + if flat.is_none() && !(removes && current.is_some()) { + return Err(bad(C, format!("object {}: `surface` must be from 1 to {}, the object's surface count", id.0, surfaces.len()))); + } + if removes { + params = effects::with_surface_map(¶ms, surface, None); + } else if let Some(flat) = flat { + // The values given go over the surface's map, or over a new map's defaults. + let mut given = match (¤t, p.get("symbol")) { + (Some(m), _) => m.to_value(), + (None, Some(_)) => json!({ "surface": surface }), + (None, None) => return Err(bad(C, format!("object {}: surface {surface} has no map: give `symbol`", id.0))), + }; + for key in PLACING { + if let Some(v) = p.get(key) { + given[key] = v.clone(); + } + } + let mut map = effects::SurfaceMap::from_value(&given).map_err(|e| bad(C, e))?; + // A map whose symbol was deleted keeps it while the request leaves `symbol` out; a + // symbol the request names must exist. + if !d.symbols.iter().any(|sym| sym.name == map.symbol) && (p.get("symbol").is_some() || current.is_none()) { + return Err(bad(C, format!("no symbol named `{}`", map.symbol))); + } + if fit { + // Art or a surface with no area has no size to fit: the map is centered and + // keeps its scales. + let scales = effects::graphic_bounds(d, &map.symbol).and_then(|art| map.fitting_scales(art, (flat.width, flat.height))); + let (scale_x, scale_y) = scales.unwrap_or((map.scale_x, map.scale_y)); + map = effects::SurfaceMap { x: 0.0, y: 0.0, scale_x, scale_y, ..map }; + } + params = effects::with_surface_map(¶ms, surface, Some(&map)); + } + } + for (key, value) in [(effects::MAP_SHADE, shade), (effects::MAP_INVISIBLE, invisible)] { + if let Some(on) = value { + params[key] = json!(on); + } + } + effects::validate_three_d_at_in(Some(d), n, &effect.id, ¶ms, (item, index)).map_err(|e| bad(C, e))?; + let state = |p: &Value| { + let on = |key: &str| p.get(key).and_then(Value::as_bool).unwrap_or(false); + (effects::surface_maps(p), on(effects::MAP_SHADE), on(effects::MAP_INVISIBLE)) + }; + let maps: Vec = effects::surface_maps(¶ms).iter().map(effects::SurfaceMap::to_value).collect(); + let changed = state(¶ms) != state(&merged); + edits.push((id, item, index, params, changed, maps)); + } + let first = edits.first().map(|(.., maps)| maps.clone()).unwrap_or_default(); + if !edits.iter().any(|(.., changed, _)| *changed) { + return Ok(json!({ "ids": [], "maps": first })); + } + let ids = s.edit("Map Art", |d, _| { + let mut done = vec![]; + for (id, item, index, params, changed, _) in &edits { + let Some(e) = d.node_mut(*id).and_then(|n| n.appearance.effects_mut(*item)).and_then(|fx| fx.get_mut(*index)).filter(|_| *changed) else { + continue; + }; + let mut current = effects::upgrade_params(&e.id, &e.params); + for key in [effects::MAP_ART, effects::MAP_SHADE, effects::MAP_INVISIBLE] { + if let (Some(v), Some(m)) = (params.get(key), current.as_object_mut()) { + m.insert(key.into(), v.clone()); + } + } + e.params = current; + done.push(*id); + } + Ok(done) + })?; + Ok(json!({ "ids": ids_json(&ids), "maps": first })) +} + #[cfg(test)] #[path = "graphics_tests.rs"] mod tests; + +#[cfg(test)] +#[path = "map_art_tests.rs"] +mod map_art_tests; diff --git a/crates/engine/src/cmd/effectcmd/map_art_tests.rs b/crates/engine/src/cmd/effectcmd/map_art_tests.rs new file mode 100644 index 0000000000..a63e46b429 --- /dev/null +++ b/crates/engine/src/cmd/effectcmd/map_art_tests.rs @@ -0,0 +1,258 @@ +#![allow(clippy::unwrap_used, clippy::panic)] +use serde_json::{Value, json}; +use vectorcraft_doc::NodeId; + +use crate::Session; + +/// A 100 × 100 square with `effect` seen straight on, and a 10 × 20 red rectangle beside it kept +/// as symbol "Mark" (11 × 21 with its stroke). +fn setup(effect: &str) -> (Session, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width":400,"height":400})).unwrap(); + let mark = s.execute("path.create", &json!({"d":"M300 300L310 300L310 320L300 320Z"})).unwrap()["id"].clone(); + s.execute("paint.setFill", &json!({"color":"#ff0000"})).unwrap(); + s.execute("threeD.addGraphic", &json!({"name": "Mark", "ids": [mark]})).unwrap(); + let id = NodeId(s.execute("path.create", &json!({"d":"M100 100L200 100L200 200L100 200Z"})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setFill", &json!({"color":"#338ad6"})).unwrap(); + s.execute("effect.apply", &json!({"effect":effect,"item":null,"params":{"rotationX":0.0,"rotationY":0.0,"rotationZ":0.0}})).unwrap(); + (s, id) +} + +fn params(s: &Session, id: NodeId) -> Value { + s.doc().unwrap().doc.node(id).unwrap().appearance.effects[0].params.clone() +} + +fn undo_len(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn map(surface: u64, x: f64, scale: (f64, f64), rotation: f64) -> Value { + json!({"surface": surface, "symbol": "Mark", "x": x, "y": 0.0, "scaleX": scale.0, "scaleY": scale.1, "rotation": rotation}) +} + +#[test] +fn map_art_sets_edits_and_removes_a_surfaces_map_one_undo_step_each() { + let (mut s, id) = setup("threeD.classicExtrude"); + let before = s.doc().unwrap().doc.clone(); + let history = undo_len(&s); + let r = s.execute("threeD.mapArt", &json!({"surface": 1, "symbol": "Mark", "x": 5.0, "rotation": 30.0})).unwrap(); + assert_eq!(r["ids"], json!([id.0])); + assert_eq!(r["maps"], json!([map(1, 5.0, (100.0, 100.0), 30.0)])); + assert_eq!(params(&s, id)["mapArt"], json!([map(1, 5.0, (100.0, 100.0), 30.0)])); + assert_eq!(undo_len(&s), history + 1); + // Without a symbol the surface's map keeps its own, and only the values given change. + s.execute("threeD.mapArt", &json!({"surface": 1, "scaleX": 50.0})).unwrap(); + assert_eq!(params(&s, id)["mapArt"], json!([map(1, 5.0, (50.0, 100.0), 30.0)])); + // Another surface takes a map of its own, kept in the order of the surfaces. + s.execute("threeD.mapArt", &json!({"surface": 4, "symbol": "Mark"})).unwrap(); + s.execute("threeD.mapArt", &json!({"surface": 2, "symbol": "Mark"})).unwrap(); + let surfaces: Vec = params(&s, id)["mapArt"].as_array().unwrap().iter().map(|m| m["surface"].as_u64().unwrap()).collect(); + assert_eq!(surfaces, [1, 2, 4]); + // Shade Artwork and Invisible Geometry are the effect's own flags. + s.execute("threeD.mapArt", &json!({"shade": true, "invisible": true})).unwrap(); + assert_eq!((params(&s, id)["mapShade"].clone(), params(&s, id)["mapInvisible"].clone()), (json!(true), json!(true))); + // A null symbol clears one surface, and clearAll every surface. + s.execute("threeD.mapArt", &json!({"surface": 2, "symbol": null})).unwrap(); + assert_eq!(params(&s, id)["mapArt"].as_array().unwrap().len(), 2); + let r = s.execute("threeD.mapArt", &json!({"clearAll": true})).unwrap(); + assert_eq!((r["maps"].clone(), params(&s, id)["mapArt"].clone()), (json!([]), json!([]))); + // With a surface, clearAll leaves that surface's new map alone. + s.execute("threeD.mapArt", &json!({"surface": 1, "symbol": "Mark"})).unwrap(); + s.execute("threeD.mapArt", &json!({"surface": 3, "symbol": "Mark", "clearAll": true})).unwrap(); + assert_eq!(params(&s, id)["mapArt"], json!([map(3, 0.0, (100.0, 100.0), 0.0)])); + // Without a symbol, clearAll keeps the surface's own map and edits it. + s.execute("threeD.mapArt", &json!({"surface": 1, "symbol": "Mark"})).unwrap(); + s.execute("threeD.mapArt", &json!({"surface": 3, "x": 4.0, "clearAll": true})).unwrap(); + assert_eq!(params(&s, id)["mapArt"], json!([map(3, 4.0, (100.0, 100.0), 0.0)])); + assert_eq!(undo_len(&s), history + 11); + for _ in 0..11 { + s.execute("edit.undo", &json!({})).unwrap(); + } + assert_eq!(s.doc().unwrap().doc.layers, before.layers); +} + +#[test] +fn a_map_past_the_surface_count_can_still_be_removed() { + let (mut s, id) = setup("threeD.classicExtrude"); + s.execute("threeD.mapArt", &json!({"surface": 1, "symbol": "Mark"})).unwrap(); + s.execute("threeD.mapArt", &json!({"surface": 6, "symbol": "Mark"})).unwrap(); + // With no depth the solid is a plane with fewer surfaces, and the map of surface 6 stays. + s.execute("effect.setParams", &json!({"index": 0, "item": null, "params": {"depth": 0}})).unwrap(); + let e = s.execute("threeD.mapArt", &json!({"surface": 6, "symbol": "Mark", "x": 3.0})).unwrap_err().to_string(); + assert!(e.contains("the object's surface count"), "{e}"); + s.execute("threeD.mapArt", &json!({"surface": 6, "symbol": null})).unwrap(); + assert_eq!(params(&s, id)["mapArt"], json!([map(1, 0.0, (100.0, 100.0), 0.0)])); + // A surface past the count with no map is still refused. + let e = s.execute("threeD.mapArt", &json!({"surface": 9, "symbol": null})).unwrap_err().to_string(); + assert!(e.contains("the object's surface count"), "{e}"); +} + +#[test] +fn a_map_of_a_deleted_symbol_keeps_it_only_while_the_request_leaves_symbol_out() { + let (mut s, id) = setup("threeD.classicExtrude"); + s.execute("threeD.mapArt", &json!({"surface": 1, "symbol": "Mark"})).unwrap(); + s.execute("symbol.delete", &json!({"name": "Mark"})).unwrap(); + let ids = json!([id.0]); + // Naming the deleted symbol is refused, and nothing changes. + let e = s.execute("threeD.mapArt", &json!({"ids": ids, "surface": 1, "symbol": "Mark", "x": 10.0})).unwrap_err().to_string(); + assert!(e.contains("no symbol named `Mark`"), "{e}"); + assert_eq!(params(&s, id)["mapArt"], json!([map(1, 0.0, (100.0, 100.0), 0.0)])); + // Leaving it out edits the map and keeps its symbol, and `symbol: null` removes the map. + s.execute("threeD.mapArt", &json!({"ids": ids, "surface": 1, "x": 10.0})).unwrap(); + assert_eq!(params(&s, id)["mapArt"], json!([map(1, 10.0, (100.0, 100.0), 0.0)])); + s.execute("threeD.mapArt", &json!({"ids": ids, "surface": 1, "symbol": null})).unwrap(); + assert_eq!(params(&s, id)["mapArt"], json!([])); +} + +#[test] +fn scale_to_fit_centers_the_art_and_fills_the_surface() { + let (mut s, id) = setup("threeD.classicExtrude"); + // The cap is 100 × 100 and the symbol's art 11 × 21. + s.execute("threeD.mapArt", &json!({"surface": 1, "symbol": "Mark", "x": 20.0, "y": 3.0, "fit": true})).unwrap(); + let m = ¶ms(&s, id)["mapArt"][0]; + assert_eq!((m["x"].as_f64(), m["y"].as_f64()), (Some(0.0), Some(0.0))); + assert!((m["scaleX"].as_f64().unwrap() - 100.0 / 11.0 * 100.0).abs() < 1e-6, "{m}"); + assert!((m["scaleY"].as_f64().unwrap() - 100.0 / 21.0 * 100.0).abs() < 1e-6, "{m}"); + // A side wall is 100 along the outline and as deep as the solid, 50. + s.execute("threeD.mapArt", &json!({"surface": 3, "symbol": "Mark", "fit": true})).unwrap(); + let m = ¶ms(&s, id)["mapArt"][1]; + assert!((m["scaleY"].as_f64().unwrap() - 50.0 / 21.0 * 100.0).abs() < 1e-6, "{m}"); +} + +#[test] +fn a_change_that_changes_nothing_records_no_undo_step() { + let (mut s, id) = setup("threeD.classicExtrude"); + s.execute("threeD.mapArt", &json!({"surface": 1, "symbol": "Mark"})).unwrap(); + let history = undo_len(&s); + let same = params(&s, id); + for p in [ + json!({"surface": 1, "symbol": "Mark"}), + json!({"surface": 1, "x": 0.0, "scaleX": 100.0}), + json!({"surface": 2, "symbol": null}), + json!({"shade": false}), + json!({"invisible": false}), + ] { + let r = s.execute("threeD.mapArt", &p).unwrap(); + assert_eq!(r["ids"], json!([]), "{p}"); + assert_eq!((undo_len(&s), params(&s, id)), (history, same.clone()), "{p}"); + } + // Clearing an object with no map records nothing either. + let (mut s, _) = setup("threeD.classicRevolve"); + let history = undo_len(&s); + assert_eq!(s.execute("threeD.mapArt", &json!({"clearAll": true})).unwrap()["ids"], json!([])); + assert_eq!(undo_len(&s), history); +} + +#[test] +fn bad_surfaces_symbols_and_values_are_refused() { + let (mut s, id) = setup("threeD.classicExtrude"); + let history = undo_len(&s); + let maps = params(&s, id)["mapArt"].clone(); + for (p, error) in [ + (json!({}), "give `surface`, `clearAll`, `shade` or `invisible`"), + (json!({"surface": 0, "symbol": "Mark"}), "`surface` must be a whole number"), + (json!({"surface": 1.5, "symbol": "Mark"}), "`surface` must be a whole number"), + (json!({"surface": "front", "symbol": "Mark"}), "`surface` must be a whole number"), + // The fill's solid has 6 surfaces and the stroke's, a square ring, 10: two caps and the + // four walls of each of its two outlines. + (json!({"surface": 17, "symbol": "Mark"}), "`surface` must be from 1 to 16"), + (json!({"surface": 1, "symbol": "Gone"}), "no symbol named `Gone`"), + (json!({"surface": 1, "symbol": 3}), "needs `symbol`"), + (json!({"surface": 1}), "surface 1 has no map: give `symbol`"), + (json!({"surface": 1, "symbol": "Mark", "scaleX": 0}), "scaleX must be a number from 1 to 10000"), + (json!({"surface": 1, "symbol": "Mark", "scaleY": 10001}), "scaleY must be a number from 1 to 10000"), + (json!({"surface": 1, "symbol": "Mark", "rotation": -361}), "rotation must be a number from -360 to 360"), + (json!({"surface": 1, "symbol": "Mark", "x": 1e7}), "x must be a number"), + (json!({"surface": 1, "symbol": "Mark", "y": "up"}), "y must be a number"), + (json!({"surface": 1, "symbol": "Mark", "fit": 1}), "fit"), + (json!({"surface": 1, "symbol": null, "x": 4.0}), "`symbol: null` removes the map"), + (json!({"surface": 1, "symbol": null, "rotation": 30.0}), "`symbol: null` removes the map"), + (json!({"surface": 1, "symbol": null, "fit": true}), "`symbol: null` removes the map"), + (json!({"symbol": "Mark"}), "need `surface`"), + (json!({"fit": true}), "need `surface`"), + (json!({"shade": "on"}), "shade"), + (json!({"invisible": 1}), "invisible"), + (json!({"clearAll": "yes"}), "clearAll"), + (json!({"surface": 1, "symbol": "Mark", "face": "front"}), "unknown parameter `face`"), + (json!({"surface": 1, "symbol": "Mark", "item": null}), "`item` needs `index`"), + (json!({"surface": 1, "symbol": "Mark", "index": 3}), "needs a 3D effect at index 3"), + ] { + let e = s.execute("threeD.mapArt", &p).unwrap_err().to_string(); + assert!(e.contains(error), "{p}: {e}"); + } + assert_eq!((undo_len(&s), params(&s, id)["mapArt"].clone()), (history, maps)); + // Revolve (Classic) has one surface, and the other 3D effects take no map. + let (mut s, _) = setup("threeD.classicRevolve"); + s.execute("threeD.mapArt", &json!({"surface": 1, "symbol": "Mark"})).unwrap(); + let e = s.execute("threeD.mapArt", &json!({"surface": 2, "symbol": "Mark"})).unwrap_err().to_string(); + assert!(e.contains("`surface` must be from 1 to 1"), "{e}"); + for effect in ["threeD.classicRotate", "threeD.extrude", "threeD.revolve"] { + let (mut s, _) = setup(effect); + for p in [json!({"surface": 1, "symbol": "Mark"}), json!({"surface": 1, "symbol": "Mark", "index": 0})] { + let e = s.execute("threeD.mapArt", &p).unwrap_err().to_string(); + assert!(e.contains("Map Art maps symbols onto Extrude & Bevel (Classic) and Revolve (Classic)"), "{effect}: {e}"); + } + // The effect's own parameters refuse a map too. + let e = s.execute("effect.setParams", &json!({"index": 0, "item": null, "params": {"mapArt": [{"surface": 1, "symbol": "Mark"}]}})); + assert!(e.is_err(), "{effect}"); + } +} + +#[test] +fn a_mapped_symbol_is_drawn_expanded_renamed_and_kept_in_use() { + let (mut s, id) = setup("threeD.classicExtrude"); + s.execute("threeD.mapArt", &json!({"surface": 1, "symbol": "Mark", "scaleX": 300.0})).unwrap(); + // effect.setParams takes the same maps and refuses a symbol the document does not have. + let e = s.execute("effect.setParams", &json!({"index": 0, "item": null, "params": {"mapArt": [{"surface": 1, "symbol": "Gone"}]}})); + assert!(e.unwrap_err().to_string().contains("Gone")); + // The symbol counts as used, and renaming it renames it in the map. + assert_eq!(s.execute("symbol.unused", &json!({})).unwrap()["names"], json!([])); + s.execute("symbol.options", &json!({"name": "Mark", "newName": "Logo"})).unwrap(); + assert_eq!(params(&s, id)["mapArt"][0]["symbol"], "Logo"); + // Expand Appearance keeps the mapped art: the red fill is among the expanded paths. + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("effect.expandAppearance", &json!({})).unwrap(); + let d = &s.doc().unwrap().doc; + let mut red = 0; + for l in &d.layers { + l.walk(&mut |n| { + for item in &n.appearance.items { + if let vectorcraft_doc::AppearanceItem::Fill(f) = item + && f.paint.color().is_some_and(|c| c.to_rgb()[0] > 0.9 && c.to_rgb()[1] < 0.1 && c.to_rgb()[2] < 0.1) + && n.visual_bounds().is_some_and(|b| b.x0 < 250.0) + { + red += 1; + } + } + }); + } + assert!(red > 0, "the expanded art holds the mapped symbol's red fill"); +} + +#[test] +fn pasted_into_another_document_a_map_brings_its_symbol() { + let (mut s, id) = setup("threeD.classicExtrude"); + s.execute("threeD.mapArt", &json!({"surface": 1, "symbol": "Mark"})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + // The symbol the pasted object's map names, and the size of that symbol's art. + let pasted = |s: &mut Session| { + s.execute("edit.paste", &json!({})).unwrap(); + let st = s.doc().unwrap(); + let n = st.doc.node(st.selection.objects[0]).unwrap(); + let name = n.appearance.effects[0].params["mapArt"][0]["symbol"].as_str().unwrap().to_string(); + let size = vectorcraft_render::effects::graphic_bounds(&st.doc, &name).map(|r| (r.width(), r.height())); + (name, size) + }; + // A document without the symbol gets it. + s.execute("file.new", &json!({"width":400,"height":400})).unwrap(); + assert_eq!(pasted(&mut s), ("Mark".to_string(), Some((11.0, 21.0)))); + // A document whose symbol "Mark" is other art gets the copied symbol under a free name, and + // the map names it. + s.execute("file.new", &json!({"width":400,"height":400})).unwrap(); + let other = s.execute("path.create", &json!({"d":"M0 0L50 0L50 50L0 50Z"})).unwrap()["id"].clone(); + s.execute("threeD.addGraphic", &json!({"name": "Mark", "ids": [other]})).unwrap(); + let (name, size) = pasted(&mut s); + assert_ne!(name, "Mark"); + assert_eq!(size, Some((11.0, 21.0))); +} diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index cd6ec30f0d..9f0c668b90 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -41,7 +41,7 @@ mod load; mod mesh3d; pub(crate) use load::{MAX_RASTER_ALLOC, file_clipped, image_clip, size_note}; mod heifread; -mod hpgl; +pub mod hpgl; mod jp2read; mod metafile; mod naming; @@ -84,7 +84,7 @@ pub(crate) use load::page_or_editing_data; pub(crate) use load::source; pub use load::{ Loaded, RasterImage, ReadFile, detect, file_name, load, load_with, open_bytes, open_bytes_with, open_read, open_template, raster_image, - read_for_open, texture_image, + read_for_open, read_for_open_asking, texture_image, }; pub(crate) use load::{check_files_not_lossy_overwrite, check_not_lossy_overwrite, lossy_source}; pub use load::{losses_summary, overwrite_losses}; @@ -98,7 +98,7 @@ pub use native::with_compression_pref; pub(crate) use pdfimport::opened_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 use psdlayers::{LAYER_WARNINGS as PSD_LAYER_WARNINGS, MERGED_WARNING as PSD_MERGED_WARNING, PsdInfo, info as psd_info}; pub(crate) use psdslices::over as psd_slices; pub(crate) use save::job_for; pub(crate) use save::save as save_document; diff --git a/crates/engine/src/cmd/fileio/batch.rs b/crates/engine/src/cmd/fileio/batch.rs index 5863dd4ff7..93670cefd9 100644 --- a/crates/engine/src/cmd/fileio/batch.rs +++ b/crates/engine/src/cmd/fileio/batch.rs @@ -68,6 +68,7 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { o.insert("commands".into(), Value::Array(cmds)); } if !s.previewing { + s.note_shape_drawn("command.batch", &entry); s.journal.push(("command.batch".into(), entry)); } Ok(json!({ "results": results })) diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index 0969adb5a2..a41831b200 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -9,7 +9,7 @@ pub fn specs() -> Vec { "Open Document", [], None, - "{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed, and the artboards are 36 pt apart plus that bleed on both sides; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), importSlices?: true (a PSD file's slices become user slices over its canvas, with its layers or its merged image; slices the file generated automatically are left out, and slices that can't be read are left out with a warning), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, through the profiles the document keeps after the color management policies of edit.colorSettings, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds; a blank page: its crop box; a PDF-compatible .ai: its trim box for crop; on its trim box a page shows its bleed box round the artboard and gives the document its bleed), in a row 36 pt apart (on trim boxes, plus the bleed on both sides), and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), importer?: \"plugin.\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; the color management policies of edit.colorSettings keep, take off or convert from the profiles the file is tagged with, their notes go to warnings, and a document they changed opens with unsaved changes; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning; a picture cut short by a reader limit, images and pattern brushes that can't be read, clips that can't be applied and raster operations other than a plain copy each add a warning), PICT .pct/.pic/.pict (QuickDraw versions 1 and 2, with or without the file's 512-byte header: one artboard, the picture's frame; shapes, lines and regions as paths, text as point type, bitmaps, pixel maps and QuickTime JPEG images as images; what isn't read is listed in warnings), HP-GL plot files .plt/.hpgl/.hgl/.hpg (one artboard round the art; what isn't drawn is listed in warnings), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again) and opens on the artboard its editing copy names as active. A file that no built-in format reads, by its content or its extension, opens with the installed importer plug-in that lists its extension (the one whose id sorts first, when several do): it is given the file, at most 128 MiB, and its objects become a new document whose artboard is their bounds; Save then asks for a name, and the warnings are the importer's. Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferences › Update Links: Automatically (else links.update). An SVG's files (relative links from the SVG's folder) stay linked, SVG files become art, missing ones a placeholder in their box (a warning and missingLinks). An SVG's variable data (SVG Options › Include Variable Data, a variableSets element) gives the document its text variables and data sets, each text variable bound to the type object its docRef names, unless the SVG restores the native document; variable data variable.loadLibrary would refuse is left out with a warning", + "{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed, and the artboards are 36 pt apart plus that bleed on both sides; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), importSlices?: true (a PSD file's slices become user slices over its canvas, with its layers or its merged image; slices the file generated automatically are left out, and slices that can't be read are left out with a warning), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, through the profiles the document keeps after the color management policies of edit.colorSettings, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds; a blank page: its crop box; a PDF-compatible .ai: its trim box for crop; on its trim box a page shows its bleed box round the artboard and gives the document its bleed), in a row 36 pt apart (on trim boxes, plus the bleed on both sides), and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), profileChoice?: \"useEmbedded\"|\"convert\"|\"discard\" (the profile of the document's color mode is not the working space: keep it, convert that model's colors into the working space and take it off, or take it off and keep the numbers) | \"leave\"|\"assignWorking\"|\"assign\" (the document has no profile of its color mode: leave it untagged, tag it with the working space, or with assignProfile?: a profile of that model) (default: what the model's policy of edit.colorSettings does; a choice for the other case, or for a document tagged with the working space, is not used; the reply's profileChoice gives {issue: mismatch|missing, model, choice} when one was given for the document's question: it names the choice, not what it did, so \"convert\" from a profile that is not available keeps the profile and a warning says the colors were not converted; the desktop app asks for it when edit.colorSettings' askMismatchOpen or askMissingOpen is on, document.open never asks), importer?: \"plugin.\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, profileChoice?, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; the color management policies of edit.colorSettings keep, take off or convert from the profiles the file is tagged with, their notes go to warnings, and a document they changed opens with unsaved changes; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning; a picture cut short by a reader limit, images and pattern brushes that can't be read, clips that can't be applied and raster operations other than a plain copy each add a warning), PICT .pct/.pic/.pict (QuickDraw versions 1 and 2, with or without the file's 512-byte header: one artboard, the picture's frame; shapes, lines and regions as paths, text as point type, bitmaps, pixel maps and QuickTime JPEG images as images; what isn't read is listed in warnings), HP-GL plot files .plt/.hpgl/.hgl/.hpg (one artboard round the art; what isn't drawn is listed in warnings), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again) and opens on the artboard its editing copy names as active. A file that no built-in format reads, by its content or its extension, opens with the installed importer plug-in that lists its extension (the one whose id sorts first, when several do): it is given the file, at most 128 MiB, and its objects become a new document whose artboard is their bounds; Save then asks for a name, and the warnings are the importer's. Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferences › Update Links: Automatically (else links.update). An SVG's files (relative links from the SVG's folder) stay linked, SVG files become art, missing ones a placeholder in their box (a warning and missingLinks). An SVG's variable data (SVG Options › Include Variable Data, a variableSets element) gives the document its text variables and data sets, each text variable bound to the type object its docRef names, unless the SVG restores the native document; variable data variable.loadLibrary would refuse is left out with a warning", always, load::open ), diff --git a/crates/engine/src/cmd/fileio/encode.rs b/crates/engine/src/cmd/fileio/encode.rs index 8b5cd9fe6f..1ecb41290e 100644 --- a/crates/engine/src/cmd/fileio/encode.rs +++ b/crates/engine/src/cmd/fileio/encode.rs @@ -878,7 +878,7 @@ fn without_nodes(n: &Arc, left_out: &dyn Fn(&Node) -> bool, changed: Optio /// absent; an error when it is not four finite numbers with a positive size, when the format isn't /// a raster one, or when it comes with an artboard choice (`rect` is the area, so those would /// contradict it). The image size limits are checked with the scale, as for an artboard. -fn page_rect(f: &Format, p: &Value) -> Result> { +pub(super) fn page_rect(f: &Format, p: &Value) -> Result> { let v = match p.get("rect") { None | Some(Value::Null) => return Ok(None), Some(v) => v, diff --git a/crates/engine/src/cmd/fileio/hpgl.rs b/crates/engine/src/cmd/fileio/hpgl.rs index 1baac844e6..bf98457771 100644 --- a/crates/engine/src/cmd/fileio/hpgl.rs +++ b/crates/engine/src/cmd/fileio/hpgl.rs @@ -6,6 +6,7 @@ use serde_json::Value; use vectorcraft_cad::hpgl::write::{DEFAULT_TOLERANCE, MAX_PENS, TOLERANCE_RANGE}; use vectorcraft_cad::hpgl::{HpglOptions, Origin, Version}; use vectorcraft_doc::Document; +use vectorcraft_geom::Rect; use super::super::{Result, bad, number_or, switch_or, text_param}; use super::{ArtboardPick, Encoded, FormatOption}; @@ -92,10 +93,58 @@ fn hex(v: &Value) -> Option<[u8; 3]> { Some([byte(0)?, byte(2)?, byte(4)?]) } -/// Encode `doc` as HP-GL: a plot of the chosen artboard (default the first), or with -/// `use_artboards` one plot per chosen artboard (default all), with one pen numbering for them all. -pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option) -> Result { - let opts = parse(p)?; +/// Check the HP-GL options and the artboard choice in `p` for an export of `doc`, as the export +/// reads them, without exporting (dialogs keep themselves open on an error). +pub fn check(doc: &Document, p: &Value) -> std::result::Result<(), String> { + let run = || -> Result<()> { + parse(p)?; + with_plotted(doc, p, |_, _| Ok(())) + }; + run().map_err(|e| e.to_string()) +} + +/// The pen table an export of `doc` with the options and artboard choice in `p`, and no `pens`, +/// uses: pen 1's color first, as `#rrggbb` colors. Empty when nothing is plotted; an error when +/// the options or the artboard choice are refused. +pub fn automatic_pens(doc: &Document, p: &Value) -> std::result::Result, String> { + let run = || -> Result> { + let mut q = p.clone(); + if let Some(o) = q.as_object_mut() { + o.remove("pens"); + } + // The order the paths are drawn in doesn't change which pen a color gets. + let opts = HpglOptions { sort: false, inside_first: false, ..parse(&q)? }; + with_plotted(doc, &q, |doc, regions| { + let plots = vectorcraft_cad::hpgl::export_regions(doc, &opts, ®ions).map_err(|e| bad(C, e))?; + Ok(plots.first().map(|o| o.pens.clone()).unwrap_or_default()) + }) + }; + let pens = run().map_err(|e| e.to_string())?; + Ok(pens.iter().map(|[r, g, b]| format!("#{r:02x}{g:02x}{b:02x}")).collect()) +} + +/// Run `f` on the document an export of `doc` with `p` plots and the regions of its plots: with +/// `useArtboards: false`, a copy of `doc` whose one artboard is the bounds of the visible art. +/// Like the export, it refuses `rect`, leaves out an opacity-mask or symbol editing layer, and +/// measures the bounds without the art a plot draws nothing for. +fn with_plotted(doc: &Document, p: &Value, f: impl FnOnce(&Document, Vec) -> Result) -> Result { + let format = super::format("hpgl").ok_or_else(|| bad(C, "no HP-GL format"))?; + super::encode::page_rect(format, p)?; + let doc = &*doc.without_edit_modes(); + let use_artboards = super::encode::use_artboards(C, p)?; + if use_artboards == Some(false) + && let Some((art, q)) = super::encode::art_page(C, doc, p, |n| vectorcraft_cad::hpgl::write::plots_nothing(doc, n))? + { + let (_, regions) = boards(&art, &q, None)?; + return f(&art, regions); + } + let (_, regions) = boards(doc, p, use_artboards)?; + f(doc, regions) +} + +/// The artboards a plot of `doc` covers and their regions: the chosen artboard (default the +/// first), or with `use_artboards` each chosen one (default all). +fn boards(doc: &Document, p: &Value, use_artboards: Option) -> Result<(Vec, Vec)> { let f = super::format("hpgl").ok_or_else(|| bad(C, "no HP-GL format"))?; let pick: ArtboardPick = super::encode::options(f, p)?; let n = doc.artboards.len(); @@ -103,10 +152,25 @@ pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option) -> 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))?], }; + if boards.is_empty() { + return Err(bad(C, "the document has no artboard")); + } let regions = boards .iter() .map(|&b| doc.artboards.get(b).map(|a| a.rect).ok_or_else(|| bad(C, format!("no artboard {}", b + 1)))) .collect::>>()?; + // The writer's own region check, so a dialog's check refuses what the writer refuses. + for r in ®ions { + vectorcraft_cad::hpgl::write::check_region(*r).map_err(|e| bad(C, e))?; + } + Ok((boards, regions)) +} + +/// Encode `doc` as HP-GL: a plot of the chosen artboard (default the first), or with +/// `use_artboards` one plot per chosen artboard (default all), with one pen numbering for them all. +pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option) -> Result { + let opts = parse(p)?; + let (boards, regions) = boards(doc, p, use_artboards)?; let plots = vectorcraft_cad::hpgl::export_regions(doc, &opts, ®ions).map_err(|e| bad(C, e))?; let mut enc = Encoded::default(); for (b, out) in boards.into_iter().zip(plots) { @@ -118,9 +182,6 @@ pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option) -> } enc.add_setting_notes(out.setting_notes); } - if enc.files.is_empty() { - return Err(bad(C, "the document has no artboard")); - } let regions: Vec = enc.files.iter().filter_map(|(b, _)| b.and_then(|b| doc.artboards.get(b))).map(|a| a.rect).collect(); enc.warnings.extend(crate::cmd::fonts::export_overflow_warning(doc, &doc.layers, Some(®ions))); Ok(enc) diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index 8249fe6b71..d63f296bdc 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -686,6 +686,29 @@ pub struct ReadFile { links: Resolved, /// Whether the color management policies changed the document ([`apply_policies`]). policy_changed: bool, + /// The answer to the document's profile question (`profileChoice`, or the app's prompt). + choice: Option, + /// What opening still has to do while the app asks about the profile ([`ReadFile::question`]): + /// the policies, the color mode, the linked files and the type are left for + /// [`ReadFile::answer`] or [`open_read`]. + rest: Option, + /// The answer that was used and the question it answered (`document.open`'s `profileChoice` + /// reply). + answered: Option, + /// The profile question as it was last asked ([`ReadFile::ask`]): an answer is taken only while + /// the question is still the same. + asked: Option, + /// Update Links and the low-resolution EPS proxy setting, while the linked files and the type + /// are left to do after the answer ([`ReadFile::finish_read`]). + links_left: Option<(bool, bool)>, +} + +/// The part of [`read_for_open`] a file waiting for a profile answer has left to do. +struct Rest { + update_links: bool, + low_res_proxy_eps: bool, + /// The color mode `colorMode` asks for, converted after the policies. + color_mode: Option, } /// Edit › Color Settings: the color management policies keep, take off or convert from the @@ -714,36 +737,145 @@ impl ReadFile { /// reads (`importer` in `p`, or an extension only an importer lists) is read by it /// ([`super::importer`]). pub fn read_for_open(name: &str, bytes: &[u8], path: Option, p: &Value, update_links: bool, low_res_proxy_eps: bool) -> Result { + read_for_open_asking(name, bytes, path, p, update_links, low_res_proxy_eps, false) +} + +/// [`read_for_open`]; with `ask` (the desktop app's File › Open), a document whose profile +/// question ([`ReadFile::question`]) Edit › Color Settings asks, and that `p` gives no +/// `profileChoice` for, stops after it is decoded: the app asks, and [`ReadFile::answer`] (or +/// [`open_read`], with the policy's choice) does the rest. +pub fn read_for_open_asking( + name: &str, + bytes: &[u8], + path: Option, + p: &Value, + update_links: bool, + low_res_proxy_eps: bool, + ask: bool, +) -> Result { let opts = LoadOptions::from_params("document.open", p)?; - let (mut loaded, policy_changed) = if opts.link_pages { - let mut loaded = linked_pages(name, bytes, path.as_deref(), &opts)?; - let changed = apply_policies(&mut loaded); - (loaded, changed) + let choice = crate::cmd::colormgmt::ProfileChoice::param(p, "document.open")?; + let (loaded, color_mode) = if opts.link_pages { + (linked_pages(name, bytes, path.as_deref(), &opts)?, None) } else { match super::importer::pick(name, bytes, p)? { - Some(plugin) => { - let mut loaded = super::importer::load(name, bytes, &plugin, p)?; - let changed = apply_policies(&mut loaded); - (loaded, changed) - } - None => { - // The color mode `p` asks for converts the colors after the policies did, through - // the profiles the document keeps. - let mut loaded = load_with(name, bytes, &LoadOptions { color_mode: None, ..opts.clone() })?; - let changed = apply_policies(&mut loaded); - if let Some(mode) = opts.color_mode.filter(|m| *m != loaded.doc.color_mode) { - let doc = &mut loaded.doc; - vectorcraft_color::cms::with_active(super::super::colormgmt::doc_cms(doc), || { - super::super::colormgmt::set_color_mode(doc, mode, true, None, opts.grays); - }); - } - (loaded, changed) - } + Some(plugin) => (super::importer::load(name, bytes, &plugin, p)?, None), + // The color mode `p` asks for converts the colors after the policies did, through the + // profiles the document keeps. + None => (load_with(name, bytes, &LoadOptions { color_mode: None, ..opts.clone() })?, opts.color_mode), } }; - let links = crate::cmd::links::resolve(&mut loaded.doc, crate::cmd::links::LinkBase::file(path.as_deref()), update_links, low_res_proxy_eps); - Session::refresh_text_bounds(&mut loaded.doc); - Ok(ReadFile { loaded, opts, path, links, policy_changed }) + let mut file = ReadFile { + loaded, + opts, + path, + links: Resolved::default(), + policy_changed: false, + choice, + rest: Some(Rest { update_links, low_res_proxy_eps, color_mode }), + answered: None, + asked: None, + links_left: None, + }; + if ask && file.choice.is_none() && file.ask().is_some() { + return Ok(file); + } + file.finish_read()?; + Ok(file) +} + +impl ReadFile { + /// The file's name, for a prompt. + pub fn name(&self) -> String { + self.path.as_deref().map(file_name).unwrap_or_else(|| self.loaded.doc.title.clone()) + } + + /// The profile question Edit › Color Settings asks about this file before it opens (its Ask + /// When Opening box of that kind is on), while the file waits for the answer + /// ([`read_for_open_asking`]); none once it is answered or read through. + pub fn question(&self) -> Option { + self.rest.as_ref()?; + let st = vectorcraft_color::cms::working_settings(); + crate::cmd::colormgmt::ProfileQuestion::of(&self.loaded.doc, &st).filter(|q| q.asked(&st)) + } + + /// [`Self::question`], kept as the question asked: [`Self::answer`] takes an answer only while + /// the question is still the same. The app calls it when it shows the question. + pub fn ask(&mut self) -> Option { + self.asked = self.question(); + self.asked.clone() + } + + /// Answer the profile question with `choice` and apply it: the policies (the answer in place of + /// the one of the document's color mode) and the color mode. The linked files and the type are + /// left for [`Self::finish_read`] or [`open_read`]. An error leaves the file waiting: a profile + /// to assign that is not one of that model, or Color Settings changed since the question was + /// asked ([`Self::ask`]) so that the question, its model, the profile it is about or the working + /// space differ. + pub fn answer(&mut self, choice: crate::cmd::colormgmt::ProfileChoice) -> Result<()> { + if let Some(asked) = &self.asked + && self.rest.is_some() + { + let now = crate::cmd::colormgmt::ProfileQuestion::of(&self.loaded.doc, &vectorcraft_color::cms::working_settings()); + let key = |q: &crate::cmd::colormgmt::ProfileQuestion| (q.issue, q.model, q.profile.clone(), q.working.clone()); + if now.as_ref().map(key) != Some(key(asked)) { + return Err(bad("document.open", "the profile question changed since it was asked: answer the question it asks now")); + } + } + let before = self.choice.replace(choice); + let r = self.apply_answer(); + if r.is_err() { + self.choice = before; + } + r + } + + /// The rest of [`read_for_open_asking`], once: the color management policies with the profile + /// answer (or as the policy says without one), the color mode `colorMode` asks for, the linked + /// files and the type. The app runs it off the UI thread once the question is answered. + pub fn finish_read(&mut self) -> Result<()> { + self.apply_answer()?; + self.finish_links(); + Ok(()) + } + + /// Read the linked files and lay out the type of a file whose profile answer is applied + /// ([`Self::answer`]), once. A file still waiting for its answer is left as it is. + fn finish_links(&mut self) { + let Some((update_links, low_res_proxy_eps)) = self.links_left.take() else { return }; + let base = crate::cmd::links::LinkBase::file(self.path.as_deref()); + self.links = crate::cmd::links::resolve(&mut self.loaded.doc, base, update_links, low_res_proxy_eps); + Session::refresh_text_bounds(&mut self.loaded.doc); + } + + /// The policies with the profile answer and the color mode `colorMode` asks for, once; the + /// linked files and the type are left for [`Self::finish_read`]. + fn apply_answer(&mut self) -> Result<()> { + if self.rest.is_none() { + return Ok(()); + } + // The question the answer was given to, for the reply's `profileChoice`. + let question = crate::cmd::colormgmt::ProfileQuestion::of(&self.loaded.doc, &vectorcraft_color::cms::working_settings()); + let answered = match (&self.choice, &question) { + (Some(c), Some(q)) if c.issue() == q.issue => Some(json!({ "issue": q.issue.id(), "model": q.to_json()["model"], "choice": c.id() })), + _ => None, + }; + // A failure leaves the file waiting, unchanged. + let (notes, changed) = crate::cmd::colormgmt::apply_open_policies_choosing(&mut self.loaded.doc, self.choice.as_ref())?; + let Some(rest) = self.rest.take() else { return Ok(()) }; + self.answered = answered; + self.loaded.warnings.extend(notes); + self.policy_changed = changed; + if let Some(mode) = rest.color_mode.filter(|m| *m != self.loaded.doc.color_mode) { + let doc = &mut self.loaded.doc; + let grays = self.opts.grays; + vectorcraft_color::cms::with_active(super::super::colormgmt::doc_cms(doc), || { + super::super::colormgmt::set_color_mode(doc, mode, true, None, grays); + }); + } + self.links_left = Some((rest.update_links, rest.low_res_proxy_eps)); + Ok(()) + } } /// The PDF `name` (`bytes`, read from `path`) opened with `linkPages`: its pages as placed documents @@ -757,8 +889,15 @@ fn linked_pages(name: &str, bytes: &[u8], path: Option<&str>, opts: &LoadOptions /// The second half of [`open_bytes_with`]: open a file [`read_for_open`] read as the new active /// document → `document.open`'s result. -pub fn open_read(s: &mut Session, file: ReadFile) -> Result { - open_loaded(s, file.loaded, file.links, file.path, &file.opts, false, file.policy_changed) +/// A file still waiting for its profile answer ([`ReadFile::question`]) opens as its policy says. +pub fn open_read(s: &mut Session, mut file: ReadFile) -> Result { + file.finish_read()?; + let answered = file.answered.take(); + let mut r = open_loaded(s, file.loaded, file.links, file.path, &file.opts, false, file.policy_changed)?; + if let Some(a) = answered { + r["profileChoice"] = a; + } + Ok(r) } /// File → New from Template: any readable file (at `path`, if it is one: its links are looked for diff --git a/crates/engine/src/cmd/fileio/pdf.rs b/crates/engine/src/cmd/fileio/pdf.rs index 651ef89e19..c0bb942150 100644 --- a/crates/engine/src/cmd/fileio/pdf.rs +++ b/crates/engine/src/cmd/fileio/pdf.rs @@ -636,8 +636,8 @@ pub const DEFAULT_FLATTENER: &str = "High Resolution"; /// `doc` with its transparency flattened for a PDF 1.3 file (asked for, or PDF/X-1a and PDF/X-3, /// whose files have none), with `flattenerPreset` (default High Resolution) and `p`'s `flattener` /// options over it; images with see-through pixels and colorized images, including those in -/// pattern tiles, count as transparency. Rasterized areas are clipped to their regions, and -/// discarded overprints are dropped. Layers the pages leave out (non-printing ones, unless asked +/// pattern tiles, count as transparency. Rasterized areas are clipped to their regions and keep no +/// alpha, and discarded overprints are dropped. Layers the pages leave out (non-printing ones, unless asked /// for) are left out of the flattening, hidden. → the document to write (`None`: `doc` as it is) /// and whether its transparency was flattened. fn flatten_for(cmd: &str, doc: &Document, set: &PdfSettings, p: &Value) -> Result<(Option, Option)> { @@ -655,8 +655,9 @@ fn flatten_for(cmd: &str, doc: &Document, set: &PdfSettings, p: &Value) -> Resul o.preserve_overprints &= set.advanced.overprint == Overprint::Preserve; o.no_transparency = Some(see_through_images(doc)); // Without soft masks a rasterized area can't be a rectangle with see-through pixels around - // its art: it is clipped to its regions (opaque inside them). + // its art: it is clipped to its regions (opaque inside them). Rasters keep no alpha either. o.clip_complex_regions = true; + o.preserve_alpha = false; Ok(match flatten_document(shown.as_ref().unwrap_or(doc), &o)? { Some(flat) => (Some(flat), Some(o)), None => (shown, None), diff --git a/crates/engine/src/cmd/fileio/psdlayers.rs b/crates/engine/src/cmd/fileio/psdlayers.rs index ea5cf63aa2..cbfaa434d5 100644 --- a/crates/engine/src/cmd/fileio/psdlayers.rs +++ b/crates/engine/src/cmd/fileio/psdlayers.rs @@ -684,57 +684,64 @@ struct Counts { clipped_out: usize, } -/// `n` things: "1 layer was", "2 layers were". -fn count(n: usize, one: &str, many: &str) -> String { - if n == 1 { format!("1 {one} was") } else { format!("{n} {many} were") } +/// Adds the warning for `n` things to `out`: `one` when `n` is 1, `many` with the count in place +/// of `{n}` when it is more, none when it is 0. Each form is a whole sentence, the key of its own +/// catalog row. +fn note(out: &mut Vec, n: usize, (one, many): (&str, &str)) { + match n { + 0 => {} + 1 => out.push(one.to_string()), + n => out.push(many.replace("{n}", &n.to_string())), + } } +/// The layer warnings in English, the form for one layer and the form for more, in the order a +/// file's warnings list them. +pub const LAYER_WARNINGS: [(&str, &str); 10] = [ + ("1 type layer came in as pixels: the text isn't editable", "{n} type layers came in as pixels: the text isn't editable"), + ("1 adjustment layer was not applied", "{n} adjustment layers were not applied"), + ( + "1 fill layer was not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels)", + "{n} fill layers were not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels)", + ), + ("the layer effects of 1 layer weren't drawn", "the layer effects of {n} layers weren't drawn"), + ("the vector masks of 1 layer weren't applied", "the vector masks of {n} layers weren't applied"), + ("the knockout of 1 layer wasn't applied", "the knockout of {n} layers wasn't applied"), + ( + "1 layer was left out (hidden layers and the layers clipped to them)", + "{n} layers were left out (hidden layers and the layers clipped to them)", + ), + ("1 layer clipped to a fill layer that wasn't drawn was left out", "{n} layers clipped to fill layers that weren't drawn were left out"), + ( + "1 layer in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed", + "{n} layers in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed", + ), + ( + "1 layer clipped to the layer below came in unclipped: the merge needs more memory than allowed", + "{n} layers clipped to the layer below came in unclipped: the merge needs more memory than allowed", + ), +]; + +/// The warning for layers merged with the layers below them, `{modes}` the blend modes' names. +pub const MERGED_WARNING: &str = "layers in blend modes VectorCraft doesn't have ({modes}) were merged with the layers below them"; + impl Notes { fn warnings(self) -> Vec { + let [types, adjustments, fills, effects, masks, knockouts, hidden, clipped_out, unmerged, unclipped] = LAYER_WARNINGS; let mut out = vec![]; - if self.types > 0 { - let n = if self.types == 1 { "1 type layer".to_string() } else { format!("{} type layers", self.types) }; - out.push(format!("{n} came in as pixels: the text isn't editable")); - } - if self.adjustments > 0 { - out.push(format!("{} not applied", count(self.adjustments, "adjustment layer", "adjustment layers"))); - } - if self.fills > 0 { - out.push(format!( - "{} not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels)", - count(self.fills, "fill layer", "fill layers") - )); - } - let layers = |n: usize| if n == 1 { "1 layer".to_string() } else { format!("{n} layers") }; - if self.effects > 0 { - out.push(format!("the layer effects of {} weren't drawn", layers(self.effects))); - } - if self.vector_masks > 0 { - out.push(format!("the vector masks of {} weren't applied", layers(self.vector_masks))); - } - if self.knockouts > 0 { - out.push(format!("the knockout of {} wasn't applied", layers(self.knockouts))); - } - if self.hidden > 0 { - out.push(format!("{} left out (hidden layers and the layers clipped to them)", count(self.hidden, "layer", "layers"))); - } - if self.clipped_out == 1 { - out.push("1 layer clipped to a fill layer that wasn't drawn was left out".into()); - } else if self.clipped_out > 1 { - out.push(format!("{} layers clipped to fill layers that weren't drawn were left out", self.clipped_out)); - } + note(&mut out, self.types, types); + note(&mut out, self.adjustments, adjustments); + note(&mut out, self.fills, fills); + note(&mut out, self.effects, effects); + note(&mut out, self.vector_masks, masks); + note(&mut out, self.knockouts, knockouts); + note(&mut out, self.hidden, hidden); + note(&mut out, self.clipped_out, clipped_out); if !self.merged.is_empty() { - out.push(format!("layers in blend modes VectorCraft doesn't have ({}) were merged with the layers below them", self.merged.join(", "))); - } - if self.unmerged > 0 { - out.push(format!( - "{} in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed", - layers(self.unmerged) - )); - } - if self.unclipped > 0 { - out.push(format!("{} clipped to the layer below came in unclipped: the merge needs more memory than allowed", layers(self.unclipped))); + out.push(MERGED_WARNING.replace("{modes}", &self.merged.join(", "))); } + note(&mut out, self.unmerged, unmerged); + note(&mut out, self.unclipped, unclipped); out } diff --git a/crates/engine/src/cmd/fileio/psdslices.rs b/crates/engine/src/cmd/fileio/psdslices.rs index cf5506ff3b..974b48ec2c 100644 --- a/crates/engine/src/cmd/fileio/psdslices.rs +++ b/crates/engine/src/cmd/fileio/psdslices.rs @@ -175,8 +175,9 @@ fn skip_record(r: &mut Reader<'_>) -> Result<(), String> { /// Versions 7 and 8: the descriptor's `slices` list, each slice an object. fn from_descriptor(d: &[(String, Value)]) -> Result, String> { let Some(Value::List(list)) = field(d, "slices") else { return Err("the slices' descriptor has no list of slices".into()) }; - if list.len() > MAX_SLICES { - return Err(format!("the file has {} slices, more than the {MAX_SLICES} read", list.len())); + let count = list.len(); + if count > MAX_SLICES { + return Err(format!("the file has {count} slices, more than the {MAX_SLICES} read")); } let mut out = vec![]; for s in list { diff --git a/crates/engine/src/cmd/fileio/tests_hpgl.rs b/crates/engine/src/cmd/fileio/tests_hpgl.rs index 8714072257..9a74b8513b 100644 --- a/crates/engine/src/cmd/fileio/tests_hpgl.rs +++ b/crates/engine/src/cmd/fileio/tests_hpgl.rs @@ -534,6 +534,104 @@ fn export_options_are_checked() { let p = json!({"format": "hpgl", "origin": "CENTER", "pens": ["#ff0000", "#000000"], "curveTolerance": 10, "sortPaths": true}); let plot = String::from_utf8(bytes(&s.execute("document.export", &p).unwrap())).unwrap(); assert_eq!(plot, "IN;PU;SP2;PU-141,141;PD-564,141,-564,564,-141,564,-141,141;PU;SP0;"); + // The check a dialog runs refuses the same options, and passes the given ones. + let doc = s.doc().unwrap().doc.clone(); + assert!(hpgl::check(&doc, &json!({"pens": ["#ff0000", "red"]})).unwrap_err().contains("`pens`")); + assert!(hpgl::check(&doc, &json!({"curveTolerance": 11})).unwrap_err().contains("`curveTolerance`")); + assert_eq!(hpgl::check(&doc, &p), Ok(())); + // It checks the artboard choice as the export does: an artboard or range past the document's, + // a `useArtboards` that isn't true or false, and the art's bounds when no art shows. + let mut blank = Session::new(); + blank.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let blank_doc = blank.doc().unwrap().doc.clone(); + for (on_blank, p) in [ + (false, json!({"format": "hpgl", "artboard": 2})), + (false, json!({"format": "hpgl", "useArtboards": true, "range": "1-3"})), + (false, json!({"format": "hpgl", "artboards": [0, 1]})), + (false, json!({"format": "hpgl", "useArtboards": "yes"})), + (true, json!({"format": "hpgl", "useArtboards": false})), + ] { + let (session, d) = if on_blank { (&mut blank, &blank_doc) } else { (&mut s, &doc) }; + assert!(hpgl::check(d, &p).is_err(), "{p}"); + assert!(session.execute("document.export", &p).is_err(), "{p}"); + } + // An artboard with no width is refused before the writer refuses it. + let mut flat = vectorcraft_doc::Document::clone(&doc); + flat.artboards[1].rect = vectorcraft_geom::Rect::new(200.0, 0.0, 200.0, 100.0); + assert_eq!(hpgl::check(&flat, &json!({"artboard": 1})).unwrap_err(), hpgl::check(&flat, &json!({"useArtboards": true})).unwrap_err()); + assert!(hpgl::check(&flat, &json!({"artboard": 1})).unwrap_err().contains("the export region is empty")); + assert_eq!(hpgl::check(&flat, &json!({})), Ok(())); + // A document with no artboard has nothing to plot on one, or on each. + flat.artboards.clear(); + for p in [json!({}), json!({"useArtboards": true})] { + assert!(hpgl::check(&flat, &p).unwrap_err().contains("the document has no artboard"), "{p}"); + } + // An area of the page is a raster export's option: the export refuses it, and so does the check. + let rect = json!({"format": "hpgl", "rect": [0, 0, 10, 10]}); + assert!(s.execute("document.export", &rect).is_err()); + assert!(hpgl::check(&doc, &rect).unwrap_err().contains("rect applies to raster formats")); + assert_eq!(hpgl::check(&doc, &json!({"useArtboards": true, "range": "2"})), Ok(())); + assert_eq!(hpgl::check(&doc, &json!({"useArtboards": false})), Ok(())); +} + +/// The pens an export without a pen table uses: one per color the plotted art draws in, in the +/// order it first draws in each, over the artboards or the art's bounds the export plots. +#[test] +fn automatic_pens_list_the_plotted_art_s_colors_in_pen_order() { + let s = two_boards(); + let doc = &s.doc().unwrap().doc; + let pens = |p: Value| hpgl::automatic_pens(doc, &p).unwrap(); + assert_eq!(pens(json!({})), ["#000000"], "the first artboard"); + assert_eq!(pens(json!({"artboard": 1})), ["#ff0000"]); + assert_eq!(pens(json!({"useArtboards": true})), ["#000000", "#ff0000"], "one numbering for every file"); + assert_eq!(pens(json!({"useArtboards": false})), ["#000000", "#ff0000"], "the art's bounds"); + // The pens given and the path order are not the export's own pens. + assert_eq!(pens(json!({"useArtboards": true, "pens": ["#00ff00"], "sortPaths": true})), ["#000000", "#ff0000"]); + // A refused artboard choice or option is an error, not an empty table. + assert!(hpgl::automatic_pens(doc, &json!({"artboard": 5})).is_err()); + assert!(hpgl::automatic_pens(doc, &json!({"curveTolerance": 20})).unwrap_err().contains("`curveTolerance`")); + // So is an area of the page, which the export and the check refuse for HP-GL. + assert!(hpgl::automatic_pens(doc, &json!({"rect": [0, 0, 10, 10]})).unwrap_err().contains("rect applies to raster formats")); + + // Art outside every artboard is plotted only with the art's bounds. + let mut off = Session::new(); + off.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + off.execute("paint.setFill", &json!({"none": true})).unwrap(); + off.execute("paint.setStroke", &json!({"color": "#0000ff"})).unwrap(); + off.execute("shape.rectangle", &json!({"x": 500, "y": 500, "width": 30, "height": 30})).unwrap(); + let doc = &off.doc().unwrap().doc; + assert_eq!(hpgl::automatic_pens(doc, &json!({})), Ok(vec![])); + assert_eq!(hpgl::automatic_pens(doc, &json!({"useArtboards": false})), Ok(vec!["#0000ff".to_string()])); +} + +/// A placed document opened with only its preview is plotted with its file's art (the plot reads +/// the file), so the check and the pens of a dialog measure that art as the export does. +#[test] +fn a_placed_document_s_pens_are_those_of_its_file_s_art() { + use crate::tests_links::{Folder, open, save, session, write}; + let dir = Folder::new("hpgl-placed"); + let src = dir.file("logo.vectorcraft"); + let mut d = vectorcraft_doc::Document::new(100.0, 50.0); + let layer = d.layers[0].id; + let id = d.alloc_id(); + let red = vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb8(255, 0, 0)); + let look = vectorcraft_doc::Appearance::basic(red, vectorcraft_color::Paint::None, 0.0); + let rect = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 100.0, 50.0)); + d.insert(Some(layer), 0, vectorcraft_doc::Node::path(id, rect, look)).unwrap(); + write(&src, &vectorcraft_format::save_file(&d)); + let mut s = session(); + s.execute("file.place", &json!({"path": src, "at": [200, 150]})).unwrap(); + let poster = dir.file("poster.vectorcraft"); + save(&mut s, &poster); + open(&mut s, &poster); + let doc = &s.doc().unwrap().doc; + assert!(doc.images.values().any(vectorcraft_doc::ImageBlob::is_proxy), "opened with the preview only"); + for p in [json!({}), json!({"useArtboards": false})] { + assert_eq!(hpgl::automatic_pens(doc, &p), Ok(vec!["#ff0000".to_string()]), "{p}"); + assert_eq!(hpgl::check(doc, &p), Ok(()), "{p}"); + } + let plot = String::from_utf8(bytes(&s.execute("document.export", &json!({"format": "hpgl"})).unwrap())).unwrap(); + assert!(plot.contains("SP1;") && plot.contains("PD"), "{plot}"); } /// `insideFirst` draws the square inside the other one first, though it was made last. diff --git a/crates/engine/src/cmd/fileio/tests_pdf13.rs b/crates/engine/src/cmd/fileio/tests_pdf13.rs index 99daa023a5..7c0aa4a74b 100644 --- a/crates/engine/src/cmd/fileio/tests_pdf13.rs +++ b/crates/engine/src/cmd/fileio/tests_pdf13.rs @@ -166,6 +166,14 @@ fn the_flattener_preset_and_options_apply() { assert!(!transparency(&kept).is_empty() && !warnings.iter().any(|w| w.contains("flattened"))); } +#[test] +fn pdf_1_3_files_flatten_without_alpha_whatever_the_options() { + let mut s = session(); + let p = json!({"compatibility": "1.3", "preserveEditing": false, "flattener": {"balance": 0, "preserveAlpha": true}}); + let (pdf, _) = export(&mut s, p); + assert!(pdf.starts_with(b"%PDF-1.3") && transparency(&pdf).is_empty()); +} + #[test] fn pdf_1_3_files_are_encrypted_with_40_bit_rc4_and_can_be_linearised() { let mut s = session(); diff --git a/crates/engine/src/cmd/fileio/tests_svg.rs b/crates/engine/src/cmd/fileio/tests_svg.rs index c7716940a1..7b5545ddca 100644 --- a/crates/engine/src/cmd/fileio/tests_svg.rs +++ b/crates/engine/src/cmd/fileio/tests_svg.rs @@ -437,3 +437,48 @@ fn svg_darkness_uses_rendered_shadow_in_non_srgb_working_space() { assert!(a.iter().zip(b).all(|(a, b)| a.abs_diff(b) <= 8), "at {x}: {a:?} vs {b:?}"); } } + +/// #864 / G11: SVG export preserves the document's physical units on the root `width`/`height` so +/// that the unit setting survives a save/open round-trip. The engine-level test covers the full +/// stack (file.new → document.setUnits → document.serialize → document.open). +#[test] +fn svg_round_trip_preserves_document_units() { + // (unit name the engine accepts, expected unit after re-import) + let cases: &[(&str, vectorcraft_doc::Unit)] = &[ + ("millimeters", vectorcraft_doc::Unit::Millimeters), + ("centimeters", vectorcraft_doc::Unit::Centimeters), + ("inches", vectorcraft_doc::Unit::Inches), + ("picas", vectorcraft_doc::Unit::Picas), + // Points and pixels both serialise as bare user-unit numbers, so both import as Pixels. + ("pixels", vectorcraft_doc::Unit::Pixels), + ]; + for (name, expected) in cases { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 1})).unwrap(); + s.execute("document.setUnits", &json!({"units": name})).unwrap(); + let r = s.execute("document.serialize", &json!({"format": "svg"})).unwrap(); + let svg_text = r["text"].as_str().unwrap(); + match *expected { + vectorcraft_doc::Unit::Millimeters => assert!(svg_text.contains("mm\""), "mm suffix missing: {svg_text}"), + vectorcraft_doc::Unit::Centimeters => assert!(svg_text.contains("cm\""), "cm suffix missing: {svg_text}"), + vectorcraft_doc::Unit::Inches => assert!(svg_text.contains("in\""), "in suffix missing: {svg_text}"), + vectorcraft_doc::Unit::Picas => assert!(svg_text.contains("pc\""), "pc suffix missing: {svg_text}"), + _ => {} + } + let b64 = vectorcraft_format::base64_encode(svg_text.as_bytes()); + s.execute("document.open", &json!({"name": "test.svg", "dataBase64": b64})).unwrap(); + let doc_state = s.doc().unwrap(); + assert_eq!(doc_state.doc.units, *expected, "unit mismatch after round-trip for '{name}'"); + } + + // Points serialise without suffix and re-open as Pixels (equivalent in user units). + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 1})).unwrap(); + s.execute("document.setUnits", &json!({"units": "points"})).unwrap(); + let r = s.execute("document.serialize", &json!({"format": "svg"})).unwrap(); + let svg_text = r["text"].as_str().unwrap(); + assert!(svg_text.contains("width=\"200\" height=\"100\""), "{svg_text}"); + let b64 = vectorcraft_format::base64_encode(svg_text.as_bytes()); + s.execute("document.open", &json!({"name": "test.svg", "dataBase64": b64})).unwrap(); + assert_eq!(s.doc().unwrap().doc.units, vectorcraft_doc::Unit::Pixels); +} diff --git a/crates/engine/src/cmd/globaledit.rs b/crates/engine/src/cmd/globaledit.rs index 29fbf97fac..660df05f71 100644 --- a/crates/engine/src/cmd/globaledit.rs +++ b/crates/engine/src/cmd/globaledit.rs @@ -746,8 +746,8 @@ fn give_appearance(a: &Appearance, b: &Appearance, m: &Appearance, n: &mut Share } /// Give the member's fill or stroke `n` the settings of the model's that changed from `a` to `b`, -/// with the values of `m` (`b` placed on the member). A stroke's pen pressure, tilt, bearing and -/// rotation stay its own. +/// with the values of `m` (`b` placed on the member). A stroke's pen pressure, tilt, bearing, +/// rotation and wheel stay its own. fn give_item(a: &AppearanceItem, b: &AppearanceItem, m: &AppearanceItem, n: &mut AppearanceItem) { use AppearanceItem::{Fill, Stroke}; match (a, b, m, n) { @@ -781,6 +781,7 @@ fn give_item(a: &AppearanceItem, b: &AppearanceItem, m: &AppearanceItem, n: &mut tilt: _, bearing: _, rotation: _, + wheel: _, } = m; give_fields!(a, b, n: paint, width, cap, join, miter_limit, align, dash, start_arrow, end_arrow, arrow_scale, profile, brush, brush_options, opacity, blend, visible, effects, arrow_align, overprint, gradient_mode); // A stroke's own brush settings go with the brush they set: a new brush takes the model's. diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index b74dd97454..5d50fb9c39 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -7406,6 +7406,81 @@ fn the_last_label_of_a_kind_edited_together_sets_what_it_keeps() { assert_eq!(kept(&s), "#ff0000"); } +/// A column graph, a 10 pt square with one red fill row, and the category labels Q1, Q2 and Q3: Q1 and Q3 have one red +/// fill row, Q2 a hidden red fill row under a green one, and Q1's row is then painted blue, which the kind keeps. +/// Returns the graph, the square and the three labels. +fn labels_with_hidden_and_shown_rows(s: &mut Session) -> (NodeId, NodeId, [NodeId; 3]) { + use vectorcraft_doc::{AppearanceItem, FillLayer}; + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(s, "column"); + let square = NodeId(s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap()); + let labels = ["Q1", "Q2", "Q3"].map(|t| text_id(s, id, "Axes", t)); + let fill = |hex: &str, visible: bool| { + AppearanceItem::Fill(FillLayer { visible, ..FillLayer::new(Paint::solid(vectorcraft_color::Color::from_hex(hex).unwrap())) }) + }; + s.edit("Rows", |d, _| { + for (l, items) in [ + (square, vec![fill("#ff0000", true)]), + (labels[0], vec![fill("#ff0000", true)]), + (labels[1], vec![fill("#ff0000", false), fill("#00ff00", true)]), + (labels[2], vec![fill("#ff0000", true)]), + ] { + d.node_mut(l).unwrap().appearance.items = items; + } + Ok(()) + }) + .unwrap(); + s.execute("appearance.setItem", &json!({"ids": [labels[0].0], "index": 0, "color": "#0000ff"})).unwrap(); + assert_eq!(kept_category_fill(s, id), Some("#0000ff".into())); + (id, square, labels) +} + +/// The fill of the category label rows graph `id` keeps, as a hex color. +fn kept_category_fill(s: &Session, id: NodeId) -> Option { + spec(s, id).label_styles.categories_rows.and_then(|r| r.paint.fill).and_then(|p| p.color()).map(|c| c.to_hex()) +} + +/// Row edits on several labels at once, with a plain object among them, keep for the kind what the last label whose shown +/// row the edit wrote shows, also when that row comes out as it was; a label whose hidden row the edit wrote is left out. +/// One undo takes it back. Covers `appearance.setItem`, `appearance.duplicateItem` and `paint.setFill` with `item`. +#[test] +fn row_edits_on_several_labels_keep_the_last_written_shown_row() { + let edits = [ + ("appearance.setItem", json!({"index": 0, "color": "#ff0000"})), + ("appearance.duplicateItem", json!({"index": 0})), + ("paint.setFill", json!({"item": 0, "color": "#ff0000"})), + ]; + for (cmd, mut p) in edits { + let mut s = Session::new(); + let (id, square, [_, q2, q3]) = labels_with_hidden_and_shown_rows(&mut s); + // Q3 shows red before and after the edit; Q2 shows green over the hidden row the edit writes. + p["ids"] = json!([q3.0, square.0, q2.0]); + s.execute(cmd, &p).unwrap(); + assert_eq!(kept_category_fill(&s, id), Some("#ff0000".into()), "{cmd}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(kept_category_fill(&s, id), Some("#0000ff".into()), "{cmd}: undo"); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(kept_category_fill(&s, id), Some("#ff0000".into()), "{cmd}: redo"); + s.execute("edit.undo", &json!({})).unwrap(); + // Only the hidden row of a label: the kind keeps blue. + let steps = s.doc().unwrap().history.undo.len(); + p["ids"] = json!([square.0, q2.0]); + s.execute(cmd, &p).unwrap(); + assert_eq!(kept_category_fill(&s, id), Some("#0000ff".into()), "{cmd}: hidden row only"); + while s.doc().unwrap().history.undo.len() > steps { + s.execute("edit.undo", &json!({})).unwrap(); + } + // Q2's shown green row, written as it was: the kind keeps green. + p["ids"] = json!([q2.0]); + p[if cmd == "paint.setFill" { "item" } else { "index" }] = json!(1); + if cmd != "appearance.duplicateItem" { + p["color"] = json!("#00ff00"); + } + s.execute(cmd, &p).unwrap(); + assert_eq!(kept_category_fill(&s, id), Some("#00ff00".into()), "{cmd}: the shown row written as it was"); + } +} + /// A label's object opacity and blend mode set without a row (`transparency.set` without `item`) are kept for its kind. #[test] fn a_labels_object_opacity_and_blend_mode_are_kept_for_its_kind() { diff --git a/crates/engine/src/cmd/kinsokusets.rs b/crates/engine/src/cmd/kinsokusets.rs new file mode 100644 index 0000000000..8a62c4d8b0 --- /dev/null +++ b/crates/engine/src/cmd/kinsokusets.rs @@ -0,0 +1,353 @@ +//! Type › Kinsoku Shori Settings…: the document's custom Kinsoku Shori sets +//! ([`vectorcraft_doc::KinsokuSet`]). Each set lists the characters that may not start a line, +//! those that may not end one, the hanging punctuation Burasagari hangs, and the inseparable +//! sequences Bunri-Kinshi keeps together. A paragraph chooses one by name in Kinsoku Set +//! (`text.setFormat {kinsoku: name}`) and holds a copy of it, which an edit of the set replaces. +//! +//! Behavior reference: the help page +//! . +//! The name rules, the limits and Hard as the set a deleted set's paragraphs take are VectorCraft's +//! own. + +use std::collections::HashMap; +use std::sync::Arc; + +use serde_json::{Map, Value, json}; +use vectorcraft_doc::graph::LabelStyles; +use vectorcraft_doc::text::{KINSOKU_CATEGORY_MAX, KINSOKU_NAME_MAX, KINSOKU_SEQUENCE, KINSOKU_SETS_MAX}; +use vectorcraft_doc::{Document, Kinsoku, KinsokuSet, Node, NodeKind, ParaStyle}; + +use super::textstyles::each_node_with_text_mut; +use super::typecmd::refresh_bounds; +use super::{CommandSpec, Result, Session, bad, cmd, has_doc}; + +/// The command Type › Kinsoku Shori Settings…'s OK runs, and the menu item's. +pub const SET: &str = "type.kinsokuSets.set"; + +/// The keys a set may give. +const SET_KEYS: [&str; 6] = ["name", "from", "cannotStart", "cannotEnd", "hanging", "inseparable"]; + +pub fn specs() -> Vec { + vec![ + cmd!( + query "type.kinsokuSets.list", + "Kinsoku Sets", + [], + None, + "{} the active document's custom Kinsoku Shori sets, and the paragraphs, paragraph styles and graphs (in the paragraph attributes they keep for their labels) using each → {sets: [{name, cannotStart: characters, cannotEnd: characters, hanging: characters, inseparable: [sequence], paragraphs, styles, graphs}]}", + has_doc, + list + ), + cmd!( + query "type.kinsokuSets.base", + "Kinsoku Set Base", + [], + None, + "{base: \"none\"|\"hard\"|\"soft\"|name of a custom set (any case), name?} the categories of a built-in or custom set, as a new set based on it starts (Type › Kinsoku Shori Settings…'s New Set): Hard and Soft list the characters they keep off a line's start and end, the East Asian comma and full stop as hanging punctuation, and the pairs Bunri-Kinshi keeps together; None lists nothing → {set: {name, cannotStart, cannotEnd, hanging, inseparable}}", + has_doc, + base + ), + cmd!( + "type.kinsokuSets.set", + "Kinsoku Shori Settings…", + ["Type"], + None, + "{sets: [{name, from?: the name the set had (rename), cannotStart?: characters, cannotEnd?: characters, hanging?: characters, inseparable?: [sequence of 2..16 characters]}]} replace the active document's custom Kinsoku Shori sets (Type › Kinsoku Shori Settings…'s OK), as one undo step, none when nothing changes. Cannot Start Line characters never start a line and Cannot End Line characters never end one; Hanging Punctuation characters hang outside a line's end with Burasagari; while Bunri-Kinshi is on, a line never breaks inside an inseparable sequence. cannotStart, cannotEnd and hanging keep each character once, sorted, and inseparable keeps each sequence once, sorted (a sequence may repeat a character); each category holds at most 4096 characters (the sequences count each of their characters); a control or space character fails the call, as do an unknown key and a `from` the document has no set of. Names are trimmed, unique in any case, at most 128 characters, never None, Hard or Soft; at most 256 sets. A set given the name of a set the document has (any case) and no `from` is that set. Every paragraph and paragraph style using a set takes its new characters and name; one using a set left out takes Hard. The built-in None, Hard and Soft can't be changed or deleted → {sets}", + has_doc, + set + ), + ] +} + +/// Call `f` with every node in `d`'s layers (opacity masks included), symbols, graph designs, +/// pattern tiles and brush art, the trees [`each_node_with_text_mut`] reaches. +fn each_node(d: &Document, f: &mut impl FnMut(&Node)) { + let brushes = vectorcraft_brush::library(d); + let trees = d.layers.iter().map(|l| &**l).chain(d.symbols.iter().map(|s| &*s.art)).chain(d.graph_designs.iter().map(|g| &*g.art)); + let patterns = d.patterns.iter().chain(d.pattern_edit.iter().filter_map(|pe| pe.original.as_ref())); + let trees = trees.chain(patterns.flat_map(|p| p.art.iter().map(|a| &**a))).chain(brushes.iter().flat_map(|b| b.art())); + for tree in trees { + vectorcraft_doc::swatches::walk_with_masks(tree, &mut |n| f(n)); + } +} + +/// Call `f` with every paragraph of the type [`each_node`] reaches. +fn each_paragraph(d: &Document, f: &mut impl FnMut(&ParaStyle)) { + each_node(d, &mut |node| { + if let NodeKind::Text(t) = &node.kind { + (0..t.paragraph_count()).for_each(|i| f(t.para_at(i))); + } + }); +} + +/// How many paragraphs, paragraph styles and graphs (in the paragraph attributes they keep for +/// their labels) use each set of the document, by lowercased name. +fn uses(s: &Session) -> Result> { + let mut n: HashMap = HashMap::new(); + let d = &s.doc()?.doc; + each_paragraph(d, &mut |p| { + if let Some(set) = &p.kinsoku_set { + n.entry(set.name.to_lowercase()).or_default().0 += 1; + } + }); + for st in d.para_styles.iter() { + if let Some(name) = st.attrs.get("kinsoku_set").and_then(|v| v.get("name")).and_then(Value::as_str) { + n.entry(name.to_lowercase()).or_default().1 += 1; + } + } + each_node(d, &mut |node| { + let Some(g) = node.extras().graph.as_deref() else { return }; + let mut l = g.label_styles.clone(); + let mut names: Vec = label_paras(&mut l).filter_map(|p| p.kinsoku_set.as_ref().map(|k| k.name.to_lowercase())).collect(); + names.sort(); + names.dedup(); + for name in names { + n.entry(name).or_default().2 += 1; + } + }); + Ok(n) +} + +fn list(s: &mut Session, _: &Value) -> Result { + let uses = uses(s)?; + let sets: Vec = s + .doc()? + .doc + .kinsoku_sets + .iter() + .map(|set| { + let (paragraphs, styles, graphs) = uses.get(&set.name.to_lowercase()).copied().unwrap_or_default(); + let mut v = json!(set); + if let Some(o) = v.as_object_mut() { + o.insert("paragraphs".into(), json!(paragraphs)); + o.insert("styles".into(), json!(styles)); + o.insert("graphs".into(), json!(graphs)); + } + v + }) + .collect(); + Ok(json!({ "sets": sets })) +} + +/// The set `name` names: a built-in one (`none`, `hard`, `soft`) or a custom set of `sets` (any +/// case). +fn named_base(sets: &[KinsokuSet], name: &str) -> Option { + match name { + "none" => Some(vectorcraft_text::kinsoku_set_from(Kinsoku::None, "")), + "hard" => Some(vectorcraft_text::kinsoku_set_from(Kinsoku::Hard, "")), + "soft" => Some(vectorcraft_text::kinsoku_set_from(Kinsoku::Soft, "")), + _ => KinsokuSet::named(sets, name.trim()).cloned(), + } +} + +fn base(s: &mut Session, p: &Value) -> Result { + const C: &str = "type.kinsokuSets.base"; + let from = p.get("base").and_then(Value::as_str).ok_or_else(|| bad(C, "give base: \"none\", \"hard\", \"soft\" or a set's name"))?; + let mut set = named_base(&s.doc()?.doc.kinsoku_sets, from).ok_or_else(|| bad(C, format!("no Kinsoku set named `{from}`")))?; + set.name = match p.get("name") { + None | Some(Value::Null) => String::new(), + Some(Value::String(n)) => n.clone(), + Some(_) => return Err(bad(C, "name must be text")), + }; + Ok(json!({ "set": set })) +} + +/// A category of single characters from `v` (text, one character after another): empty when left +/// out. Text far longer than a category holds is refused before it is read. +fn chars(v: Option<&Value>, key: &str, name: &str, c: &str) -> Result> { + match v { + None | Some(Value::Null) => Ok(Vec::new()), + Some(Value::String(text)) => { + if text.chars().count() > KINSOKU_CATEGORY_MAX * 4 { + return Err(bad(c, format!("`{name}`: {key} must be at most {KINSOKU_CATEGORY_MAX} characters"))); + } + Ok(text.chars().collect()) + } + Some(_) => Err(bad(c, format!("`{name}`: {key} must be text, one character after another"))), + } +} + +/// Set `v` from command parameters, its name trimmed, with the name it had (`from`, trimmed) when +/// it gives one. +fn parse_set(v: &Value, c: &str) -> Result<(KinsokuSet, Option)> { + let o = v.as_object().ok_or_else(|| bad(c, "each set must be {name, cannotStart?, cannotEnd?, hanging?, inseparable?}"))?; + if let Some(k) = o.keys().find(|k| !SET_KEYS.contains(&k.as_str())) { + return Err(bad(c, format!("unknown key `{k}`; a set takes {}", SET_KEYS.join(", ")))); + } + // A null value is refused rather than read as a key left out. + if let Some(k) = o.iter().find_map(|(k, v)| v.is_null().then_some(k)) { + return Err(bad(c, format!("`{k}` can't be null; leave it out instead"))); + } + let raw = o.get("name").and_then(Value::as_str).ok_or_else(|| bad(c, "each set needs a name"))?; + let name = KinsokuSet::clean_name(raw).ok_or_else(|| { + bad(c, format!("`{raw}` can't name a Kinsoku set (1 to {KINSOKU_NAME_MAX} characters, no control characters, not None, Hard or Soft)")) + })?; + let from = match o.get("from") { + None | Some(Value::Null) => None, + Some(Value::String(f)) => Some(f.trim().to_string()), + Some(_) => return Err(bad(c, format!("`{name}`: from must be text"))), + }; + let inseparable = match o.get("inseparable") { + None | Some(Value::Null) => Vec::new(), + Some(Value::Array(list)) => { + if list.len() > KINSOKU_CATEGORY_MAX { + return Err(bad(c, format!("`{name}`: inseparable: at most {KINSOKU_CATEGORY_MAX} characters in all"))); + } + list.iter() + .map(|s| { + s.as_str().map(str::to_string).ok_or_else(|| { + bad( + c, + format!( + "`{name}`: inseparable must be a list of {} to {} characters each", + KINSOKU_SEQUENCE.start(), + KINSOKU_SEQUENCE.end() + ), + ) + }) + }) + .collect::>>()? + } + Some(_) => return Err(bad(c, format!("`{name}`: inseparable must be a list of sequences"))), + }; + let mut set = KinsokuSet { + cannot_start: chars(o.get("cannotStart"), "cannotStart", &name, c)?, + cannot_end: chars(o.get("cannotEnd"), "cannotEnd", &name, c)?, + hanging: chars(o.get("hanging"), "hanging", &name, c)?, + inseparable, + name, + }; + set.normalize(); + set.check().map_err(|e| bad(c, format!("`{}`: {e}", set.name)))?; + Ok((set, from)) +} + +/// Make `after` the active document's custom sets, as one undo step (none when nothing changes). +/// `renamed` maps the lowercased name of each set of the document that is kept to the index in +/// `after` of what it becomes; a set it leaves out is deleted, and its paragraphs and paragraph +/// styles take Hard. +fn replace(s: &mut Session, after: Vec, renamed: HashMap) -> Result<()> { + let before = s.doc()?.doc.kinsoku_sets.to_vec(); + let after_arcs: Vec> = after.iter().cloned().map(Arc::new).collect(); + // The paragraph value of each set of the document as it was: the new set, or none (Hard). + let next = |old: &KinsokuSet| -> Option>> { + let key = old.name.to_lowercase(); + before.iter().any(|b| b.name.to_lowercase() == key).then(|| renamed.get(&key).and_then(|&i| after_arcs.get(i).cloned())) + }; + let fix = |p: &mut ParaStyle| -> bool { + let Some(old) = p.kinsoku_set.as_deref() else { return false }; + let Some(new) = next(old) else { return false }; + if new.as_deref() == Some(old) { + return false; + } + if new.is_none() { + p.kinsoku = Kinsoku::Hard; + } + p.kinsoku_set = new; + true + }; + let mut texts_change = false; + each_paragraph(&s.doc()?.doc, &mut |p| texts_change |= !texts_change && fix(&mut p.clone())); + // A graph draws its labels again from the paragraph attributes it keeps for them. + let fix_labels = |l: &mut LabelStyles| label_paras(l).fold(false, |changed, p| fix(p) | changed); + each_node(&s.doc()?.doc, &mut |n| { + texts_change |= !texts_change && n.extras().graph.as_deref().is_some_and(|g| fix_labels(&mut g.label_styles.clone())); + }); + let style_attrs = |attrs: &Map| -> Option> { + let old: KinsokuSet = serde_json::from_value(attrs.get("kinsoku_set")?.clone()).ok()?; + let new = next(&old)?; + if new.as_deref() == Some(&old) { + return None; + } + let mut m = attrs.clone(); + match new { + Some(set) => m.insert("kinsoku_set".into(), json!(set)), + None => { + m.insert("kinsoku".into(), json!(Kinsoku::Hard)); + m.insert("kinsoku_set".into(), Value::Null) + } + }; + Some(m) + }; + let styles_change = s.doc()?.doc.para_styles.iter().any(|st| style_attrs(&st.attrs).is_some()); + if before == after && !texts_change && !styles_change { + return Ok(()); + } + s.edit("Kinsoku Shori Settings", |d, _| { + *d.kinsoku_sets = after.clone(); + for st in d.para_styles.iter_mut() { + if let Some(m) = style_attrs(&st.attrs) { + st.attrs = m; + } + } + each_node_with_text_mut(d, &mut |n| { + if let Some(g) = n.extras_if_any().and_then(|e| e.graph.as_deref_mut()) { + fix_labels(&mut g.label_styles); + } + if let NodeKind::Text(t) = &mut n.kind { + let mut changed = false; + for p in t.para_styles_mut() { + changed |= fix(p); + } + if changed { + refresh_bounds(t); + } + } + Ok(()) + }) + }) +} + +/// The paragraph attributes graph label styles `l` keep: the value axis, the categories and the +/// legend. +fn label_paras(l: &mut LabelStyles) -> impl Iterator { + [&mut l.values_para, &mut l.categories_para, &mut l.legend_para].into_iter().flatten() +} + +fn set(s: &mut Session, p: &Value) -> Result { + let list = + p.get("sets").and_then(Value::as_array).ok_or_else(|| bad(SET, "give sets: [{name, cannotStart?, cannotEnd?, hanging?, inseparable?}…]"))?; + if list.len() > KINSOKU_SETS_MAX { + return Err(bad(SET, format!("a document keeps at most {KINSOKU_SETS_MAX} Kinsoku sets"))); + } + let parsed = list.iter().map(|v| parse_set(v, SET)).collect::>>()?; + let mut names = std::collections::HashSet::new(); + for (set, _) in &parsed { + if !names.insert(set.name.to_lowercase()) { + return Err(bad(SET, format!("two Kinsoku sets are named `{}`", set.name))); + } + } + let before = s.doc()?.doc.kinsoku_sets.to_vec(); + let has = |n: &str| before.iter().any(|b| KinsokuSet::same_name(&b.name, n)); + // Which set of the document each given set continues: the one `from` names, else the one of + // its own name that no other set's `from` claims. + let mut renamed: HashMap = HashMap::new(); + for (i, (set, from)) in parsed.iter().enumerate() { + if let Some(f) = from { + if !has(f) { + return Err(bad(SET, format!("`{}`: the document has no Kinsoku set named `{f}`", set.name))); + } + if renamed.insert(f.to_lowercase(), i).is_some() { + return Err(bad(SET, format!("two Kinsoku sets come from `{f}`"))); + } + } + } + for (i, (set, from)) in parsed.iter().enumerate() { + let key = set.name.to_lowercase(); + if from.is_none() && has(&set.name) && !renamed.contains_key(&key) { + renamed.insert(key, i); + } + } + let after: Vec = parsed.into_iter().map(|(set, _)| set).collect(); + replace(s, after.clone(), renamed)?; + Ok(json!({ "sets": after })) +} + +/// The custom set of the active document that `text.setFormat`'s `kinsoku` names (any case), as a +/// paragraph holds it. +pub(crate) fn chosen(s: &Session, name: &str) -> Result>> { + Ok(KinsokuSet::named(&s.doc()?.doc.kinsoku_sets, name.trim()).cloned().map(Arc::new)) +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/kinsokusets/tests.rs b/crates/engine/src/cmd/kinsokusets/tests.rs new file mode 100644 index 0000000000..1d1c8980c0 --- /dev/null +++ b/crates/engine/src/cmd/kinsokusets/tests.rs @@ -0,0 +1,458 @@ +use serde_json::{Value, json}; +use vectorcraft_doc::{Kinsoku, NodeId, NodeKind}; + +use crate::Session; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + s +} + +fn names(s: &Session) -> Vec { + s.doc().unwrap().doc.kinsoku_sets.iter().map(|k| k.name.clone()).collect() +} + +fn steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn text(s: &Session, id: u64) -> vectorcraft_doc::TextObject { + match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => (**t).clone(), + _ => panic!("not text"), + } +} + +/// Two paragraphs of area type, the second one selected by its range. +fn type_object(s: &mut Session) -> u64 { + s.execute("text.create", &json!({"x": 10, "y": 10, "text": "あいう\nかきく", "area": {"width": 100, "height": 100}})).unwrap()["id"] + .as_u64() + .unwrap() +} + +fn tight() -> Value { + json!({"name": "Tight", "cannotStart": "」。、う", "cannotEnd": "「", "hanging": "、。", "inseparable": ["——"]}) +} + +/// Kinsoku Shori Settings' OK replaces the document's custom sets as one undo step (none when +/// nothing changes); each category keeps each character once, sorted; the sets are listed with +/// their users, saved with the document and undone with it. +#[test] +fn kinsoku_sets_are_set_as_one_undo_step_and_saved() { + let mut s = session(); + let before = steps(&s); + let r = s.execute("type.kinsokuSets.set", &json!({"sets": [tight(), {"name": " Loose ", "cannotStart": "ーーッ"}]})).unwrap(); + assert_eq!(r["sets"][1]["name"], "Loose"); + assert_eq!(r["sets"][1]["cannotStart"], "ッー"); + assert_eq!(names(&s), ["Tight", "Loose"]); + assert_eq!(steps(&s), before + 1); + s.execute("type.kinsokuSets.set", &json!({"sets": [tight(), {"name": "Loose", "cannotStart": "ッー"}]})).unwrap(); + assert_eq!(steps(&s), before + 1, "the same sets again change nothing"); + let listed = s.execute("type.kinsokuSets.list", &json!({})).unwrap(); + assert_eq!((listed["sets"][0]["name"].clone(), listed["sets"][0]["paragraphs"].clone()), (json!("Tight"), json!(0))); + let reopened = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + assert_eq!(*reopened.kinsoku_sets, *s.doc().unwrap().doc.kinsoku_sets); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(names(&s).is_empty()); + // A document without sets saves none. + let saved = vectorcraft_format::save(&s.doc().unwrap().doc, false); + assert!(!String::from_utf8_lossy(&saved).contains("kinsoku_sets")); +} + +/// The sets are checked before anything changes: a built-in name, a blank or too-long name, two +/// sets of one name in any case, an unknown key, a sequence of one character or with a space, a +/// control character, a `from` the document has no set of, a null value, and more than 256 sets +/// all fail. +#[test] +fn kinsoku_sets_refuse_what_a_set_cannot_hold() { + let mut s = session(); + s.execute("type.kinsokuSets.set", &json!({"sets": [tight()]})).unwrap(); + let before = steps(&s); + let long = "x".repeat(129); + for bad in [ + json!([{"name": "Hard"}]), + json!([{"name": "soft"}]), + json!([{"name": " "}]), + json!([{"name": long}]), + json!([{"name": "A"}, {"name": "a"}]), + json!([{"name": "A", "strict": true}]), + json!([{"name": "A", "inseparable": ["あ"]}]), + json!([{"name": "A", "inseparable": ["あ い"]}]), + json!([{"name": "A", "inseparable": "あい"}]), + json!([{"name": "A", "cannotStart": "あ\u{7}"}]), + json!([{"name": "A", "cannotStart": ["あ"]}]), + json!([{"name": "A", "from": "Missing"}]), + json!([{"name": "A", "from": "Tight"}, {"name": "B", "from": "tight"}]), + json!([{"name": "Tight", "from": "Tight", "cannotStart": null}]), + json!([{"name": "Tight", "from": null}]), + json!([{"name": "A", "inseparable": null}]), + json!((0..257).map(|i| json!({"name": format!("S{i}")})).collect::>()), + ] { + assert!(s.execute("type.kinsokuSets.set", &json!({"sets": bad})).is_err(), "{bad}"); + } + assert!(s.execute("type.kinsokuSets.set", &json!({})).is_err()); + assert_eq!((names(&s), steps(&s)), (vec!["Tight".to_string()], before), "a refused call changes nothing"); +} + +/// Kinsoku Set chooses a custom set by name (any case) for the paragraphs `text.setFormat` sets: each +/// holds a copy of it beside Hard, in one undo step; a name the document has no set of fails the call +/// and changes nothing; a built-in set takes the custom one's place. Paragraph styles carry it. +#[test] +fn text_set_format_chooses_a_custom_set_per_paragraph() { + let mut s = session(); + s.execute("type.kinsokuSets.set", &json!({"sets": [tight()]})).unwrap(); + let id = type_object(&mut s); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + assert!(s.execute("text.setFormat", &json!({"kinsoku": "Missing"})).is_err()); + assert!(text(&s, id).para_at(0).kinsoku_set.is_none(), "a refused call changes nothing"); + let before = steps(&s); + let second = "あいう\n".len(); + s.execute("text.setFormat", &json!({"kinsoku": "tight", "start": second, "end": second})).unwrap(); + assert_eq!(steps(&s), before + 1); + let t = text(&s, id); + assert!(t.para_at(0).kinsoku_set.is_none()); + let p = t.para_at(1); + assert_eq!((p.kinsoku_name(), p.kinsoku), ("Tight", Kinsoku::Hard)); + s.execute("text.setFormat", &json!({"kinsoku": "Tight", "start": second, "end": second})).unwrap(); + assert_eq!(steps(&s), before + 1, "the set the paragraph already has records nothing"); + // The file keeps the paragraph's copy. + let reopened = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + let Some(NodeKind::Text(back)) = reopened.node(NodeId(id)).map(|n| &n.kind) else { panic!("text") }; + assert_eq!(back.para_at(1).kinsoku_name(), "Tight"); + // A paragraph style captured from it carries the set; Soft replaces it. + s.execute("paraStyle.new", &json!({"name": "Tight Body", "id": id, "start": second, "end": second})).unwrap(); + s.execute("text.setFormat", &json!({"kinsoku": "soft"})).unwrap(); + assert!(text(&s, id).para_at(1).kinsoku_set.is_none()); + assert_eq!(text(&s, id).para_at(1).kinsoku, Kinsoku::Soft); + s.execute("paraStyle.apply", &json!({"name": "Tight Body", "id": id})).unwrap(); + assert_eq!(text(&s, id).para_at(0).kinsoku_name(), "Tight"); + assert_eq!(text(&s, id).para_at(1).kinsoku_name(), "Tight"); +} + +/// A paragraph style that gives only a built-in Kinsoku Set replaces a custom set on the paragraphs +/// it is applied to: the style keeps Kinsoku Set's custom set with its built-in choice. One whose +/// attributes give only a custom set (written by hand into a file) brings Hard with it. +#[test] +fn a_style_with_a_built_in_kinsoku_set_replaces_a_custom_set() { + let mut s = session(); + s.execute("type.kinsokuSets.set", &json!({"sets": [tight()]})).unwrap(); + let id = type_object(&mut s); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + for (style, kinsoku, name) in [("Soft Only", "soft", "Soft"), ("None Only", "none", "None"), ("Hard Only", "hard", "Hard")] { + s.execute("text.setFormat", &json!({"kinsoku": "Tight"})).unwrap(); + assert_eq!(text(&s, id).para_at(0).kinsoku_name(), "Tight"); + s.execute("paraStyle.new", &json!({"name": style, "attrs": {"kinsoku": kinsoku}})).unwrap(); + s.execute("paraStyle.apply", &json!({"name": style, "id": id})).unwrap(); + let t = text(&s, id); + assert_eq!((t.para_at(0).kinsoku_name(), t.para_at(1).kinsoku_name()), (name, name), "{style}"); + } + s.execute("text.setFormat", &json!({"kinsoku": "soft"})).unwrap(); + let only_set = serde_json::Map::from_iter([("kinsoku_set".to_string(), tight_set(&s))]); + let def = vectorcraft_doc::TextStyleDef { name: "Set Only".into(), attrs: only_set }; + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).para_styles.push(def); + s.execute("paraStyle.apply", &json!({"name": "Set Only", "id": id})).unwrap(); + assert_eq!(text(&s, id).para_at(0).kinsoku_name(), "Tight"); +} + +fn tight_set(s: &Session) -> Value { + json!(s.doc().unwrap().doc.kinsoku_sets[0]) +} + +/// Redefining a paragraph style's Kinsoku Set changes the paragraphs that use the style's set and +/// keeps a paragraph's own custom set: the set and Hard beside it change together. +#[test] +fn redefining_a_style_keeps_a_paragraphs_own_custom_set() { + let mut s = session(); + s.execute("type.kinsokuSets.set", &json!({"sets": [tight(), {"name": "Loose"}]})).unwrap(); + let id = type_object(&mut s); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + s.execute("paraStyle.new", &json!({"name": "Body", "attrs": {"kinsoku_set": tight_set(&s)}})).unwrap(); + s.execute("paraStyle.apply", &json!({"name": "Body", "id": id})).unwrap(); + let second = "あいう\n".len(); + s.execute("text.setFormat", &json!({"kinsoku": "Loose", "start": second, "end": second})).unwrap(); + s.execute("paraStyle.setAttrs", &json!({"name": "Body", "attrs": {"kinsoku": "soft"}})).unwrap(); + let t = text(&s, id); + assert_eq!((t.para_at(0).kinsoku_name(), t.para_at(1).kinsoku_name()), ("Soft", "Loose")); +} + +/// A paragraph style's custom set is one of the document's, by name in any case, with the +/// document's characters; a name the document has no set of fails the call. +#[test] +fn a_styles_custom_set_is_one_of_the_documents() { + let mut s = session(); + s.execute("type.kinsokuSets.set", &json!({"sets": [tight()]})).unwrap(); + assert!(s.execute("paraStyle.new", &json!({"name": "Body", "attrs": {"kinsoku_set": {"name": "Missing"}}})).is_err()); + s.execute("paraStyle.new", &json!({"name": "Body", "attrs": {"kinsoku_set": {"name": "tight", "cannotStart": "x"}}})).unwrap(); + let listed = s.execute("paraStyle.list", &json!({})).unwrap(); + let body = listed["styles"].as_array().unwrap().iter().find(|st| st["name"] == "Body").unwrap().clone(); + assert_eq!(body["attrs"]["kinsoku_set"], tight_set(&s)); + assert!(s.execute("paraStyle.setAttrs", &json!({"name": "Body", "attrs": {"kinsoku_set": {"name": "Missing"}}})).is_err()); +} + +/// A custom set goes with Hard and has a name a custom set can have: a paragraph style call that +/// gives one beside None or Soft, or with a blank or built-in name, fails and leaves the styles as +/// they were, and one beside Hard is kept. +#[test] +fn a_styles_custom_set_given_beside_none_or_soft_fails_the_call() { + let mut s = session(); + s.execute("type.kinsokuSets.set", &json!({"sets": [tight()]})).unwrap(); + s.execute("paraStyle.new", &json!({"name": "Body", "attrs": {"kinsoku_set": tight_set(&s)}})).unwrap(); + let styles = |s: &Session| s.doc().unwrap().doc.para_styles.clone(); + let before = styles(&s); + for kinsoku in ["none", "soft"] { + let attrs = json!({"kinsoku": kinsoku, "kinsoku_set": tight_set(&s)}); + assert!(s.execute("paraStyle.new", &json!({"name": "Other", "attrs": attrs})).is_err(), "new with {kinsoku}"); + assert!(s.execute("paraStyle.setAttrs", &json!({"name": "Body", "attrs": attrs})).is_err(), "setAttrs with {kinsoku}"); + assert_eq!(styles(&s), before, "{kinsoku}"); + } + for name in ["", " ", "Hard", "soft"] { + let attrs = json!({"kinsoku_set": {"name": name}}); + assert!(s.execute("paraStyle.new", &json!({"name": "Other", "attrs": attrs})).is_err(), "new named `{name}`"); + assert!(s.execute("paraStyle.setAttrs", &json!({"name": "Body", "attrs": attrs})).is_err(), "setAttrs named `{name}`"); + assert_eq!(styles(&s), before, "`{name}`"); + } + let attrs = json!({"kinsoku": "hard", "kinsoku_set": tight_set(&s)}); + s.execute("paraStyle.new", &json!({"name": "Other", "attrs": attrs})).unwrap(); + let other = styles(&s).into_iter().find(|st| st.name == "Other").unwrap(); + assert_eq!(other.attrs["kinsoku_set"], tight_set(&s)); +} + +/// Editing a set gives every paragraph and paragraph style using it the new characters, renaming it +/// (`from`) the new name too, and deleting it sets them to Hard: each in one undo step, which undo +/// takes back with the set. Paragraphs using no set, or another set, stay as they are. +#[test] +fn editing_renaming_and_deleting_a_set_updates_its_users() { + let mut s = session(); + s.execute("type.kinsokuSets.set", &json!({"sets": [tight(), {"name": "Other", "cannotStart": "ー"}]})).unwrap(); + let id = type_object(&mut s); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let second = "あいう\n".len(); + s.execute("text.setFormat", &json!({"kinsoku": "Tight", "start": 0, "end": 0})).unwrap(); + s.execute("text.setFormat", &json!({"kinsoku": "Other", "start": second, "end": second})).unwrap(); + s.execute("paraStyle.new", &json!({"name": "Uses Tight", "id": id, "start": 0, "end": 0})).unwrap(); + let style_set = |s: &Session| s.doc().unwrap().doc.para_styles.iter().find(|st| st.name == "Uses Tight").unwrap().attrs["kinsoku_set"].clone(); + assert_eq!(style_set(&s)["name"], "Tight"); + let listed = s.execute("type.kinsokuSets.list", &json!({})).unwrap(); + assert_eq!((listed["sets"][0]["paragraphs"].clone(), listed["sets"][0]["styles"].clone()), (json!(1), json!(1))); + + // Edit: 「 may end a line now, and う may start one. + let before = steps(&s); + let edited = json!({"name": "Tight", "cannotStart": "」。、", "hanging": "、。", "inseparable": ["——"]}); + s.execute("type.kinsokuSets.set", &json!({"sets": [edited, {"name": "Other", "cannotStart": "ー"}]})).unwrap(); + assert_eq!(steps(&s), before + 1); + let p = text(&s, id).para_at(0).clone(); + assert_eq!(p.kinsoku_set.as_ref().unwrap().cannot_start, ['、', '。', '」']); + assert!(p.kinsoku_set.as_ref().unwrap().cannot_end.is_empty()); + assert_eq!(style_set(&s)["cannotStart"], "、。」"); + assert_eq!(text(&s, id).para_at(1).kinsoku_name(), "Other", "another set's paragraph stays"); + + // Rename: the users take the new name. + let renamed = json!({"name": "Strict", "from": "Tight", "cannotStart": "」。、", "hanging": "、。", "inseparable": ["——"]}); + s.execute("type.kinsokuSets.set", &json!({"sets": [renamed, {"name": "Other", "cannotStart": "ー"}]})).unwrap(); + assert_eq!(names(&s), ["Strict", "Other"]); + assert_eq!(text(&s, id).para_at(0).kinsoku_name(), "Strict"); + assert_eq!(style_set(&s)["name"], "Strict"); + + // Delete: its users take Hard, in one step that undo takes back. + let before = steps(&s); + s.execute("type.kinsokuSets.set", &json!({"sets": [{"name": "Other", "cannotStart": "ー"}]})).unwrap(); + assert_eq!(steps(&s), before + 1); + let p = text(&s, id).para_at(0).clone(); + assert_eq!((p.kinsoku_set.is_none(), p.kinsoku), (true, Kinsoku::Hard)); + assert_eq!(style_set(&s), Value::Null); + assert_eq!(text(&s, id).para_at(1).kinsoku_name(), "Other"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(text(&s, id).para_at(0).kinsoku_name(), "Strict"); + assert_eq!(style_set(&s)["name"], "Strict"); + assert_eq!(names(&s), ["Strict", "Other"]); +} + +/// Type pasted into another document brings its custom sets: a missing set is added, the +/// document's set of that name with the same characters is used, and one with other characters +/// keeps its own and the pasted set comes in under a free name, so editing the document's set +/// leaves the pasted paragraphs alone. A paragraph style that comes along takes the same set. A +/// document with no room for another set gives the pasted paragraphs Hard. +#[test] +fn pasted_type_brings_its_kinsoku_sets() { + let mut s = session(); + s.execute("type.kinsokuSets.set", &json!({"sets": [tight()]})).unwrap(); + let id = type_object(&mut s); + s.execute("paraStyle.new", &json!({"name": "Tight Body", "attrs": {"kinsoku_set": tight_set(&s)}})).unwrap(); + s.execute("paraStyle.apply", &json!({"name": "Tight Body", "id": id})).unwrap(); + let source = s.doc().unwrap().doc.kinsoku_sets[0].clone(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + let pasted = |s: &mut Session| -> (vectorcraft_doc::TextObject, Value) { + let v = s.execute("edit.paste", &json!({})).unwrap(); + (text(s, v["ids"][0].as_u64().unwrap()), v) + }; + let style_set = |s: &Session| s.doc().unwrap().doc.para_styles.iter().find(|st| st.name == "Tight Body").unwrap().attrs["kinsoku_set"].clone(); + + // Pasted back after the set was edited: the document's set as it is now, laid out anew. + s.execute("type.kinsokuSets.set", &json!({"sets": [{"name": "Tight", "cannotStart": "いうかきく"}]})).unwrap(); + let (t, _) = pasted(&mut s); + let now = s.doc().unwrap().doc.kinsoku_sets[0].clone(); + assert_eq!(t.para_at(0).kinsoku_set.as_deref(), Some(&now)); + let mut fresh = t.clone(); + crate::cmd::typecmd::refresh_bounds(&mut fresh); + assert!(fresh == t, "the pasted type is laid out with the document's set"); + + // A document without the set. + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let (t, _) = pasted(&mut s); + assert_eq!(names(&s), ["Tight"]); + assert_eq!(t.para_at(1).kinsoku_set.as_deref(), Some(&source)); + assert_eq!(style_set(&s), json!(source)); + let (_, again) = pasted(&mut s); + assert_eq!((again["added"].clone(), names(&s)), (json!(0), vec!["Tight".to_string()]), "a second paste uses the set the first added"); + + // A document whose set of that name has other characters. + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + s.execute("type.kinsokuSets.set", &json!({"sets": [{"name": "TIGHT", "cannotStart": "ー"}]})).unwrap(); + let (t, v) = pasted(&mut s); + assert_eq!(names(&s), ["TIGHT", "Tight 2"]); + let p = t.para_at(0); + assert_eq!((p.kinsoku_name(), p.kinsoku_set.as_deref().map(|k| &k.cannot_start)), ("Tight 2", Some(&source.cannot_start))); + assert_eq!(style_set(&s)["name"], "Tight 2"); + assert!(v["renamed"].as_array().unwrap().contains(&json!({"kind": "kinsokuSet", "from": "Tight", "to": "Tight 2"})), "{v}"); + let kept = json!(s.doc().unwrap().doc.kinsoku_sets[1]); + s.execute("type.kinsokuSets.set", &json!({"sets": [{"name": "TIGHT", "cannotStart": "ッ"}, kept]})).unwrap(); + let users = s.execute("type.kinsokuSets.list", &json!({})).unwrap(); + assert_eq!(users["sets"][0]["paragraphs"], 0, "editing the document's own set leaves the pasted paragraphs alone: {users}"); + + // A document with no room for another set. + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let full: Vec = (0..256).map(|i| json!({"name": format!("Set {i}")})).collect(); + s.execute("type.kinsokuSets.set", &json!({"sets": full})).unwrap(); + let (t, _) = pasted(&mut s); + assert_eq!(names(&s).len(), 256); + let p = t.para_at(0); + assert_eq!((p.kinsoku_set.is_none(), p.kinsoku), (true, Kinsoku::Hard)); + assert_eq!(style_set(&s), Value::Null); +} + +/// A pasted set whose name, at the longest a name can be, the document's set with other +/// characters already has comes in under a free name that fits: the number takes the place of the +/// name's last characters, and a space left at the end of them is dropped. A second paste uses +/// the set the first added. +#[test] +fn a_pasted_set_with_the_longest_name_comes_in_under_a_name_that_fits() { + for (long, fitted) in + [("あ".repeat(128), format!("{} 2", "あ".repeat(126))), (format!("{} いい", "あ".repeat(125)), format!("{} 2", "あ".repeat(125)))] + { + let mut s = session(); + s.execute("type.kinsokuSets.set", &json!({"sets": [{"name": long, "cannotStart": "」"}]})).unwrap(); + let id = type_object(&mut s); + s.execute("text.setFormat", &json!({"ids": [id], "kinsoku": long})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + s.execute("type.kinsokuSets.set", &json!({"sets": [{"name": long, "cannotStart": "ー"}]})).unwrap(); + let v = s.execute("edit.paste", &json!({})).unwrap(); + assert_eq!(names(&s), [long.clone(), fitted.clone()]); + let t = text(&s, v["ids"][0].as_u64().unwrap()); + let p = t.para_at(0); + assert_eq!((p.kinsoku_name(), p.kinsoku_set.as_deref().map(|k| k.cannot_start.clone())), (fitted.as_str(), Some(vec!['」']))); + let again = s.execute("edit.paste", &json!({})).unwrap(); + assert_eq!( + (again["added"].clone(), names(&s)), + (json!(0), vec![long.clone(), fitted.clone()]), + "a second paste uses the set the first added" + ); + } +} + +/// The Kinsoku Sets a graph keeps for its labels (value axis, categories, legend), and those its +/// labels are drawn with now. +fn graph_label_sets(s: &Session, id: u64) -> (Vec, Vec) { + let n = s.doc().unwrap().doc.node(NodeId(id)).unwrap().clone(); + let l = n.extras().graph.as_deref().unwrap().label_styles.clone(); + let kept = [l.values_para, l.categories_para, l.legend_para].into_iter().flatten().map(|p| p.kinsoku_name().to_string()).collect(); + let mut drawn = vec![]; + n.walk(&mut |m| { + if let NodeKind::Text(t) = &m.kind { + drawn.push(t.para_at(0).kinsoku_name().to_string()); + } + }); + (kept, drawn) +} + +/// A graph's labels keep a custom set as type does. Pasted into a document whose set of that name +/// has other characters, they take the copy the paste adds, also once the graph is drawn again. +/// Editing a set gives the graph's kept attributes the new characters, and deleting it gives them +/// Hard. +#[test] +fn graph_labels_keep_their_custom_set() { + let mut s = session(); + s.execute("type.kinsokuSets.set", &json!({"sets": [tight()]})).unwrap(); + let csv = ",2024,2025\nQ1,3,2\nQ2,5,4"; + let id = s.execute("graph.create", &json!({"type": "column", "x": 10, "y": 10, "width": 300, "height": 200, "csv": csv})).unwrap()["id"] + .as_u64() + .unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + s.execute("text.setFormat", &json!({"kinsoku": "Tight"})).unwrap(); + let (kept, drawn) = graph_label_sets(&s, id); + assert_eq!(kept, ["Tight"; 3]); + assert!(!drawn.is_empty() && drawn.iter().all(|k| k == "Tight"), "{drawn:?}"); + s.execute("edit.copy", &json!({})).unwrap(); + + // Pasted where the set of that name has other characters: the labels take the added copy. + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + s.execute("type.kinsokuSets.set", &json!({"sets": [{"name": "TIGHT", "cannotStart": "ー"}]})).unwrap(); + let pasted = s.execute("edit.paste", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + assert_eq!(names(&s), ["TIGHT", "Tight 2"]); + s.execute("graph.setData", &json!({"id": pasted, "csv": csv})).unwrap(); + let (kept, drawn) = graph_label_sets(&s, pasted); + assert_eq!(kept, ["Tight 2"; 3]); + assert!(drawn.iter().all(|k| k == "Tight 2"), "the labels drawn again keep the copy: {drawn:?}"); + + // A second copy becomes a symbol's art. + let in_symbol = s.execute("edit.paste", &json!({})).unwrap()["ids"][0].clone(); + s.execute("symbol.new", &json!({"name": "Chart", "ids": [in_symbol]})).unwrap(); + let symbol_starts = |s: &Session| { + let mut out = vec![]; + s.doc().unwrap().doc.symbols.iter().find(|x| x.name == "Chart").unwrap().art.walk(&mut |n| { + if let Some(g) = n.extras().graph.as_deref() { + out.push(g.label_styles.values_para.as_ref().unwrap().kinsoku_set.as_deref().unwrap().cannot_start.clone()); + } + }); + out + }; + assert_eq!(symbol_starts(&s).len(), 1); + let listed = s.execute("type.kinsokuSets.list", &json!({})).unwrap(); + assert_eq!((listed["sets"][1]["name"].clone(), listed["sets"][1]["graphs"].clone()), (json!("Tight 2"), json!(2)), "{listed}"); + assert_eq!(listed["sets"][0]["graphs"], 0); + + // Edited, then deleted: the kept attributes follow the set, so the labels drawn again do too. + let edited = json!({"name": "Tight 2", "cannotStart": "ー"}); + s.execute("type.kinsokuSets.set", &json!({"sets": [{"name": "TIGHT", "cannotStart": "ー"}, edited]})).unwrap(); + let l = &s.doc().unwrap().doc.node(NodeId(pasted)).unwrap().extras().graph.as_deref().unwrap().label_styles; + assert_eq!(l.values_para.as_ref().unwrap().kinsoku_set.as_deref().unwrap().cannot_start, ['ー']); + assert_eq!(symbol_starts(&s), [vec!['ー']], "a graph in a symbol's art too"); + s.execute("type.kinsokuSets.set", &json!({"sets": [{"name": "TIGHT", "cannotStart": "ー"}]})).unwrap(); + s.execute("graph.setData", &json!({"id": pasted, "csv": csv})).unwrap(); + let (kept, drawn) = graph_label_sets(&s, pasted); + assert_eq!(kept, ["Hard"; 3]); + assert!(drawn.iter().all(|k| k == "Hard"), "{drawn:?}"); +} + +/// New Set's starting point: Hard and Soft give their characters, None gives an empty set, and a +/// custom set (any case) gives its own; an unknown base fails. +#[test] +fn a_new_set_starts_from_a_built_in_or_custom_set() { + let mut s = session(); + s.execute("type.kinsokuSets.set", &json!({"sets": [tight()]})).unwrap(); + let hard = s.execute("type.kinsokuSets.base", &json!({"base": "hard", "name": "New"})).unwrap(); + let soft = s.execute("type.kinsokuSets.base", &json!({"base": "soft"})).unwrap(); + let start = |v: &Value| v["set"]["cannotStart"].as_str().unwrap().to_string(); + assert!(start(&hard).contains('ー') && !start(&soft).contains('ー') && start(&soft).contains('」')); + assert_eq!(hard["set"]["name"], "New"); + assert_eq!(hard["set"]["hanging"], "、。,.。、"); + assert_eq!(hard["set"]["inseparable"].as_array().unwrap().len(), 5); + let none = s.execute("type.kinsokuSets.base", &json!({"base": "none"})).unwrap(); + assert_eq!(none["set"]["cannotStart"], ""); + let custom = s.execute("type.kinsokuSets.base", &json!({"base": "TIGHT"})).unwrap(); + assert_eq!(custom["set"]["cannotEnd"], "「"); + assert!(s.execute("type.kinsokuSets.base", &json!({"base": "Missing"})).is_err()); +} diff --git a/crates/engine/src/cmd/layerpanel.rs b/crates/engine/src/cmd/layerpanel.rs index 81e73326fb..b88f6ce636 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?, layersOnly?} (default: the frontmost selected object in the stacking order) 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…]}", + "{id?, layersOnly?} (default: the frontmost selected object in the stacking order) highlight the object's row; the Layers panel opens the layers around it, and scrolls to its row when the row is in the list, also when the row was already highlighted (Show Layers Only, a search, the filter, or editing an opacity mask on another layer can leave the row out) → {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 ), diff --git a/crates/engine/src/cmd/object/arrange.rs b/crates/engine/src/cmd/object/arrange.rs index 4250f3c377..a0f292fecf 100644 --- a/crates/engine/src/cmd/object/arrange.rs +++ b/crates/engine/src/cmd/object/arrange.rs @@ -334,6 +334,9 @@ pub(super) fn isolate(s: &mut Session, p: &Value) -> Result { if matches!(st.doc.node(id).ok_or(EngineError::NoNode(id))?.kind, NodeKind::Text(_)) { return Err(bad("object.isolate", "type objects can't be isolated")); } + if st.doc.node(id).is_some_and(|n| n.is_ruler_guide()) { + return Err(bad("object.isolate", "ruler guides can't be isolated")); + } let isolation = st.doc.node(id).filter(|n| n.extras().shaper.is_some()).and_then(|n| n.children()).and_then(|c| c.first()).map_or(id, |n| n.id); // A hidden or locked object, one in a hidden or locked group or layer, and a guide path while diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index 92f4744fea..0172a7466c 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -241,7 +241,7 @@ pub fn specs() -> Vec { "Enter Isolation Mode", [], None, - "{id?} isolate a group, a layer or a single object (default: the first selected object); type, a hidden or locked object, an object in a hidden or locked group or layer, and a guide path while Lock Guides is on are refused, and so is every object while an opacity mask is edited", + "{id?} isolate a group, a layer or a single object (default: the first selected object); type, a ruler guide, a hidden or locked object, an object in a hidden or locked group or layer, and a guide path while Lock Guides is on are refused, and so is every object while an opacity mask is edited", crate::cmd::maskedit::outside_mask_editing, isolate ), diff --git a/crates/engine/src/cmd/panelcmds.rs b/crates/engine/src/cmd/panelcmds.rs index 769cb530b0..13f7051223 100644 --- a/crates/engine/src/cmd/panelcmds.rs +++ b/crates/engine/src/cmd/panelcmds.rs @@ -67,7 +67,7 @@ pub fn specs() -> Vec { "Character / Paragraph", [], None, - "{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), antiAlias?: \"none\"|\"sharp\"|\"crisp\"|\"strong\" (Character panel › Anti-aliasing Method, how the type's edges are drawn as pixels; it sets each targeted type object, with or without a range; each frame of a thread keeps its own method; graph labels keep it for every label of their kind when the graph is drawn again; new type: \"sharp\"), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\", listAlign?: \"left\"|\"right\", listLevel?: 1..9 (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right; listAlign \"right\" (Bullets and Numbering…'s Alignment) puts the marker against the text, and \"left\" (the default) puts it at the first line's start, the text starting at the same place with either; it sets the paragraphs that are in a list or that the call puts in one, and a list keeps it when it changes between bullets and numbers; listLevel (Tab and Shift+Tab at the start of a list paragraph, Bullets and Numbering…'s Level) is a whole number from 1 to 9 that sets the paragraphs in a list or that the call puts in one, a list keeping it when it changes between bullets and numbers, and a list turned on without listLevel starting at level 1; each level past the first sets the paragraph 18 pt further in than its left indent, and each level counts its own numbers: a list paragraph with text sets the counts of the levels deeper than its own back to 0, so a deeper numbered paragraph after it counts from 1, and a paragraph back at a shallower level goes on with that level's count), startNumber?: 1..999999999, restartNumbering?: bool (Bullets and Numbering…'s Start At, VectorCraft's own: startNumber gives the first numbered paragraph the call touches, the first that holds text or else the first, taking the type objects in the order of `ids` and passing over a threaded frame's first paragraph when it continues from the frame before, that number, and the numbered paragraphs after it at its level count on from it, through the story's threaded frames; restartNumbering true gives it 1, and false takes the number away from every paragraph the call touches but such a continued first paragraph, which then count on from the paragraph before; giving both fails the call, and when the call touches no numbered paragraph nothing changes; a paragraph made with Return does not take the number, a paragraph made bulleted keeps none, and a paragraph style made from the paragraph does not keep it, nor does a graph label when the graph is drawn again), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"yakumonoHankaku\"|\"gyomatsuYakumonoHankaku\"|\"gyomatsuYakumonoZenkaku\"|\"yakumonoZenkaku\"|\"lineEndHalf\" (Mojikumi Set: Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), kinsokuType?: \"pushInFirst\"|\"pushOutFirst\"|\"pushOutOnly\" (Paragraph panel menu › Kinsoku Shori Type: how area type keeps those characters off a line's ends; pushInFirst sets them on the line when its gaps next to CJK characters can close up enough, by at most a tenth of an em each, pushOutFirst does so only when moving the character before them to the next line would leave the line more than an em short, and pushOutOnly, the default, moves it unless Burasagari hangs an overflowing comma or full stop; no effect with kinsoku \"none\"), bunriKinshi?: bool (Paragraph panel menu › Bunri-Kinshi: a line never breaks inside an inseparable pair, two em dashes, two horizontal ellipses, two two-dot leaders or the two halves of a vertical kana repeat mark, and justification adds no space inside one; kept but without effect with kinsoku \"none\"; off by default), kurikaeshiMojiShori?: bool (Paragraph panel menu › Kurikaeshi Moji Shori: a repeat mark 々, ゝ, ゞ, ヽ or ヾ that starts a line is drawn as the character before it, the voiced marks ゞ and ヾ as its voiced form when it has one, and the text keeps the mark; off by default), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings, as text.setRangeStyle: a tate-chu-yoko block moves up or down, right or left, and on a vertical path toward or away from the path's start, to its left or right), warichu?: bool, warichuLines?: 1..6, warichuGap?: pt 0..100, warichuScale?: % 10..100, warichuAlign?: \"auto\"|\"left\"|\"center\"|\"right\"|\"justifyLeft\"|\"justifyCenter\"|\"justifyRight\"|\"justifyAll\" (Character panel menu › Warichu and Warichu Settings, as text.setRangeStyle: the characters set smaller and stacked on lines inside their line), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options, as text.setRangeStyle: space before and after each character in reading order), tsume?: % 0..100 (Character panel › Tsume, with Show East Asian Options, as text.setRangeStyle: the share of the blank space beside each character's ink taken away, down the column for an upright character in vertical type), diacriticHorizontal?, diacriticVertical?: 1/1000 em -1000..1000 (Character panel › Adjust Horizontal and Vertical Diacritic Position, with Show Indic Options, as text.setRangeStyle: the mark glyphs among the characters move right or up relative to their letters), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, as text.setRangeStyle), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), glyphForm?: \"traditional\"|\"expert\"|\"jis04\"|\"jis90\"|\"jis78\"|\"jis83\"|\"fullWidth\"|\"halfWidth\"|\"thirdWidth\"|\"quarterWidth\"|\"default\" (Glyphs panel menu, with Show East Asian Options, as text.setRangeStyle: the characters drawn in one OpenType form of the font, or its default glyphs; a form other than \"default\" takes away their glyph choice), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference, as text.setRangeStyle: the height of the font that the size measures), language?: name|tag (Character panel › Language, as text.setRangeStyle), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font, as text.setRangeStyle: each axis named set in its units and clamped to its range, null back to the style's own setting), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), romanHangingPunctuation?: bool (Paragraph panel menu › Roman Hanging Punctuation: quotation marks, hyphens, full stops and commas starting or ending a line hang outside the margin, asterisks, tildes, ellipses, dashes, colons and semicolons by half; off by default), koreanLineBreakAnywhere?: bool (Paragraph panel menu › Korean Line Break Anywhere: a line may break between any two Hangul syllables; off, a word with Hangul in it breaks only at its spaces and punctuation, or where it is wider than the line; new type: false, paragraphs saved before the option: true), kashida?: \"none\"|\"short\"|\"medium\"|\"long\"|\"stylistic\" (Paragraph panel › Insert Kashidas: justified lines of horizontal area type lengthen each Arabic word with a kashida between its last pair of joined letters, at most a quarter, half or whole em long, or whole tatweels up to an em for stylistic, before they widen their word spaces; none by default), composer?: \"singleLine\"|\"everyLine\"|\"standardSingleLine\"|\"standardEveryLine\" (line breaking, Every-line by default; singleLine and everyLine are the Middle Eastern & South Asian composers, which shape Indic, Arabic and Hebrew type; the standard ones set it glyph by glyph as the font maps its characters, for legacy fonts that keep a script on Latin character codes), start?: byte, end?: byte} (baselineShift is in document points and hScale includes the object transform; groups include their text descendants; with a range: the character attributes style that range and the paragraph attributes apply to the paragraphs it touches; without: all the text, and graph labels keep the character and paragraph attributes for every label of their kind when the graph is drawn again, the graph still setting each label's alignment; a number or switch given as another type fails the call, and a null value leaves its attribute as it is, so a call with only null values fails with nothing to change; a call that gives the values the text already has records no undo step). Or {paragraphIndents: [{id, start: byte where the paragraph starts, leftIndent?, firstLineIndent?: pt -1296..1296}…]} alone (Tabs panel indent markers over paragraphs with indents of their own): each entry sets one paragraph of a type object, at least one indent each, at most 100000 entries; every entry is checked before anything changes, and an unknown key, a value out of range, an object that is not type, a byte where no paragraph starts or two entries for one paragraph with other values fail the call; all of it is one edit, a threaded story flowing again once, and when no paragraph's indents change nothing is recorded → {ids}", + "{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), antiAlias?: \"none\"|\"sharp\"|\"crisp\"|\"strong\" (Character panel › Anti-aliasing Method, how the type's edges are drawn as pixels; it sets each targeted type object, with or without a range; each frame of a thread keeps its own method; graph labels keep it for every label of their kind when the graph is drawn again; new type: \"sharp\"), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\", listAlign?: \"left\"|\"right\", listLevel?: 1..9 (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right; listAlign \"right\" (Bullets and Numbering…'s Alignment) puts the marker against the text, and \"left\" (the default) puts it at the first line's start, the text starting at the same place with either; it sets the paragraphs that are in a list or that the call puts in one, and a list keeps it when it changes between bullets and numbers; listLevel (Tab and Shift+Tab at the start of a list paragraph, Bullets and Numbering…'s Level) is a whole number from 1 to 9 that sets the paragraphs in a list or that the call puts in one, a list keeping it when it changes between bullets and numbers, and a list turned on without listLevel starting at level 1; each level past the first sets the paragraph 18 pt further in than its left indent, and each level counts its own numbers: a list paragraph with text sets the counts of the levels deeper than its own back to 0, so a deeper numbered paragraph after it counts from 1, and a paragraph back at a shallower level goes on with that level's count), startNumber?: 1..999999999, restartNumbering?: bool (Bullets and Numbering…'s Start At, VectorCraft's own: startNumber gives the first numbered paragraph the call touches, the first that holds text or else the first, taking the type objects in the order of `ids` and passing over a threaded frame's first paragraph when it continues from the frame before, that number, and the numbered paragraphs after it at its level count on from it, through the story's threaded frames; restartNumbering true gives it 1, and false takes the number away from every paragraph the call touches but such a continued first paragraph, which then count on from the paragraph before; giving both fails the call, and when the call touches no numbered paragraph nothing changes; a paragraph made with Return does not take the number, a paragraph made bulleted keeps none, and a paragraph style made from the paragraph does not keep it, nor does a graph label when the graph is drawn again), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"yakumonoHankaku\"|\"gyomatsuYakumonoHankaku\"|\"gyomatsuYakumonoZenkaku\"|\"yakumonoZenkaku\"|\"lineEndHalf\" (Mojikumi Set: Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\"|name of a custom set (Kinsoku Set: Soft lets 々, ー and small kana start a line; a custom set of type.kinsokuSets.list, any case, keeps its own characters off a line's start and end, hangs its own hanging punctuation with burasagari and keeps its own inseparable sequences with bunriKinshi; a name the document has no set of fails the call), kinsokuType?: \"pushInFirst\"|\"pushOutFirst\"|\"pushOutOnly\" (Paragraph panel menu › Kinsoku Shori Type: how area type keeps those characters off a line's ends; pushInFirst sets them on the line when its gaps next to CJK characters can close up enough, by at most a tenth of an em each, pushOutFirst does so only when moving the character before them to the next line would leave the line more than an em short, and pushOutOnly, the default, moves it unless Burasagari hangs the Kinsoku Set's overflowing hanging punctuation; no effect with kinsoku \"none\"), bunriKinshi?: bool (Paragraph panel menu › Bunri-Kinshi: a line never breaks inside an inseparable pair, two em dashes, two horizontal ellipses, two two-dot leaders or the two halves of a vertical kana repeat mark, or with a custom set inside one of its inseparable sequences, and justification adds no space inside one; kept but without effect with kinsoku \"none\"; off by default), kurikaeshiMojiShori?: bool (Paragraph panel menu › Kurikaeshi Moji Shori: a repeat mark 々, ゝ, ゞ, ヽ or ヾ that starts a line is drawn as the character before it, the voiced marks ゞ and ヾ as its voiced form when it has one, and the text keeps the mark; off by default), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings, as text.setRangeStyle: a tate-chu-yoko block moves up or down, right or left, and on a vertical path toward or away from the path's start, to its left or right), warichu?: bool, warichuLines?: 1..6, warichuGap?: pt 0..100, warichuScale?: % 10..100, warichuAlign?: \"auto\"|\"left\"|\"center\"|\"right\"|\"justifyLeft\"|\"justifyCenter\"|\"justifyRight\"|\"justifyAll\" (Character panel menu › Warichu and Warichu Settings, as text.setRangeStyle: the characters set smaller and stacked on lines inside their line), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options, as text.setRangeStyle: space before and after each character in reading order), tsume?: % 0..100 (Character panel › Tsume, with Show East Asian Options, as text.setRangeStyle: the share of the blank space beside each character's ink taken away, down the column for an upright character in vertical type), diacriticHorizontal?, diacriticVertical?: 1/1000 em -1000..1000 (Character panel › Adjust Horizontal and Vertical Diacritic Position, with Show Indic Options, as text.setRangeStyle: the mark glyphs among the characters move right or up relative to their letters), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, as text.setRangeStyle), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), glyphForm?: \"traditional\"|\"expert\"|\"jis04\"|\"jis90\"|\"jis78\"|\"jis83\"|\"fullWidth\"|\"halfWidth\"|\"thirdWidth\"|\"quarterWidth\"|\"default\" (Glyphs panel menu, with Show East Asian Options, as text.setRangeStyle: the characters drawn in one OpenType form of the font, or its default glyphs; a form other than \"default\" takes away their glyph choice), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference, as text.setRangeStyle: the height of the font that the size measures), language?: name|tag (Character panel › Language, as text.setRangeStyle), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font, as text.setRangeStyle: each axis named set in its units and clamped to its range, null back to the style's own setting), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: the Kinsoku Set's hanging punctuation ending an area type line hangs outside it: when it doesn't fit, or always; with None, Hard and Soft that is an East Asian comma or full stop, and a custom set hangs its own hanging characters; new type: \"standard\"), romanHangingPunctuation?: bool (Paragraph panel menu › Roman Hanging Punctuation: quotation marks, hyphens, full stops and commas starting or ending a line hang outside the margin, asterisks, tildes, ellipses, dashes, colons and semicolons by half; off by default), koreanLineBreakAnywhere?: bool (Paragraph panel menu › Korean Line Break Anywhere: a line may break between any two Hangul syllables; off, a word with Hangul in it breaks only at its spaces and punctuation, or where it is wider than the line; new type: false, paragraphs saved before the option: true), kashida?: \"none\"|\"short\"|\"medium\"|\"long\"|\"stylistic\" (Paragraph panel › Insert Kashidas: justified lines of horizontal area type lengthen each Arabic word with a kashida between its last pair of joined letters, at most a quarter, half or whole em long, or whole tatweels up to an em for stylistic, before they widen their word spaces; none by default), composer?: \"singleLine\"|\"everyLine\"|\"standardSingleLine\"|\"standardEveryLine\" (line breaking, Every-line by default; singleLine and everyLine are the Middle Eastern & South Asian composers, which shape Indic, Arabic and Hebrew type; the standard ones set it glyph by glyph as the font maps its characters, for legacy fonts that keep a script on Latin character codes), start?: byte, end?: byte} (baselineShift is in document points and hScale includes the object transform; groups include their text descendants; with a range: the character attributes style that range and the paragraph attributes apply to the paragraphs it touches; without: all the text, and graph labels keep the character and paragraph attributes for every label of their kind when the graph is drawn again, the graph still setting each label's alignment; a number or switch given as another type fails the call, and a null value leaves its attribute as it is, so a call with only null values fails with nothing to change; a call that gives the values the text already has records no undo step). Or {paragraphIndents: [{id, start: byte where the paragraph starts, leftIndent?, firstLineIndent?: pt -1296..1296}…]} alone (Tabs panel indent markers over paragraphs with indents of their own): each entry sets one paragraph of a type object, at least one indent each, at most 100000 entries; every entry is checked before anything changes, and an unknown key, a value out of range, an object that is not type, a byte where no paragraph starts or two entries for one paragraph with other values fail the call; all of it is one edit, a threaded story flowing again once, and when no paragraph's indents change nothing is recorded → {ids}", has_doc, set_format ), @@ -755,11 +755,21 @@ fn set_format(s: &mut Session, p: &Value) -> Result { }; let kinsoku = match p.get("kinsoku") { None | Some(Value::Null) => None, + // A custom set (Type › Kinsoku Shori Settings…) by name: the paragraph holds a copy of it + // and keeps Hard, which builds without custom sets read. Some(v) => Some(match v.as_str() { - Some("none") => vectorcraft_doc::Kinsoku::None, - Some("hard") => vectorcraft_doc::Kinsoku::Hard, - Some("soft") => vectorcraft_doc::Kinsoku::Soft, - _ => return Err(bad(C, "`kinsoku` must be \"none\", \"hard\" or \"soft\"")), + Some("none") => (vectorcraft_doc::Kinsoku::None, None), + Some("hard") => (vectorcraft_doc::Kinsoku::Hard, None), + Some("soft") => (vectorcraft_doc::Kinsoku::Soft, None), + name => match name.map(|n| super::kinsokusets::chosen(s, n)).transpose()?.flatten() { + Some(set) => (vectorcraft_doc::Kinsoku::Hard, Some(set)), + None => { + return Err(bad( + C, + "`kinsoku` must be \"none\", \"hard\", \"soft\" or the name of a Kinsoku set of the document (type.kinsokuSets.list)", + )); + } + }, }), }; let kinsoku_type = match p.get("kinsokuType") { @@ -1058,8 +1068,9 @@ fn set_format(s: &mut Session, p: &Value) -> Result { if let Some(v) = mojikumi { para.mojikumi = v; } - if let Some(v) = kinsoku { - para.kinsoku = v; + if let Some((v, set)) = &kinsoku { + para.kinsoku = *v; + para.kinsoku_set = set.clone(); } if let Some(v) = kinsoku_type { para.kinsoku_type = v; diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 5a10ae3d9c..fe48adce26 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -46,6 +46,8 @@ pub(super) const ALLOWED: &[&str] = &[ "addon.packaging.setRole", "addon.packaging.setRoleSwatch", "addon.pathtools.addPoints", + "addon.pathtools.boundingCircle", + "addon.pathtools.boundingRectangle", "addon.pathtools.bridge", "addon.pathtools.close", "addon.pathtools.commonTangents", @@ -557,6 +559,7 @@ pub(super) const ALLOWED: &[&str] = &[ "select.update", "shape.arc", "shape.circleThroughPoints", + "shape.curvatureCircle", "shape.editFlare", "shape.ellipse", "shape.flare", @@ -600,6 +603,7 @@ pub(super) const ALLOWED: &[&str] = &[ "swatch.move", "swatch.new", "swatch.newGroup", + "swatch.renameGroup", "swatch.resetDefaults", "swatch.setSpot", "swatch.sortByKind", @@ -623,6 +627,7 @@ pub(super) const ALLOWED: &[&str] = &[ "symbol.replace", "symbol.selectInstances", "symbol.setCurrent", + "symbol.setDensity", "symbol.sortByName", "symbol.spray", "symbol.unused", @@ -661,6 +666,7 @@ pub(super) const ALLOWED: &[&str] = &[ "text.thread.remove", "text.touchType", "threeD.addGraphic", + "threeD.mapArt", "threeD.mapGraphic", "transparency.disableOpacityMask", "transparency.editOpacityMask", @@ -684,6 +690,9 @@ pub(super) const ALLOWED: &[&str] = &[ "type.fillPlaceholder", "type.fitHeadline", "type.insert", + "type.kinsokuSets.base", + "type.kinsokuSets.list", + "type.kinsokuSets.set", "type.opticalMarginAlignment", "type.orientation.horizontal", "type.orientation.vertical", diff --git a/crates/engine/src/cmd/prefscmds.rs b/crates/engine/src/cmd/prefscmds.rs index 491284bb23..f66322498e 100644 --- a/crates/engine/src/cmd/prefscmds.rs +++ b/crates/engine/src/cmd/prefscmds.rs @@ -142,6 +142,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[ 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!("showToolCards", "General", "Options", "Show Tool Cards", bool), p!("showExternalScriptWarning", "General", "Options", "Show External Script Warning", bool), p!("antiAliasedArtwork", "General", "Options", "Anti-aliased Artwork", bool), p!("selectSameTintPercent", "General", "Options", "Select Same Tint %", bool), @@ -455,6 +456,8 @@ pub const PREF_SPECS: &[PrefSpec] = &[ choice(&[("default", "Default"), ("object", "Transform Object Only"), ("pattern", "Transform Pattern Only"), ("both", "Transform Both")]) ), p!("useRegistrationPointForSymbol", "General", "Transform Panel", "Use Registration Point for Symbol", bool), + // The Transform panel menu: drawing a shape shows the panel. + p!("showOnShapeCreation", "General", "Transform Panel", "Show on Shape Creation", bool), // The Align panel menu's Align to Glyph Bounds: Align and Distribute measure type by its glyphs' ink. p!("alignGlyphBoundsPoint", "Type", "Align to Glyph Bounds", "Point Text", bool), p!("alignGlyphBoundsArea", "Type", "Align to Glyph Bounds", "Area Text", bool), diff --git a/crates/engine/src/cmd/swatch.rs b/crates/engine/src/cmd/swatch.rs index b93c378fea..76003551cd 100644 --- a/crates/engine/src/cmd/swatch.rs +++ b/crates/engine/src/cmd/swatch.rs @@ -9,7 +9,9 @@ use vectorcraft_doc::swatches::{LinkFn, PaintFn, color_name, map_node_paints, ma use vectorcraft_doc::{Document, NodeId}; use super::paint::paint_from; -use super::{CommandSpec, Result, Session, bad, bool_or, check_numbers, check_switches, cmd, color_value, has_doc, index, ok, str_param, switch_or}; +use super::{ + CommandSpec, Result, Session, bad, bool_or, check_numbers, check_switches, cmd, color_value, has_doc, index, ok, str_param, switch_or, text_param, +}; use crate::EngineError; pub fn specs() -> Vec { @@ -106,6 +108,15 @@ pub fn specs() -> Vec { has_doc, swatch_ungroup ), + cmd!( + "swatch.renameGroup", + "Color Group Options", + ["Window", "Swatches"], + None, + "{group: color group, name: its new name (trimmed)} rename a color group, as one undo step; its swatches, their colors and the art linked to them stay as they are. Swatches and color groups share one set of names, so a name another color group or a swatch has is an error, as is an empty name; the group's own name records no undo step. A drag still in progress becomes an undo step of its own first → {name}", + has_doc, + swatch_rename_group + ), cmd!( "swatch.sortByKind", "Sort by Kind", @@ -1200,6 +1211,35 @@ fn swatch_ungroup(s: &mut Session, p: &Value) -> Result { Ok(json!({ "swatches": moved })) } +fn swatch_rename_group(s: &mut Session, p: &Value) -> Result { + const C: &str = "swatch.renameGroup"; + let group = text_param(p, "group", C)?.ok_or_else(|| bad(C, "missing `group`"))?.to_string(); + let name = text_param(p, "name", C)?.ok_or_else(|| bad(C, "missing `name`"))?.trim().to_string(); + if name.is_empty() { + return Err(bad(C, "`name` is empty")); + } + let d = &s.doc()?.doc; + if !d.swatch_groups.iter().any(|g| g.name == group) { + return Err(bad(C, format!("no colour group `{group}`"))); + } + if name == group { + return Ok(json!({ "name": name })); + } + if d.swatch_name_taken(&name) { + return Err(bad(C, format!("a swatch or color group named `{name}` already exists"))); + } + // A drag still in progress is a step of its own, so canceling or undoing it leaves the rename. + if !s.previewing && s.batch_stash.is_none() && s.in_interaction() { + super::settle_interaction(s)?; + } + s.edit("Color Group Options", |d, _| { + let g = d.swatch_groups.iter_mut().find(|g| g.name == group).ok_or_else(|| bad(C, format!("no colour group `{group}`")))?; + g.name.clone_from(&name); + Ok(()) + })?; + Ok(json!({ "name": name })) +} + fn swatch_sort_by_kind(s: &mut Session, _: &Value) -> Result { let rank = |w: &Swatch| match &w.paint { Paint::None => 0, diff --git a/crates/engine/src/cmd/textstyles.rs b/crates/engine/src/cmd/textstyles.rs index 11bd1b4259..cde1456589 100644 --- a/crates/engine/src/cmd/textstyles.rs +++ b/crates/engine/src/cmd/textstyles.rs @@ -39,13 +39,37 @@ impl Kind { /// Attributes of style `name` (the Normal style is built in: empty unless redefined). fn attrs(self, d: &Document, name: &str) -> Option> { match self.defs(d).iter().find(|s| s.name == name) { - Some(s) => Some(s.attrs.clone()), + Some(s) => { + let mut attrs = s.attrs.clone(); + if self == Kind::Para { + kinsoku_pair(&mut attrs); + } + Some(attrs) + } None if name == self.normal() => Some(Map::new()), None => None, } } } +/// The two keys of Kinsoku Set: a built-in set (`kinsoku`) and a custom set (`kinsoku_set`), which +/// goes with Hard. +const KINSOKU: [&str; 2] = ["kinsoku", "kinsoku_set"]; + +/// Paragraph style attributes `attrs` with Kinsoku Set as one attribute: one that gives only +/// `kinsoku` gets no custom set, and one that gives only `kinsoku_set` gets Hard beside it. +fn kinsoku_pair(attrs: &mut Map) { + match (attrs.contains_key(KINSOKU[0]), attrs.contains_key(KINSOKU[1])) { + (true, false) => { + attrs.insert(KINSOKU[1].into(), Value::Null); + } + (false, true) => { + attrs.insert(KINSOKU[0].into(), json!(vectorcraft_doc::Kinsoku::Hard)); + } + _ => {} + } +} + /// One command spec (the `cmd!` macro wants literals; these ids are built with `concat!`). const fn spec(id: &'static str, label: &'static str, menu: &'static [&'static str], params: &'static str, run: Run, journal: bool) -> CommandSpec { CommandSpec { id, label, menu, shortcut: None, params, enabled: has_doc, run, journal, schema: None } @@ -253,6 +277,7 @@ pub fn para_attrs(v: &ParaStyle) -> Map { ("leading_model", json!(v.leading_model)), ("burasagari", json!(v.burasagari)), ("kinsoku", json!(v.kinsoku)), + ("kinsoku_set", json!(v.kinsoku_set)), ("kinsoku_type", json!(v.kinsoku_type)), ("bunri_kinshi", json!(v.bunri_kinshi)), ("kurikaeshi_moji_shori", json!(v.kurikaeshi_moji_shori)), @@ -325,6 +350,8 @@ fn restyle( // Starts from every key `cur` writes, so values no style sets (a glyph choice) are kept. let Some(mut m) = to_map(cur) else { return cur.clone() }; m.extend(attrs(cur)); + let pair = |m: &Map| KINSOKU.map(|k| m.get(k).cloned()); + let own = pair(&m); for (k, v) in new { if old.get(k).is_none_or(|o| m.get(k) == Some(o)) { m.insert(k.clone(), v.clone()); @@ -338,6 +365,25 @@ fn restyle( m.insert(k.clone(), base_value.clone()); } } + // Kinsoku Set's two keys change together: a paragraph whose Kinsoku Set is not the old + // style's keeps its own. + let has = |m: &Map| KINSOKU.iter().any(|k| m.contains_key(*k)); + if has(old) || has(new) { + let follows = !has(old) || pair(old) == own; + let to = if !follows { + own + } else if has(new) { + pair(new) + } else { + pair(base) + }; + for (k, v) in KINSOKU.into_iter().zip(to) { + match v { + Some(v) => m.insert(k.to_string(), v), + None => m.remove(k), + }; + } + } serde_json::from_value(Value::Object(m)).unwrap_or_else(|_| cur.clone()) } @@ -359,16 +405,27 @@ fn font_change(before: &CharStyle, mut st: CharStyle, attrs: &Map /// Change text in layers, symbols, graph designs, pattern tiles, saved pattern tiles restored by /// Cancel, and brush art, including opacity masks in those trees. pub(crate) fn each_text_mut(d: &mut Document, f: &mut impl FnMut(&mut vectorcraft_doc::TextObject) -> Result<()>) -> Result<()> { + each_node_with_text_mut(d, &mut |n| match &mut n.kind { + NodeKind::Text(t) => f(t), + _ => Ok(()), + }) +} + +/// Change the nodes [`each_text_mut`] reaches: each type object and each node holding one, and each +/// graph keeping paragraph attributes for its labels, with or without labels drawn. +pub(crate) fn each_node_with_text_mut(d: &mut Document, f: &mut impl FnMut(&mut Node) -> Result<()>) -> Result<()> { fn has_text(n: &Node) -> bool { matches!(n.kind, NodeKind::Text(_)) + || n.extras().graph.as_deref().is_some_and(|g| { + let l = &g.label_styles; + l.values_para.is_some() || l.categories_para.is_some() || l.legend_para.is_some() + }) || n.extras().mask.as_ref().is_some_and(|mask| has_text(&mask.art)) || n.children().is_some_and(|children| children.iter().any(|child| has_text(child))) } - fn visit(n: &mut Node, f: &mut impl FnMut(&mut vectorcraft_doc::TextObject) -> Result<()>) -> Result<()> { - if let NodeKind::Text(t) = &mut n.kind { - f(t)?; - } + fn visit(n: &mut Node, f: &mut impl FnMut(&mut Node) -> Result<()>) -> Result<()> { + f(n)?; if let Some(mask) = n.extras_if_any().and_then(|e| e.mask.as_mut()) && has_text(&mask.art) { @@ -654,10 +711,43 @@ fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Ma } para_ranges(&st, m, kept, &c)?; sort_tabs(&mut st, m, kept); + // A custom Kinsoku set goes with Hard and has a name a custom set can have: one + // given beside None or Soft, or with a blank or built-in name, fails the call + // instead of being dropped. + if m.get("kinsoku_set").is_some_and(|v| !v.is_null()) && KINSOKU.iter().any(|k| kept.and_then(|kept| kept.get(*k)) != m.get(*k)) { + if st.kinsoku != vectorcraft_doc::Kinsoku::Hard { + return Err(bad(&c, "`kinsoku_set` goes with `kinsoku` Hard: give `kinsoku` as `hard` or leave it out")); + } + if st.kinsoku_set.is_none() { + return Err(bad(&c, "`kinsoku_set` needs the name of one of the document's Kinsoku sets")); + } + } + // A custom Kinsoku set is one of the document's, by name (any case), as + // `text.setFormat` chooses it; one the style already holds stays. + if let Some(set) = &st.kinsoku_set + && kept.and_then(|k| k.get("kinsoku_set")) != m.get("kinsoku_set") + { + let name = set.name.clone(); + let found = vectorcraft_doc::KinsokuSet::named(&d.kinsoku_sets, &name).cloned().map(std::sync::Arc::new); + st.kinsoku_set = + Some(found.ok_or_else(|| bad(&c, format!("`kinsoku_set`: the document has no Kinsoku set named `{name}`")))?); + } para_attrs(&st) } }; - Ok(Some(m.keys().filter_map(|k| full.get(k).map(|v| (k.clone(), v.clone()))).collect())) + let mut out: Map = m.keys().filter_map(|k| full.get(k).map(|v| (k.clone(), v.clone()))).collect(); + // A paragraph style giving one key of Kinsoku Set keeps both, so applying it replaces a + // paragraph's custom set or built-in set. + if kind == Kind::Para { + for k in KINSOKU { + if KINSOKU.iter().any(|g| m.contains_key(*g)) + && let Some(v) = full.get(k) + { + out.insert(k.into(), v.clone()); + } + } + } + Ok(Some(out)) } Some(_) => Err(bad(&kind.cmd(verb), "attrs must be an object")), } diff --git a/crates/engine/src/cmd/typemenu.rs b/crates/engine/src/cmd/typemenu.rs index f9c6471812..e9c316157f 100644 --- a/crates/engine/src/cmd/typemenu.rs +++ b/crates/engine/src/cmd/typemenu.rs @@ -147,7 +147,7 @@ pub fn specs() -> Vec { "Paste without Formatting", ["Edit"], Some("Cmd+Alt+V"), - "{center?, dx?, dy?, swatchConflict?} paste as edit.paste; pasted text takes the default character style (one run) and leaves its character and paragraph styles behind, as do the labels of pasted graphs, which take a new graph's label character style and paragraph attributes (keeping their alignment); a pasted graph no longer keeps its labels' character and paragraph formats, so a later redraw sets them the same way → {ids, added, merged, renamed}", + "{center?, dx?, dy?, swatchConflict?, profileMismatch?} paste as edit.paste; pasted text takes the default character style (one run) and leaves its character and paragraph styles behind, as do the labels of pasted graphs, which take a new graph's label character style and paragraph attributes (keeping their alignment); a pasted graph no longer keeps its labels' character and paragraph formats, so a later redraw sets them the same way → {ids, added, merged, renamed}", has_clipboard, paste_plain ), diff --git a/crates/engine/src/command_sets.rs b/crates/engine/src/command_sets.rs index ee594bae25..82e090a3ef 100644 --- a/crates/engine/src/command_sets.rs +++ b/crates/engine/src/command_sets.rs @@ -24,6 +24,11 @@ pub const ON_ACTIVE_ARTBOARD: [&str; 8] = [ /// `indices` instead. pub const FIT_ACTIVE_ARTBOARD: [&str; 2] = ["artboard.fitToArt", "artboard.fitToSelection"]; +/// The commands that the Rectangle, Rounded Rectangle, Ellipse, Polygon, Star and Line Segment +/// tools and their dialogs, and the Shaper tool for a shape it recognizes, run to draw a shape +/// ([`crate::Session::take_shape_drawn`]). +pub const DRAWS_SHAPE: [&str; 5] = ["shape.rectangle", "shape.ellipse", "shape.polygon", "shape.star", "shape.line"]; + /// `(command, param)` pairs the journal records only so a replay reproduces the original run /// (dates from the clock: `cmd::clock_date`; the artboards the app passes to the /// [`ON_ACTIVE_ARTBOARD`] and [`FIT_ACTIVE_ARTBOARD`] commands and to a batch; the artboards the diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index b824bebce2..c5ecee374e 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -48,7 +48,7 @@ pub struct AutomationRoots { write: Vec, } -#[derive(Debug)] +#[derive(Clone, Debug)] struct Root { /// The folder made absolute, links followed: what paths are compared with. resolved: PathBuf, @@ -128,6 +128,25 @@ impl AutomationRoots { } } + /// The roots that grant only what both `self` and `other` grant: for each kind, every root of + /// one that lies inside a root of the other. A kind left with none grants no access of its kind. + pub fn intersect(&self, other: &Self) -> Arc { + let both = |a: &[Root], b: &[Root]| { + let mut out: Vec = Vec::new(); + for r in a + .iter() + .filter(|r| b.iter().any(|o| inside(&r.resolved, &o.resolved))) + .chain(b.iter().filter(|o| a.iter().any(|r| inside(&o.resolved, &r.resolved)))) + { + if !out.iter().any(|o| o.resolved == r.resolved) { + out.push(r.clone()); + } + } + out + }; + Arc::new(Self { read: both(&self.read, &other.read), write: both(&self.write, &other.write) }) + } + /// The roots for people: `read A, B; write C` (`none` for a kind without any). pub fn describe(&self) -> String { let list = |roots: &[Root]| { @@ -223,6 +242,36 @@ impl ScopeHandle { let Self(scope, gate, exempt) = self; with_gate(gate, || with_gate_reads_exempt(exempt, || with_scope(scope, f))) } + + /// The roots in force in this scope, if any (as [`current`] gives them on its thread). + fn roots(&self) -> Option> { + match &self.0 { + Some(Scope::Confined(r)) => Some(r.clone()), + Some(Scope::Unconfined) => None, + None => PROCESS.get().cloned(), + } + } + + /// The captured scope narrowed to what the calling thread may reach as well: the roots of both + /// are in force ([`AutomationRoots::intersect`]), and without roots in either, none are. The + /// script gates of both are in force too, and reads are exempt from them only where both are. + pub fn within_current(self) -> Self { + let here = Self::capture(); + let gate = match (self.1.clone(), here.1.clone()) { + (None, None) => None, + (Some(g), None) | (None, Some(g)) => Some(g), + (Some(a), Some(b)) if Arc::ptr_eq(&a, &b) => Some(a), + (Some(a), Some(b)) => Some(Arc::new(a.followed_by(b))), + }; + let exempt = self.2 && here.2; + let scope = match (self.roots(), here.roots()) { + (None, None) => self.0, + (Some(r), None) | (None, Some(r)) => Some(Scope::Confined(r)), + (Some(a), Some(b)) if Arc::ptr_eq(&a, &b) => Some(Scope::Confined(a)), + (Some(a), Some(b)) => Some(Scope::Confined(a.intersect(&b))), + }; + Self(scope, gate, exempt) + } } /// What a command a running script runs (`vc.run`) may read and write: the places the script's @@ -235,10 +284,26 @@ pub(crate) struct ScriptGate { pub(crate) write: ScriptScope, /// The paths of the open documents' files, as the documents hold them. pub(crate) documents: Vec, + /// Another gate a path must pass as well ([`ScopeHandle::within_current`]). + pub(crate) also: Option>, } impl ScriptGate { + /// This gate with `next` at the end of its chain of `also` gates, so a path must pass every + /// gate already in the chain as well as `next`. + fn followed_by(&self, next: Arc) -> ScriptGate { + let also = match &self.also { + None => next, + Some(also) if Arc::ptr_eq(also, &next) => next, + Some(also) => Arc::new(also.followed_by(next)), + }; + ScriptGate { also: Some(also), ..self.clone() } + } + fn check(&self, path: &str, access: Access) -> Result<(), String> { + if let Some(also) = &self.also { + also.check(path, access)?; + } let real = if ScriptScope::refused_by_name(Path::new(path)) { None } else { resolve(path).ok() }; let allowed = real.is_some_and(|real| { let scoped = match access { @@ -824,6 +889,74 @@ mod tests { p.to_string_lossy().into_owned() } + /// The roots both grant: the deeper of two nested roots, nothing for roots apart, and a kind + /// only one grants is not granted. + #[test] + fn intersected_roots_grant_what_both_grant() { + let (base, roots) = folders("intersect"); + let narrow = AutomationRoots::new(&[&base.join("in/sub"), &base.join("in2")], &[]).unwrap().unwrap(); + let both = roots.intersect(&narrow); + assert_eq!(both.check(&s(base.join("in/sub/x.svg")), Access::Read), Ok(())); + assert!(both.check(&s(base.join("in/a.svg")), Access::Read).is_err(), "only the narrow root grants it"); + assert!(both.check(&s(base.join("in2")), Access::Read).is_err(), "only the narrow roots grant it"); + assert!(both.check(&s(base.join("out/x.svg")), Access::Write).is_err(), "only the first grants writes"); + assert_eq!(both.describe(), narrow.intersect(&roots).describe(), "either order"); + let unconfined = ScopeHandle(Some(Scope::Unconfined), None, false); + let within = |saved: ScopeHandle, here: Option<&Arc>| { + confine(here, || saved.within_current()).run(|| current().map(|r| r.describe())) + }; + assert_eq!(within(unconfined.clone(), Some(&narrow)), Some(narrow.describe()), "a confined caller keeps its roots"); + assert_eq!(within(ScopeHandle(Some(Scope::Confined(roots.clone())), None, false), None), Some(roots.describe()), "the saved roots stay"); + assert_eq!(within(ScopeHandle(Some(Scope::Confined(roots.clone())), None, false), Some(&narrow)), Some(both.describe())); + assert!(unconfined.run(|| current().is_none())); + let _ = std::fs::remove_dir_all(base); + } + + /// A scope narrowed to the calling thread keeps the script gate of both: a script command that + /// carries on work saved without a gate reads only what its gate allows, and with a gate saved + /// too, only what both allow; reads are exempt only where both scopes exempt them. + #[test] + fn a_narrowed_scope_keeps_the_script_gates_of_both() { + let (base, _) = folders("narrowed-gate"); + let gate = + |dir: &str| ScriptGate { read: ScriptScope::of_folder(&base.join(dir)), write: ScriptScope::default(), documents: vec![], also: None }; + let (inside, other) = (s(base.join("in/a.svg")), s(base.join("outside/secret.svg"))); + let reads = |saved: ScopeHandle, gate_here: Option| { + let narrowed = match gate_here { + Some(g) => with_script_gate(g, || saved.within_current()), + None => saved.within_current(), + }; + narrowed.run(|| (check_read(&inside).is_ok(), check_read(&other).is_ok())) + }; + let plain = ScopeHandle(None, None, false); + assert_eq!(reads(plain.clone(), Some(gate("in"))), (true, false), "the confirming command's gate"); + assert_eq!(reads(ScopeHandle(None, Some(Arc::new(gate("in"))), false), None), (true, false), "the saved gate"); + assert_eq!(reads(ScopeHandle(None, Some(Arc::new(gate("in"))), false), Some(gate("outside"))), (false, false), "both gates"); + assert_eq!(reads(ScopeHandle(None, None, true), Some(gate("in"))), (true, false), "exempt only where both are"); + assert_eq!(reads(plain, None), (true, true)); + let _ = std::fs::remove_dir_all(base); + } + + /// A scope narrowed again and again keeps every gate it was narrowed by: a gate an earlier + /// narrowing joined to the chain still refuses what it refused before. + #[test] + fn a_scope_narrowed_several_times_keeps_every_gate() { + let (base, _) = folders("narrowed-thrice"); + let gate = |dir: &Path| ScriptGate { read: ScriptScope::of_folder(dir), write: ScriptScope::default(), documents: vec![], also: None }; + let (inside, other) = (s(base.join("in/a.svg")), s(base.join("outside/secret.svg"))); + let narrow = |saved: ScopeHandle, g: ScriptGate| with_script_gate(g, || saved.within_current()); + let reads = |h: &ScopeHandle| h.clone().run(|| (check_read(&inside).is_ok(), check_read(&other).is_ok())); + let first = narrow(ScopeHandle(None, None, false), gate(&base)); + assert_eq!(reads(&first), (true, true)); + let second = narrow(first, gate(&base.join("in"))); + assert_eq!(reads(&second), (true, false), "the second gate refuses the outside file"); + let third = narrow(second, gate(&base)); + assert_eq!(reads(&third), (true, false), "the second gate is kept after a third narrowing"); + let fourth = narrow(third, gate(&base)); + assert_eq!(reads(&fourth), (true, false), "and after a fourth"); + let _ = std::fs::remove_dir_all(base); + } + #[test] fn network_paths_are_told_by_name() { for p in [r"\\server\share\x.svg", "//server/share/x.svg", r"\\?\UNC\server\share\x.svg", r"\\?\unc\server\share"] { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 94ea383690..8cc6b4084e 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -110,6 +110,9 @@ pub struct Session { /// Set while saved steps play ([`Session::replay`]): [`Session::execute`] then takes keys the /// command's params description doesn't name instead of refusing them. replaying: bool, + /// Set when a command that draws a shape was journaled outside saved steps + /// ([`Session::take_shape_drawn`]). + shape_drawn: bool, /// Set when the active tool panicked (see [`guard`]); reported by the next tool event. tool_panic: Option, /// How many times switching or closing documents, or replacing the active one, has started the @@ -411,7 +414,7 @@ mod session; pub(crate) use command_sets::SELECTS_GIVEN_IDS; #[cfg(test)] use command_sets::given_ids; -pub use command_sets::{FIT_ACTIVE_ARTBOARD, ON_ACTIVE_ARTBOARD, waits_for_tool_edit}; +pub use command_sets::{DRAWS_SHAPE, FIT_ACTIVE_ARTBOARD, ON_ACTIVE_ARTBOARD, waits_for_tool_edit}; pub use doc_state::{DocState, OpenRows, RecalledSelection}; pub use error::{EngineError, READ_ONLY_LOCATION, Result, SCRIPT_BUSY}; #[cfg(test)] diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index d2e615992a..0bf8203463 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -57,6 +57,9 @@ pub struct Prefs { pub interpolate_control_points: bool, pub use_precise_cursors: bool, pub show_tool_tips: bool, + /// General › Show Tool Cards: with tool tips on, a tool button's tool tip is a card with what the + /// tool does and its keys, for tools that have a description. + pub show_tool_cards: bool, /// Other Script… warns before it runs a chosen script. pub show_external_script_warning: bool, pub anti_aliased_artwork: bool, @@ -400,6 +403,11 @@ pub struct Prefs { /// selected, the panel and the Properties panel's Transform section measure and transform it /// from its symbol's registration point instead of the reference point. pub use_registration_point_for_symbol: bool, + /// The Transform panel menu's Show on Shape Creation: drawing a shape with the Rectangle, + /// Rounded Rectangle, Ellipse, Polygon, Star or Line Segment tool (a drag or OK in the tool's + /// dialog, also on the active perspective plane), a shape the Shaper tool recognizes, or running + /// one of [`crate::DRAWS_SHAPE`], shows the Transform panel. + pub show_on_shape_creation: bool, /// The tools' persistent options by store (a tool id, or a store a family shares: `liquify` /// holds the Liquify tools' Global Brush Dimensions), see [`vectorcraft_tools::settings`]: /// kept across tool switches and saved with the preferences. Not a Preferences dialog field: @@ -453,6 +461,7 @@ impl Default for Prefs { interpolate_control_points: false, use_precise_cursors: false, show_tool_tips: true, + show_tool_cards: false, show_external_script_warning: true, anti_aliased_artwork: true, select_same_tint_percent: false, @@ -621,6 +630,7 @@ impl Default for Prefs { single_corner_radius: true, transform_panel_patterns: "default".to_string(), use_registration_point_for_symbol: false, + show_on_shape_creation: false, tool_settings: Default::default(), perspective_presets: vec![], blend_options: None, diff --git a/crates/engine/src/sanity.rs b/crates/engine/src/sanity.rs index 4737246c9d..33738597b6 100644 --- a/crates/engine/src/sanity.rs +++ b/crates/engine/src/sanity.rs @@ -49,7 +49,8 @@ pub(crate) fn doc_sane(d: &Document, sel: &Selection) -> bool { && objects_in_range(d, &sel.objects) } -fn rect_in_range(r: vectorcraft_geom::Rect) -> bool { +/// Is every edge of `r` finite and within [`MAX_COORD`] of the origin? +pub(crate) fn rect_in_range(r: vectorcraft_geom::Rect) -> bool { [r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite() && v.abs() <= MAX_COORD) } diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 6eecfeabf8..c0694bbd81 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -457,7 +457,7 @@ impl Disk { /// The gate for a command the script runs: the places it reads and writes now, and the files of /// the open documents, `documents`. pub(crate) fn gate(&self, documents: Vec) -> crate::file_access::ScriptGate { - crate::file_access::ScriptGate { read: self.scope.clone(), write: self.writes.clone(), documents } + crate::file_access::ScriptGate { read: self.scope.clone(), write: self.writes.clone(), documents, also: None } } /// The files written since this was last asked, to name in the report. diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index d6af60fee1..e48a8f6f38 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -1,4 +1,4 @@ -use super::command_sets::{JOURNALED_READS, SELECTS_GIVEN_IDS, TAKES_GUIDE_IDS, given_ids, strip_replay_only, waits_for_tool_edit}; +use super::command_sets::{DRAWS_SHAPE, JOURNALED_READS, SELECTS_GIVEN_IDS, TAKES_GUIDE_IDS, given_ids, strip_replay_only, waits_for_tool_edit}; use super::doc_state::DocState; use super::error::{EngineError, Result}; use super::history::NamedStep; diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 2c7b19ffbb..6ad8ed586e 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -68,6 +68,7 @@ impl Session { preview_memo: Default::default(), depth: 0, replaying: false, + shape_drawn: false, tool_panic: None, tool_resets: 0, tool_set_since_reset: false, diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index ce0c2998fe..2ab7fff2d4 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -458,6 +458,7 @@ impl Session { st.last_perspective = perspective_again; } let (doc, journal, grouped) = (self.active().map(|d| d.uid), self.journal.len(), self.undo_group_docs()); + self.note_shape_drawn(&preview.0, &preview.1); self.journal.push(preview); self.journal_in_undo_groups(doc, &grouped, journal); if self.depth == 0 { diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index 3bc5c72378..046c480079 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -1,6 +1,6 @@ use super::{ - CommandSpec, EngineError, JOURNALED_READS, NodeId, Result, SELECTS_GIVEN_IDS, Selection, Session, TAKES_GUIDE_IDS, Value, cmd, find_command, - given_ids, guard, strip_replay_only, waits_for_tool_edit, + CommandSpec, DRAWS_SHAPE, EngineError, JOURNALED_READS, NodeId, Result, SELECTS_GIVEN_IDS, Selection, Session, TAKES_GUIDE_IDS, Value, cmd, + find_command, given_ids, guard, strip_replay_only, waits_for_tool_edit, }; /// A command's result `r` with the warnings of the previews that settling an interaction applied @@ -242,6 +242,7 @@ impl Session { let journaled = spec.journal || (self.depth == 0 && std::mem::take(&mut self.journal_query)); if journaled && self.depth == 0 && self.active().is_none_or(|d| d.interaction.is_none()) { let p = self.noted(params); + self.note_shape_drawn(id, &p); self.journal.push((id.to_string(), p)); } if self.depth == 0 { @@ -313,6 +314,32 @@ impl Session { self.replaying } + /// Note that journal entry `id` with `params` drew a shape ([`DRAWS_SHAPE`], also on the active + /// perspective plane as `perspective.draw` naming one, and as a step of `command.batch`), unless + /// saved steps are playing or a script runs. + pub(crate) fn note_shape_drawn(&mut self, id: &str, params: &Value) { + let shape = |id: &str| DRAWS_SHAPE.contains(&id); + let draws = |id: &str, params: Option<&Value>| { + shape(id) || (id == "perspective.draw" && params.and_then(|p| p.get("command")).and_then(Value::as_str).is_some_and(shape)) + }; + let in_batch = || { + params.get("commands").and_then(Value::as_array).is_some_and(|steps| { + steps.iter().any(|step| step.get("command").and_then(Value::as_str).is_some_and(|c| draws(c, step.get("params")))) + }) + }; + if !self.replaying && !self.script_in_run && (draws(id, Some(params)) || (id == "command.batch" && in_batch())) { + self.shape_drawn = true; + } + } + + /// Whether a shape was drawn since the last call: a drag of a shape tool that was committed, OK + /// in its dialog, or a [`DRAWS_SHAPE`] command (alone or as a batch step). Saved steps that play + /// ([`Session::replay`]) and a script's commands do not count. A frontend that shows the + /// Transform panel after a new shape asks this. + pub fn take_shape_drawn(&mut self) -> bool { + std::mem::take(&mut self.shape_drawn) + } + /// The journal from entry `start` on, as an action records it: without the params that only /// pin a replay to the original run ([`REPLAY_ONLY`]), so playing the action later acts now. pub fn journal_for_action(&self, start: usize) -> Vec<(String, Value)> { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 38692e9056..65c72cdc1c 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -44,6 +44,7 @@ mod constrain_new; mod constrain_tools; mod containers; mod css; +mod curvature_circle; mod cut; mod dashalign; mod dcs; @@ -199,6 +200,7 @@ mod swatchlib; mod symbol_nine_slice; mod symbolbounds; mod symboledit; +mod symbolism_options; mod symbollib; mod tangent_line; mod targeting; diff --git a/crates/engine/src/tests/assets_3d.rs b/crates/engine/src/tests/assets_3d.rs index d546eed793..1a647fb798 100644 --- a/crates/engine/src/tests/assets_3d.rs +++ b/crates/engine/src/tests/assets_3d.rs @@ -312,6 +312,112 @@ fn export_3d_paints_mapped_graphics_on_their_caps_in_every_format() { assert_eq!(image::load_from_memory(&png).unwrap().to_rgba8().dimensions(), (1024, 1024), "1024 pixels by default"); } +/// A blue 100 × 100 square revolved straight on about its left edge with `params`, with the red +/// 10 × 20 graphic "Mark" mapped onto its side `x` pt from the middle, collected as a 3D asset named +/// "Ball" in `format`. +fn revolved(format: &str, params: Value, x: f64) -> (Session, u64) { + let mut s = session(); + let mark = run(&mut s, "path.create", json!({"d": "M300 300L310 300L310 320L300 320Z"}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"color": "#ff0000"})); + run(&mut s, "threeD.addGraphic", json!({"name": "Mark", "ids": [mark]})); + let id = run(&mut s, "path.create", json!({"d": "M100 100L200 100L200 200L100 200Z"}))["id"].as_u64().unwrap(); + run(&mut s, "paint.setFill", json!({"color": "#0000ff"})); + let mut p = json!({"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0}); + p.as_object_mut().unwrap().extend(params.as_object().unwrap().clone()); + run(&mut s, "effect.apply", json!({"effect": "threeD.revolve", "params": p})); + run(&mut s, "threeD.mapGraphic", json!({"symbol": "Mark", "x": x, "ids": [id]})); + run(&mut s, "layer.setProps", json!({"id": id, "name": "Ball"})); + let asset = run(&mut s, "assets.add3D", json!({"ids": [id], "format": format}))["assets"][0].as_u64().unwrap(); + (s, asset) +} + +#[test] +fn export_3d_paints_graphics_mapped_onto_a_revolves_side_in_every_format() { + for (format, names) in [ + ("usda", vec!["Ball.usda", "Ball-texture-1.png"]), + ("usdz", vec!["Ball.usdz"]), + ("gltf", vec!["Ball.gltf"]), + ("obj", vec!["Ball.obj", "Ball.mtl", "Ball-texture-1.png"]), + ] { + let (mut s, _) = revolved(format, json!({}), 0.0); + let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128}))); + assert_eq!(out.iter().map(|(n, _)| n.as_str()).collect::>(), names, "{format}"); + } + // The side unrolled is 200π around the axis (the square's far edge is 100 from it) by 300 + // along the profile (its edge on the axis sweeps nothing): 512 × 245 pixels, blue with the red + // graphic at the middle. + let (mut s, _) = revolved("usda", json!({}), 0.0); + let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 512}))); + let picture = &out[1].1; + let scale = 512.0 / (200.0 * std::f64::consts::PI); + assert_eq!(image::load_from_memory(picture).unwrap().to_rgba8().dimensions(), (512, (300.0 * scale).ceil() as u32)); + let middle = (150.0 * scale) as u32; + assert!(is_red(pixel(picture, 256, middle)) && is_blue(pixel(picture, 10, 10)), "{:?}", pixel(picture, 256, middle)); + let usda = String::from_utf8(out[0].1.clone()).unwrap(); + assert_eq!((usda.matches("def Mesh").count(), usda.matches("primvars:st").count()), (1, 1), "the side is the only face"); + // Moved 50 pt around the axis, the graphic moves as far across the picture. + let (mut s, _) = revolved("usda", json!({}), 50.0); + let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 512}))); + let moved = (256.0 + 50.0 * scale).round() as u32; + assert!(is_red(pixel(&out[1].1, moved, middle)) && is_blue(pixel(&out[1].1, 256, middle))); + // An OBJ's texture coordinates stay inside the picture, as OBJ reads them (up from its bottom). + let (mut s, _) = revolved("obj", json!({}), 0.0); + let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128}))); + let obj = String::from_utf8(out[0].1.clone()).unwrap(); + let vt: Vec = obj.lines().filter_map(|l| l.strip_prefix("vt ")).flat_map(|l| l.split(' ').map(|v| v.parse::().unwrap())).collect(); + assert!(!vt.is_empty() && vt.iter().all(|v| (-1e-9..=1.0 + 1e-9).contains(v)), "{vt:?}"); + assert!(String::from_utf8(out[1].1.clone()).unwrap().contains("map_Kd -clamp on Ball-texture-1.png")); + // glTF embeds the picture, and the side's coordinates are its TEXCOORD_0. + let (mut s, _) = revolved("gltf", json!({}), 0.0); + let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128}))); + let g: Value = serde_json::from_slice(&out[0].1).unwrap(); + assert_eq!(g["images"].as_array().map(Vec::len), Some(1)); + assert!(g["meshes"].as_array().unwrap().iter().any(|m| !m["primitives"][0]["attributes"]["TEXCOORD_0"].is_null())); +} + +#[test] +fn a_partial_revolve_keeps_its_cut_sides_plain_beside_its_textured_side() { + let (mut s, asset) = revolved("usda", json!({"angle": 270.0}), 0.0); + let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128}))); + assert_eq!(out.iter().map(|(n, _)| n.as_str()).collect::>(), ["Ball.usda", "Ball-texture-1.png"]); + let usda = String::from_utf8(out[0].1.clone()).unwrap(); + assert_eq!((usda.matches("def Mesh").count(), usda.matches("primvars:st").count()), (2, 1), "the cut sides and the side"); + let d = &s.doc().unwrap().doc; + let id = d.asset(asset).unwrap().nodes[0].0; + // Without its graphics the surface is one plain mesh, as before. + run(&mut s, "select.set", json!({"ids": [id]})); + run(&mut s, "effect.setParams", json!({"index": 0, "params": {"graphics": []}})); + let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128}))); + assert_eq!(out.iter().map(|(n, _)| n.as_str()).collect::>(), ["Ball.usda"]); + assert_eq!(String::from_utf8(out[0].1.clone()).unwrap().matches("def Mesh").count(), 1); +} + +#[test] +fn a_revolved_groups_graphics_export_on_its_longest_members_side_only() { + let mut s = session(); + let mark = run(&mut s, "path.create", json!({"d": "M300 300L310 300L310 320L300 320Z"}))["id"].clone(); + run(&mut s, "threeD.addGraphic", json!({"name": "Mark", "ids": [mark]})); + let a = run(&mut s, "path.create", json!({"d": "M100 100L140 100L140 200L100 200Z"}))["id"].as_u64().unwrap(); + let b = run(&mut s, "path.create", json!({"d": "M100 120L160 120L160 130L100 130Z"}))["id"].as_u64().unwrap(); + let g = run(&mut s, "object.group", json!({"ids": [a, b]}))["id"].as_u64().unwrap(); + run(&mut s, "select.set", json!({"ids": [g]})); + run(&mut s, "effect.apply", json!({"effect": "threeD.revolve", "params": {"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0}})); + run(&mut s, "threeD.mapGraphic", json!({"symbol": "Mark", "ids": [g]})); + let d = &s.doc().unwrap().doc; + let parts = vectorcraft_render::effects::three_d_meshes_in(Some(d), d.node(vectorcraft_doc::NodeId(g)).unwrap()).unwrap(); + assert_eq!(parts.len(), 2); + let textured: Vec = parts.iter().enumerate().filter(|(_, p)| p.graphics.is_some()).map(|(k, _)| k).collect(); + assert_eq!(textured, [0], "the taller member's side"); + // A half-opaque member: as on the canvas, its opacity applies to its side and the graphics + // together, and the graphics keep the opacity of the fill. + run(&mut s, "transparency.set", json!({"ids": [a], "opacity": 50})); + let d = &s.doc().unwrap().doc; + let parts = vectorcraft_render::effects::three_d_meshes_in(Some(d), d.node(vectorcraft_doc::NodeId(g)).unwrap()).unwrap(); + let graphics = parts[0].graphics.as_ref().unwrap(); + assert_eq!((graphics.opacity, graphics.object), (1.0, 0.5)); + assert!((parts[0].color[3] - 0.5).abs() < 1e-6, "{:?}", parts[0].color); +} + #[test] fn a_texture_takes_the_opacity_of_the_fill_and_of_the_object_as_the_canvas_draws_them() { let half = |a: u8| (120..=135).contains(&a); diff --git a/crates/engine/src/tests/brushlib.rs b/crates/engine/src/tests/brushlib.rs index 38aadcc712..168cc20db8 100644 --- a/crates/engine/src/tests/brushlib.rs +++ b/crates/engine/src/tests/brushlib.rs @@ -114,6 +114,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() { "bristle-brushes", "pattern-borders", "scatter-shapes", + "stipple", "game-trails", "energy-beams", "dry-media", @@ -122,36 +123,39 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() { ] ); assert!(libs.iter().all(|l| l["category"] == "builtIn")); + // Looked up by id, so a library added to the list does not shift these checks. + let entry = |id: &str| libs.iter().find(|l| l["id"] == id).unwrap(); let lib = run(&mut s, "brush.library", json!({"library": "art ribbons"})); assert_eq!( lib["brushes"].as_array().unwrap().iter().map(|b| b["name"].as_str().unwrap()).collect::>(), ["Notched Ribbon", "Double Line", "Wave", "Teardrop", "Striped Ribbon"] ); - assert_eq!(libs[0]["count"].as_u64(), Some(5)); + assert_eq!(entry("art-ribbons")["count"].as_u64(), Some(5)); let trails = run(&mut s, "brush.library", json!({"library": "game-trails"})); assert_eq!( trails["brushes"].as_array().unwrap().iter().map(|b| b["name"].as_str().unwrap()).collect::>(), ["Speed Line", "Dash Trail", "Burst Ray", "Zigzag"] ); - assert_eq!(libs[7]["count"].as_u64(), Some(4)); + assert_eq!(entry("game-trails")["count"].as_u64(), Some(4)); let beams = run(&mut s, "brush.library", json!({"library": "energy-beams"})); assert_eq!( beams["brushes"].as_array().unwrap().iter().map(|b| b["name"].as_str().unwrap()).collect::>(), ["Laser Bolt", "Plasma Arc", "Charge Wave", "Spark Trail"] ); - assert_eq!(libs[8]["count"].as_u64(), Some(4)); + assert_eq!(entry("energy-beams")["count"].as_u64(), Some(4)); let dry = run(&mut s, "brush.library", json!({"library": "Dry Media"})); assert_eq!( dry["brushes"].as_array().unwrap().iter().map(|b| (b["name"].as_str().unwrap(), b["type"].as_str().unwrap())).collect::>(), [("Chalk Grain", "art"), ("Graphite Pencil", "art"), ("Wax Crayon", "art"), ("Charcoal Dust", "art")] ); - assert_eq!((libs[9]["name"].as_str(), libs[9]["count"].as_u64()), (Some("Dry Media"), Some(4))); + assert_eq!((entry("dry-media")["name"].as_str(), entry("dry-media")["count"].as_u64()), (Some("Dry Media"), Some(4))); let arrows = run(&mut s, "brush.library", json!({"library": "Arrows"})); assert_eq!( arrows["brushes"].as_array().unwrap().iter().map(|b| (b["name"].as_str().unwrap(), b["type"].as_str().unwrap())).collect::>(), [("Solid Arrow", "art"), ("Open Arrow", "art"), ("Double Arrow", "art"), ("Chevron Arrow", "art"), ("Dashed Arrow", "art")] ); - assert_eq!((libs[11]["name"].as_str(), libs[11]["count"].as_u64()), (Some("Arrows"), Some(5))); + assert_eq!((entry("arrows")["name"].as_str(), entry("arrows")["count"].as_u64()), (Some("Arrows"), Some(5))); + assert_eq!((entry("stipple")["name"].as_str(), entry("stipple")["count"].as_u64()), (Some("Stipple"), Some(4))); run(&mut s, "file.new", json!({"width": 200, "height": 200})); let id = run(&mut s, "shape.rectangle", json!({"x": 10, "y": 20, "width": 40, "height": 8}))["id"].as_u64().unwrap(); let added = run(&mut s, "brush.addFromLibrary", json!({"library": "energy-beams", "name": "Laser Bolt", "apply": true, "ids": [id]})); @@ -166,6 +170,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() { ("bristle-brushes", "bristle"), ("pattern-borders", "pattern"), ("scatter-shapes", "scatter"), + ("stipple", "scatter"), ("game-trails", "art"), ("energy-beams", "art"), ("dry-media", "art"), @@ -228,6 +233,54 @@ fn black_stroke() -> vectorcraft_doc::StrokeLayer { vectorcraft_doc::StrokeLayer::new(vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), 1.0) } +#[test] +fn stipple_library_draws_dot_textures_and_survives_save() { + let mut s = session(); + let (_, lib) = cmd::brushlib::library(&s, "stipple").unwrap(); + let names: Vec<&str> = lib.brushes.iter().map(|b| b.name.as_str()).collect(); + assert_eq!(names, ["Fine Stipple", "Dense Stipple", "Soft Stipple", "Bold Stipple"]); + let path = run(&mut s, "shape.line", json!({"x1": 10, "y1": 20, "x2": 210, "y2": 20}))["id"].as_u64().unwrap(); + for b in &lib.brushes { + let BrushKind::Scatter(scatter) = &b.kind else { panic!("{} is not a scatter brush", b.name) }; + assert_eq!(scatter.colorization, vectorcraft_brush::Colorization::Tints); + assert!(scatter.spacing.0 > 0.0 && scatter.spacing.1 >= scatter.spacing.0); + // A red stroke: the black dots take it as their color, and Soft Stipple's dots stay translucent. + let red = vectorcraft_color::Color::rgb(0.8, 0.1, 0.2); + let stroke = vectorcraft_doc::StrokeLayer::new(vectorcraft_color::Paint::solid(red), 1.0); + let pieces = vectorcraft_brush::stroke_pieces(&lib.doc, b, &line_to(200.0), &stroke); + let points = anchors(&pieces.iter().collect::>()); + assert!(!points.is_empty() && points.iter().all(|p| p.x.is_finite() && p.y.is_finite()), "{}", b.name); + let mut dots = vec![]; + for piece in &pieces { + piece.walk(&mut |c| { + if c.path_data().is_some() { + let fill = c.appearance.fill().unwrap_or_else(|| panic!("a {} dot has no fill", b.name)); + dots.push((fill.paint.color(), fill.opacity)); + } + }); + } + assert!(!dots.is_empty(), "{}", b.name); + for (color, opacity) in dots { + let rgb = color.unwrap_or_else(|| panic!("a {} dot is not a solid color", b.name)).to_rgb(); + assert!(rgb.iter().zip(red.to_rgb()).all(|(a, e)| (a - e).abs() < 1e-4), "{} dot is {rgb:?}, not the stroke color", b.name); + if b.name == "Soft Stipple" { + assert!(opacity > 0.0 && opacity < 1.0, "Soft Stipple dot opacity {opacity}"); + } else { + assert_eq!(opacity, 1.0, "{}", b.name); + } + } + let before = undo_len(&s); + let result = run(&mut s, "brush.addFromLibrary", json!({"library": "stipple", "name": b.name, "apply": true, "ids": [path]})); + assert_eq!(strs(&result["added"]), [b.name.as_str()]); + assert_eq!(undo_len(&s), before + 1); + assert_eq!(doc(&s).node(NodeId(path)).unwrap().appearance.stroke().unwrap().brush.as_deref(), Some(b.name.as_str())); + } + let saved = run(&mut s, "brush.saveLibrary", json!({"names": names})); + let bytes = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap(); + let reopened = vectorcraft_format::load(&bytes).unwrap(); + assert_eq!(vectorcraft_brush::library(&reopened), lib.brushes); +} + #[test] fn arrows_library_lists_renders_and_applies_original_brushes() { let mut s = session(); diff --git a/crates/engine/src/tests/brushsym.rs b/crates/engine/src/tests/brushsym.rs index 3a3a07a2c1..1d53214ec9 100644 --- a/crates/engine/src/tests/brushsym.rs +++ b/crates/engine/src/tests/brushsym.rs @@ -1572,6 +1572,79 @@ fn freehand_points_record_the_pens_tilt_bearing_and_rotation() { assert_eq!(tilt.unwrap().at(0.9), vectorcraft_doc::PressureProfile::MID, "half way over without one"); } +/// The airbrush finger wheel recorded on the stroke `id`. +fn wheel_of(s: &Session, id: NodeId) -> Option { + node(s, id).appearance.stroke().and_then(|st| st.wheel.clone()) +} + +/// `path.freehand` points carry an airbrush pen's finger wheel seventh (or as `wheel`), 0..1; the +/// stroke keeps it, a continued or reversed stroke keeps it in step, a wheel that is not a number +/// or is outside 0..1 is refused, and the Paintbrush records it from the pen. A Calligraphic brush with +/// Size on Stylus Wheel draws it, and it lasts through saving, new art leaving it behind. +#[test] +fn freehand_points_record_the_stylus_wheel() { + let mut s = session(); + let draw = |s: &mut Session, points: Value| { + NodeId(s.execute("path.freehand", &json!({"points": points, "style": "brush"})).unwrap()["id"].as_u64().unwrap()) + }; + let id = draw(&mut s, json!([[0, 50, null, null, null, null, 0], [100, 50, null, null, null, null, 1]])); + let w = wheel_of(&s, id).unwrap(); + assert!(w.at(0.0) < 1e-6 && (w.at(1.0) - 1.0).abs() < 1e-6, "{w:?}"); + assert_eq!(pose_of(&s, id), (None, None, None), "the wheel alone"); + assert_eq!(pressure_of(&s, id), None); + // As keys; a point without one is half way. + let id = draw(&mut s, json!([{"x": 0, "y": 150, "wheel": 0}, {"x": 50, "y": 150}, {"x": 100, "y": 150, "wheel": 1}])); + let w = wheel_of(&s, id).unwrap(); + assert!(w.at(0.0) < 1e-6 && (w.at(0.5) - 0.5).abs() < 1e-6 && (w.at(1.0) - 1.0).abs() < 1e-6, "{w:?}"); + // No wheel given: none recorded. + let id = draw(&mut s, json!([[0, 250, 0.5, 30, 0, 90], [100, 250, 0.5, 30, 0, 90]])); + assert_eq!(wheel_of(&s, id), None); + // Not a number: refused, and nothing drawn. + let before = s.doc().unwrap().doc.clone(); + let err = s.execute("path.freehand", &json!({"points": [[0, 0, null, null, null, null, "0.5"], [10, 0]], "style": "brush"})); + assert!(err.unwrap_err().to_string().contains("`wheel` must be a number")); + assert_eq!(s.doc().unwrap().doc.layers, before.layers, "the document is unchanged"); + // Outside 0..1: refused, and nothing drawn. + for points in [json!([{"x": 0, "y": 0, "wheel": -2}, {"x": 10, "y": 0}]), json!([[0, 0], [10, 0, null, null, null, null, 9]])] { + let err = s.execute("path.freehand", &json!({"points": points, "style": "brush"})); + assert!(err.unwrap_err().to_string().contains("`wheel` must be from 0 to 1")); + assert_eq!(s.doc().unwrap().doc.layers, before.layers, "the document is unchanged"); + } + // Continued at its end by a stroke without a wheel: the old part keeps it, the new one is half way. + let id = draw(&mut s, json!([[0, 350, null, null, null, null, 1], [100, 350, null, null, null, null, 1]])); + s.execute("path.freehand", &json!({"points": [[100, 350], [200, 350]], "style": "brush", "extend": {"id": id.0, "end": "end"}})).unwrap(); + let w = wheel_of(&s, id).unwrap(); + assert!((w.at(0.25) - 1.0).abs() < 1e-6 && (w.at(0.9) - 0.5).abs() < 1e-6, "{w:?}"); + // The Paintbrush records it, and a brush with Size on Stylus Wheel draws it. + let params = json!({"angle": 0, "roundness": 100, "size": 6, "variation": [0, 0, 4], "modes": ["fixed", "fixed", "stylusWheel"]}); + s.execute("brush.options", &json!({"name": "3 pt. Round", "params": params})).unwrap(); + s.execute("brush.setCurrent", &json!({"name": "3 pt. Round"})).unwrap(); + let v = ViewInfo::default(); + s.select_tool("paintbrush", v).unwrap(); + let strokes = |s: &mut Session, y: f64, wheel: Option| { + let pen = wheel.map(|w| PenPose { wheel: Some(w), ..PenPose::default() }); + for (k, x) in [(PointerKind::Down, 20.0), (PointerKind::Drag, 120.0), (PointerKind::Drag, 220.0), (PointerKind::Up, 320.0)] { + s.pointer(&PointerEvent { pen, ..PointerEvent::new(k, x, y) }, v).unwrap(); + } + let id = s.doc().unwrap().selection.objects[0]; + select(s, &[]); + id + }; + let far = strokes(&mut s, 500.0, Some(1.0)); + let near = strokes(&mut s, 600.0, Some(0.0)); + let mouse = strokes(&mut s, 700.0, None); + assert_eq!(wheel_of(&s, far).map(|w| w.at(0.5)), Some(1.0)); + assert_eq!(wheel_of(&s, mouse), None, "a mouse has no wheel"); + let height = |s: &Session, id| brushed_bounds(s, id).height(); + assert!((height(&s, far) - 10.0).abs() < 0.1 && (height(&s, near) - 2.0).abs() < 0.1, "{} {}", height(&s, far), height(&s, near)); + assert!((height(&s, mouse) - 6.0).abs() < 0.1, "the brush's own size: {}", height(&s, mouse)); + // Saved and reopened as it was; new art takes the look without the wheel. + let doc: Document = (*s.doc().unwrap().doc).clone(); + let back = vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap(); + assert_eq!(back.node(far).unwrap().appearance.stroke(), doc.node(far).unwrap().appearance.stroke()); + assert!(vectorcraft_doc::Appearance::clone(&doc.node(far).unwrap().appearance).without_pressure().stroke().is_some_and(|st| st.wheel.is_none())); +} + /// #764: a stroke that connects two paths joins the pen's tilt, bearing and rotation of both, the /// connected path's after the stroke's. #[test] @@ -1611,7 +1684,7 @@ fn paintbrush_records_the_pens_tilt_on_the_stroke() { select(s, &[]); id }; - let pen = strokes(&mut s, 60.0, Some(PenPose { tilt: Some([0.0, 0.0]), rotation: Some(30.0) })); + let pen = strokes(&mut s, 60.0, Some(PenPose { tilt: Some([0.0, 0.0]), rotation: Some(30.0), wheel: None })); let (tilt, bearing, rotation) = pose_of(&s, pen); assert_eq!(tilt.as_ref().map(|t| t.at(0.5)), Some(0.0), "upright"); assert!(bearing.is_some() && (rotation.unwrap().at(0.5) + 30.0).abs() < 1e-6); diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index 33483c5e21..f8ebd9a93b 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -5474,6 +5474,90 @@ fn layers_drag_into_a_nested_live_paint_group_makes_the_outer_group_again() { assert_eq!(faces(&node(&s, outer)).len(), cut, "the outer group is made after the inner one"); } +/// A Live Paint group's sources group can't be dragged out of the group, which would leave faces +/// and edges with no paths: the move is refused and changes nothing. A reorder within the group, +/// and a copy dragged out, are allowed. +#[test] +fn layers_drag_keeps_the_sources_group_in_its_live_paint_group() { + use vectorcraft_tools::builder::{faces, is_live_paint, sources}; + let mut s = session(); + let g = live(&mut s); + let layer = s.doc().unwrap().doc.parent_of(g).unwrap(); + let src = sources(&node(&s, g)).unwrap().id; + let before = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()); + let err = s.execute("layer.move", &json!({"ids": [src.0], "target": layer.0})).unwrap_err().to_string(); + assert!(err.contains("sources group stays in the group"), "{err}"); + let err = s.execute("node.move", &json!({"id": src.0, "parent": layer.0, "index": 0})).unwrap_err().to_string(); + assert!(err.contains("sources group stays in the group"), "{err}"); + assert!(s.doc().unwrap().doc == before.0, "nothing moved"); + assert_eq!(s.doc().unwrap().history.undo.len(), before.1); + s.execute("node.move", &json!({"id": src.0, "parent": g.0, "index": 99})).unwrap(); + let n = node(&s, g); + assert!(is_live_paint(&n)); + assert_eq!(sources(&n).unwrap().id, src); + assert_eq!(faces(&n).len(), 3); + s.execute("layer.move", &json!({"ids": [src.0], "target": layer.0, "copy": true})).unwrap(); + assert_eq!(s.doc().unwrap().doc.parent_of(src), Some(g), "a copy leaves the sources group where it is"); +} + +/// A shown path dragged into a hidden group among a Live Paint group's paths stops cutting its +/// faces, and dragged back out of it cuts them again. +#[test] +fn layers_drag_into_a_hidden_group_among_the_sources_makes_the_faces_again() { + use vectorcraft_tools::builder::{faces, sources}; + let mut s = session(); + let g = live(&mut s); + let first_source = |s: &Session| sources(&node(s, g)).unwrap().children().unwrap()[0].id; + let a = line_to_right_face(&mut s, 30.0); + let target = first_source(&s); + s.execute("layer.move", &json!({"ids": [a.0], "target": target.0, "place": "above"})).unwrap(); + assert_eq!(faces(&node(&s, g)).len(), 5); + let b = line_to_right_face(&mut s, 70.0); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + let hidden = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("object.hide", &json!({"ids": [hidden.0]})).unwrap(); + let target = first_source(&s); + s.execute("layer.move", &json!({"ids": [hidden.0], "target": target.0, "place": "above"})).unwrap(); + let src = sources(&node(&s, g)).unwrap().id; + assert_eq!(s.doc().unwrap().doc.parent_of(hidden), Some(src)); + assert_eq!(faces(&node(&s, g)).len(), 5, "a hidden group cuts nothing"); + s.execute("layer.move", &json!({"ids": [a.0], "target": hidden.0, "place": "inside"})).unwrap(); + assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(hidden)); + assert_eq!(faces(&node(&s, g)).len(), 3, "the path in the hidden group no longer cuts the faces"); + let target = first_source(&s); + s.execute("layer.move", &json!({"ids": [a.0], "target": target.0, "place": "above"})).unwrap(); + assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(sources(&node(&s, g)).unwrap().id)); + assert_eq!(faces(&node(&s, g)).len(), 5, "back among the shown paths, it cuts them again"); +} + +/// A Live Paint group with no paths dragged into another one with none joins it: the drop is one +/// "Merge Live Paint" step, and the group stays a Live Paint group with no faces or edges. +#[test] +fn layers_drag_of_an_empty_live_paint_group_into_another_joins_it() { + use vectorcraft_tools::builder::{edges, faces, is_live_paint, sources}; + let mut s = session(); + let empty = |s: &mut Session| { + let g = live(s); + let layer = s.doc().unwrap().doc.parent_of(g).unwrap(); + for p in sources(&node(s, g)).unwrap().children().unwrap().iter().map(|c| c.id).collect::>() { + s.execute("layer.move", &json!({"ids": [p.0], "target": layer.0})).unwrap(); + } + assert!(faces(&node(s, g)).is_empty()); + g + }; + let (g, h) = (empty(&mut s), empty(&mut s)); + let r = s.execute("layer.move", &json!({"ids": [h.0], "target": g.0, "place": "inside"})).unwrap(); + assert_eq!(r["ids"], json!([g.0])); + assert_eq!(undo_label(&s).as_deref(), Some("Merge Live Paint")); + let n = node(&s, g); + assert!(is_live_paint(&n)); + assert!(sources(&n).unwrap().children().unwrap().is_empty()); + assert!(faces(&n).is_empty() && edges(&n).is_empty()); + assert!(s.doc().unwrap().doc.node(h).is_none(), "the dropped group joined"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.node(h).is_some()); +} + /// Give Live Paint group `g` a lock, hidden state, appearance, knockout, opacity mask and /// graphic style link, and return it as it then is. fn dress_live_group(s: &mut Session, g: NodeId) -> Node { @@ -8617,6 +8701,54 @@ fn image_trace_view_is_stored_kept_and_validated() { assert!(s.execute("imageTrace.setView", &json!({"id": a.0, "view": "outlines"})).is_err()); } +/// The Split view's divider is set with the view, kept when omitted, when tracing again and through +/// save and open, adds no undo step when unchanged and one when changed, and is checked. On screen +/// the source image shows left of it and the result right of it; exports draw the result. +#[test] +fn image_trace_split_view_keeps_and_validates_its_divider() { + let mut s = session(); + let g = disc_on_blue(&mut s); + // The image covers 50 to 250 across; the disc 90 to 210, so the divider moves over the disc. + let r = s.execute("imageTrace.setView", &json!({"view": "split"})).unwrap(); + assert_eq!((r["view"].as_str(), r["split"].as_f64()), (Some("split"), Some(0.5))); + let steps = s.doc().unwrap().history.undo.len(); + let r = s.execute("imageTrace.setView", &json!({"view": "split", "split": 0.25})).unwrap(); + assert_eq!(r["split"].as_f64(), Some(0.25)); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1); + assert_eq!(node(&s, g).trace_split(), 0.25); + for same in [json!({"view": "split", "split": 0.25}), json!({"view": "split"})] { + let r = s.execute("imageTrace.setView", &same).unwrap(); + assert_eq!(r["split"].as_f64(), Some(0.25), "{same}"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "{same}: no undo step"); + } + // Pixels at y = 60 (above the disc): the image's blue left of x = 100, white right of it. + let blue = |p: [u8; 4]| p[0] < 200 && p[2] > 245; + let white = |p: [u8; 4]| p[0] > 245 && p[1] > 245 && p[2] > 245; + let screen = render_doc(&s, true); + assert!(blue(screen.pixel(60, 60)) && blue(screen.pixel(95, 60)), "{:?}", screen.pixel(95, 60)); + assert!(white(screen.pixel(105, 60)) && white(screen.pixel(240, 60)), "{:?}", screen.pixel(105, 60)); + let export = render_doc(&s, false); + assert!(white(export.pixel(60, 60)), "exports draw the tracing result"); + // Another view keeps the divider for when Split is chosen again. + s.execute("imageTrace.setView", &json!({"view": "outlines"})).unwrap(); + assert_eq!(node(&s, g).trace_split(), 0.25); + s.execute("imageTrace.setView", &json!({"view": "split"})).unwrap(); + let g = NodeId(s.execute("imageTrace.make", &json!({"id": g.0, "params": {"ignoreWhite": true, "noise": 30}})).unwrap()["id"].as_u64().unwrap()); + assert_eq!((node(&s, g).trace_view(), node(&s, g).trace_split()), (vectorcraft_doc::TraceView::Split, 0.25), "tracing again"); + let back = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + assert_eq!((back.node(g).unwrap().trace_view(), back.node(g).unwrap().trace_split()), (vectorcraft_doc::TraceView::Split, 0.25)); + // Bad dividers are refused and change nothing. + let steps = s.doc().unwrap().history.undo.len(); + for bad in [json!(-0.1), json!(1.01), json!("0.5"), json!(true), json!([0.5])] { + assert!(s.execute("imageTrace.setView", &json!({"view": "split", "split": bad})).is_err(), "{bad}"); + } + assert_eq!((s.doc().unwrap().history.undo.len(), node(&s, g).trace_split()), (steps, 0.25)); + for edge in [0.0, 1.0] { + s.execute("imageTrace.setView", &json!({"view": "split", "split": edge})).unwrap(); + assert_eq!(node(&s, g).trace_split(), edge); + } +} + #[test] fn image_trace_views_draw_on_screen_only_and_expand_to_the_result() { let mut s = session(); diff --git a/crates/engine/src/tests/curvature_circle.rs b/crates/engine/src/tests/curvature_circle.rs new file mode 100644 index 0000000000..e862a03aaf --- /dev/null +++ b/crates/engine/src/tests/curvature_circle.rs @@ -0,0 +1,226 @@ +//! `shape.curvatureCircle`: the circle that touches a path at a point and bends as the path bends +//! there, and the Curvature Circle tool that runs it. + +use serde_json::{Value, json}; +use vectorcraft_doc::LiveShape; +use vectorcraft_geom::{Point, Rect}; +use vectorcraft_tools::{Mods, PointerEvent, PointerKind}; + +use crate::*; + +const C: &str = "shape.curvatureCircle"; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + s +} + +fn undo_len(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn object_count(s: &Session) -> usize { + let mut n = 0; + s.doc().unwrap().doc.walk(|_| n += 1); + n +} + +fn id_of(v: &Value) -> NodeId { + NodeId(v["id"].as_u64().unwrap()) +} + +fn center_of(v: &Value) -> Point { + Point::new(v["cx"].as_f64().unwrap(), v["cy"].as_f64().unwrap()) +} + +/// Whether the geometric bounds of `id` are `want` to within 10⁻⁶ pt. +fn bounds_are(s: &Session, id: NodeId, want: Rect) -> bool { + let b = s.doc().unwrap().doc.bounds_of(&[id], false).unwrap(); + [(b.x0, want.x0), (b.y0, want.y0), (b.x1, want.x1), (b.y1, want.y1)].iter().all(|(a, w)| (a - w).abs() < 1e-6) +} + +/// A circle of radius 100 centered at (200, 200). +fn circle(s: &mut Session) -> NodeId { + id_of(&s.execute("shape.ellipse", &json!({"x": 100, "y": 100, "width": 200, "height": 200})).unwrap()) +} + +/// The parabola y = 200 + (x − 200)² / 200 from x = 100 to 300, one cubic: its vertex is at +/// (200, 200), where it bends with radius 100 about (200, 300). +fn parabola(s: &mut Session) -> NodeId { + let (a, b) = (166.666_666_666_666_66, 233.333_333_333_333_34); + let d = format!("M100 250 C{a} 183.333333333333334 {b} 183.333333333333334 300 250"); + id_of(&s.execute("path.create", &json!({ "d": d })).unwrap()) +} + +/// On a circle, the curvature circle is the circle itself: a live ellipse with the current paint, +/// selected, in one undo step. On the other side, it is the same size and touches the circle from +/// outside. +#[test] +fn the_curvature_circle_of_a_circle_is_the_circle() { + let mut s = session(); + let path = circle(&mut s); + let (undo, count) = (undo_len(&s), object_count(&s)); + for seg in 0..4 { + let v = s.execute(C, &json!({"id": path.0, "segment": seg, "t": 0.5})).unwrap(); + assert!(v["nominal"].as_bool().unwrap() && (v["radius"].as_f64().unwrap() - 100.0).abs() < 1e-9, "{v}"); + assert!(center_of(&v).distance(Point::new(200.0, 200.0)) < 1e-9, "{v}"); + let id = id_of(&v); + assert!(bounds_are(&s, id, Rect::new(100.0, 100.0, 300.0, 300.0))); + let node = s.doc().unwrap().doc.node(id).unwrap().clone(); + let vectorcraft_doc::NodeKind::Path { live: Some(live), .. } = &node.kind else { panic!("a live shape: {node:?}") }; + assert!(matches!(**live, LiveShape::Ellipse { .. })); + assert_eq!(s.doc().unwrap().selection.objects, vec![id]); + } + assert_eq!((undo_len(&s), object_count(&s)), (undo + 4, count + 4)); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(object_count(&s), count + 3); + let v = s.execute(C, &json!({"id": path.0, "segment": 1, "t": 0.5, "convex": true})).unwrap(); + assert!((center_of(&v).distance(Point::new(200.0, 200.0)) - 200.0).abs() < 1e-9 && (v["radius"].as_f64().unwrap() - 100.0).abs() < 1e-9, "{v}"); +} + +/// At the vertex of a parabola, the circle has the parabola's curvature, radius 100, on the side +/// it bends toward, or on the other side with `convex`. +#[test] +fn the_curvature_circle_at_a_parabola_vertex() { + let mut s = session(); + let path = parabola(&mut s); + let v = s.execute(C, &json!({"id": path.0, "segment": 0, "t": 0.5})).unwrap(); + assert!(!v["nominal"].as_bool().unwrap() && (v["radius"].as_f64().unwrap() - 100.0).abs() < 1e-6, "{v}"); + assert!(center_of(&v).distance(Point::new(200.0, 300.0)) < 1e-6, "{v}"); + let v = s.execute(C, &json!({"id": path.0, "segment": 0, "t": 0.5, "convex": true})).unwrap(); + assert!(center_of(&v).distance(Point::new(200.0, 100.0)) < 1e-6, "{v}"); +} + +/// A straight segment, a cusp, a corner anchor and a bend so slight that its circle would reach +/// past the canvas are errors, and nothing is drawn. +#[test] +fn straight_segments_cusps_and_huge_circles_are_refused() { + let mut s = session(); + let line = id_of(&s.execute("shape.line", &json!({"x1": 10, "y1": 20, "x2": 130, "y2": 70})).unwrap()); + let cusp = id_of(&s.execute("path.create", &json!({"d": "M0 0 C100 100 0 100 100 0"})).unwrap()); + let gentle = id_of(&s.execute("path.create", &json!({"d": "M0 0 C100 0.0000001 200 0.0000001 300 0"})).unwrap()); + // A curve that meets a line at a corner anchor (150, 0). + let corner = id_of(&s.execute("path.create", &json!({"d": "M0 0 C50 -50 100 -50 150 0 L300 0"})).unwrap()); + let (undo, count) = (undo_len(&s), object_count(&s)); + for (id, t, want) in [ + (line, 0.5, "the path is straight there, so no circle matches its curvature"), + (cusp, 0.5, "the path has a cusp there, so it has no single curvature"), + (corner, 1.0, "the path has a corner there, so it has no single curvature"), + (gentle, 0.5, "the circle that matches the path there would reach past the canvas"), + ] { + let e = s.execute(C, &json!({"id": id.0, "segment": 0, "t": t})).unwrap_err().to_string(); + assert!(e.contains(want), "{e}"); + } + assert_eq!((undo_len(&s), object_count(&s)), (undo, count)); +} + +/// Params that are missing or out of range are errors, and nothing is drawn. +#[test] +fn bad_params_are_refused() { + let mut s = session(); + let path = circle(&mut s); + let (undo, count) = (undo_len(&s), object_count(&s)); + for (p, want) in [ + (json!({"segment": 0, "t": 0.5}), "missing id"), + (json!({"id": path.0, "t": 0.5}), "missing segment"), + (json!({"id": path.0, "segment": 0}), "missing number `t`"), + (json!({"id": path.0, "segment": 0, "t": 1.5}), "`t` must be from 0 to 1"), + (json!({"id": path.0, "segment": 0, "t": -0.1}), "`t` must be from 0 to 1"), + (json!({"id": path.0, "segment": 0, "t": "0.5"}), "`t` must be a number"), + (json!({"id": path.0, "segment": 4, "t": 0.5}), "no such segment"), + (json!({"id": path.0, "subpath": 1, "segment": 0, "t": 0.5}), "no such subpath"), + (json!({"id": path.0, "segment": 0, "t": 0.5, "convex": "yes"}), "`convex` must be true or false"), + ] { + let e = s.execute(C, &p).unwrap_err().to_string(); + assert!(e.contains(want), "{p}: {e}"); + } + assert!(s.execute(C, &json!({"id": 9999, "segment": 0, "t": 0.5})).is_err()); + assert_eq!((undo_len(&s), object_count(&s)), (undo, count)); +} + +/// A guide has no curvature circle, as the tool leaves guides out; an error names the command. +#[test] +fn a_guide_is_refused() { + let mut s = session(); + let path = circle(&mut s); + s.execute("view.guides.make", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.node(path).unwrap().is_guide()); + let (undo, count) = (undo_len(&s), object_count(&s)); + let e = s.execute(C, &json!({"id": path.0, "segment": 0, "t": 0.5})).unwrap_err().to_string(); + assert!(e.contains("a guide has no curvature circle") && e.contains(C), "{e}"); + assert_eq!((undo_len(&s), object_count(&s)), (undo, count)); +} + +/// With Align New Objects to Pixel Grid on, the circle still touches the path where it was asked: +/// it is not pixel-aligned, so the grid does not move it. +#[test] +fn the_circle_is_not_moved_onto_the_pixel_grid() { + let mut s = session(); + s.execute("document.setup", &json!({"alignNewObjectsToPixelGrid": true})).unwrap(); + let path = id_of(&s.execute("shape.ellipse", &json!({"x": 100.3, "y": 100.2, "width": 200.4, "height": 200.4})).unwrap()); + let v = s.execute(C, &json!({"id": path.0, "segment": 0, "t": 0.5})).unwrap(); + let (c, r) = (center_of(&v), v["radius"].as_f64().unwrap()); + let id = id_of(&v); + assert!(bounds_are(&s, id, Rect::new(c.x - r, c.y - r, c.x + r, c.y + r)), "{v}"); + assert!(!s.doc().unwrap().doc.node(id).unwrap().extras().pixel_aligned); +} + +fn view() -> ViewInfo { + ViewInfo { smart_guides: false, ..ViewInfo::default() } +} + +fn click(s: &mut Session, mods: Mods, x: f64, y: f64) { + for k in [PointerKind::Move, PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(k, x, y).with_mods(mods), view()).unwrap(); + } +} + +/// With the Curvature Circle tool, a click on a path draws the circle that matches it there, in +/// one undo step; with Shift, on the other side. A click on a straight line or away from every +/// path draws nothing. +#[test] +fn the_curvature_circle_tool_draws_the_circle_where_it_clicks() { + let mut s = session(); + let path = circle(&mut s); + s.execute("shape.line", &json!({"x1": 10, "y1": 380, "x2": 390, "y2": 380})).unwrap(); + s.select_tool("curvatureCircle", view()).unwrap(); + let (undo, count) = (undo_len(&s), object_count(&s)); + click(&mut s, Mods::default(), 301.0, 200.0); + assert_eq!(undo_len(&s), undo + 1); + let id = *s.doc().unwrap().selection.objects.first().unwrap(); + assert_ne!(id, path); + assert!(bounds_are(&s, id, Rect::new(100.0, 100.0, 300.0, 300.0))); + let shift = Mods { shift: true, ..Mods::default() }; + click(&mut s, shift, 300.0, 200.0); + let id = *s.doc().unwrap().selection.objects.first().unwrap(); + assert!(bounds_are(&s, id, Rect::new(300.0, 100.0, 500.0, 300.0))); + assert_eq!(object_count(&s), count + 2); + click(&mut s, Mods::default(), 200.0, 381.0); + click(&mut s, Mods::default(), 20.0, 20.0); + assert_eq!((undo_len(&s), object_count(&s)), (undo + 2, count + 2)); +} + +/// After a click at a parabola's vertex, a click at (280, 236), 2.4 pt from the circle just drawn +/// and about 3.1 pt from the parabola, passes over that circle and draws the parabola's circle +/// there; after an Undo, the pointer reaches the circle again. +#[test] +fn the_next_click_passes_over_the_circle_the_tool_drew() { + let mut s = session(); + parabola(&mut s); + s.select_tool("curvatureCircle", view()).unwrap(); + click(&mut s, Mods::default(), 200.0, 200.0); + let first = *s.doc().unwrap().selection.objects.first().unwrap(); + assert!(bounds_are(&s, first, Rect::new(100.0, 200.0, 300.0, 400.0))); + click(&mut s, Mods::default(), 280.0, 236.0); + let second = *s.doc().unwrap().selection.objects.first().unwrap(); + assert_ne!(second, first); + let r = s.doc().unwrap().doc.bounds_of(&[second], false).unwrap().width() / 2.0; + assert!(r > 150.0, "the parabola's circle at x = 280 is larger than at its vertex: {r}"); + s.execute("edit.undo", &json!({})).unwrap(); + let count = object_count(&s); + click(&mut s, Mods::default(), 280.0, 241.0); + assert_eq!(object_count(&s), count + 1, "the circle drawn first is within reach again"); + let third = *s.doc().unwrap().selection.objects.first().unwrap(); + assert!(bounds_are(&s, third, Rect::new(100.0, 200.0, 300.0, 400.0)), "the click drew the first circle's own circle"); +} diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index dfa3e95aba..75d7d081d9 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -751,14 +751,14 @@ fn eraser_size_follows_the_pen_pressure() { assert!(err.to_string().contains("sizeMode"), "{err}"); } -/// Eraser Tool Options' Angle, Roundness and Size variation menus: a value on Rotation, Bearing, -/// Tilt or Pressure takes what the pen read along the drag, Random stays within its Variation, a +/// Eraser Tool Options' Angle, Roundness and Size variation menus: a value on Stylus Wheel, Rotation, +/// Bearing, Tilt or Pressure takes what the pen read along the drag, Random stays within its Variation, a /// drag without the reading erases at the value itself, an open path is cut where the varied tip /// covers it, and an unknown mode or a variation out of its range is refused with nothing erased. #[test] fn the_eraser_tip_varies_with_its_modes() { // Which of `probes` a level drag through the middle of a 400 by 200 rectangle erases, each of - // its points `[x, 100]` followed by `pen` ([pressure, tiltX, tiltY, rotation]). + // its points `[x, 100]` followed by `pen` ([pressure, tiltX, tiltY, rotation, wheel]). let erased = |tip: serde_json::Value, pen: serde_json::Value, probes: &[(f64, f64)]| -> Vec { let mut s = session(); rect(&mut s, 0.0, 0.0, 400.0, 200.0); @@ -785,6 +785,10 @@ fn the_eraser_tip_varies_with_its_modes() { // The barrel turned half way round reads the most, which turns the tip upright. assert_eq!(erased(on_rotation.clone(), json!([none, none, none, 180]), &probes), [true, true], "Rotation"); assert_eq!(erased(on_rotation.clone(), json!([]), &probes), [true, false], "Rotation without a reading"); + // The finger wheel at the far end of its travel reads the most; without a wheel the tip lies level. + let on_wheel = with(&level, json!({"angleMode": "stylusWheel", "angleVariation": 90})); + assert_eq!(erased(on_wheel.clone(), json!([none, none, none, none, 1.0]), &probes), [true, true], "Stylus Wheel"); + assert_eq!(erased(on_wheel, json!([none, none, none, none, none]), &probes), [true, false], "Stylus Wheel without a reading"); // Leaning to the left (a bearing of 180°) reads the most too. let on_bearing = with(&level, json!({"angleMode": "bearing", "angleVariation": 90})); assert_eq!(erased(on_bearing.clone(), json!([none, -45, 0, none]), &probes), [true, true], "Bearing"); @@ -831,11 +835,11 @@ fn the_eraser_tip_varies_with_its_modes() { let id = rect(&mut s, 0.0, 0.0, 100.0, 100.0); s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); let stroke = json!({"points": [[-10, 50], [110, 50]]}); - let modes = "\"fixed\", \"random\", \"pressure\", \"tilt\", \"bearing\" or \"rotation\""; + let modes = "\"fixed\", \"random\", \"pressure\", \"tilt\", \"bearing\", \"rotation\" or \"stylusWheel\""; for (extra, want) in [ (json!({"angleMode": "wheel"}), format!("angleMode is one of {modes}, not `wheel`")), (json!({"roundnessMode": 3}), format!("roundnessMode is one of {modes}, not 3")), - (json!({"sizeMode": "stylusWheel"}), format!("sizeMode is one of {modes}, not `stylusWheel`")), + (json!({"sizeMode": "Pressure"}), format!("sizeMode is one of {modes}, not `Pressure`")), (json!({"angleVariation": 181}), "angleVariation must be at most 180".to_string()), (json!({"roundnessVariation": 101}), "roundnessVariation must be at most 100".to_string()), (json!({"roundnessVariation": -1}), "roundnessVariation must be 0 or more".to_string()), @@ -3171,8 +3175,9 @@ fn drawing_commands_refuse_a_point_or_pressure_given_as_text() { } /// The drawing tools' commands refuse a pen pressure outside 0 to 1, a tiltX or tiltY outside -90 -/// to 90 and a rotation outside 0 to 360, naming the key, and a point array of more than six -/// numbers, naming the point; the document, the selection and the undo history stay as they were. +/// to 90, a rotation outside 0 to 360 and a stylus wheel outside 0 to 1, naming the key, and a +/// point array of more than seven numbers, naming the point; the document, the selection and the +/// undo history stay as they were. /// The ends of each range, null, one tilt axis alone and a mouse point `[x, y]` still draw. #[test] fn pen_values_outside_their_ranges_are_refused() { @@ -3194,7 +3199,8 @@ fn pen_values_outside_their_ranges_are_refused() { let tilt_x = "`tiltX` must be from -90 to 90"; let tilt_y = "`tiltY` must be from -90 to 90"; let rotation = "`rotation` must be from 0 to 360"; - let entries = "`points[3]` must be an array of at most 6 entries"; + let wheel = "`wheel` must be from 0 to 1"; + let entries = "`points[3]` must be an array of at most 7 entries"; for cmd in cmds { for (bad, want) in [ (json!([150, 150, -0.01]), pressure), @@ -3208,8 +3214,11 @@ fn pen_values_outside_their_ranges_are_refused() { (json!([150, 150, null, null, null, -1]), rotation), (json!({"x": 150, "y": 150, "rotation": 360.5}), rotation), (json!([150, 150, null, null, null, 720]), rotation), - (json!([150, 150, 0.5, 0, 0, 0, 1]), entries), - (json!([150, 150, null, null, null, null, null]), entries), + (json!([150, 150, null, null, null, null, -0.01]), wheel), + (json!([150, 150, 0.5, 0, 0, 0, 1.5]), wheel), + (json!({"x": 150, "y": 150, "wheel": 1e300}), wheel), + (json!([150, 150, 0.5, 0, 0, 0, 1, 0]), entries), + (json!([150, 150, null, null, null, null, null, null]), entries), ] { let points: Vec<_> = good.iter().cloned().chain([bad]).collect(); let sel = s.doc().unwrap().selection.clone(); @@ -3220,8 +3229,8 @@ fn pen_values_outside_their_ranges_are_refused() { for (row, cmd) in ["path.freehand", "brush.freehand", "path.blob", "path.eraseRegion"].into_iter().enumerate() { let y = 300.0 + 50.0 * row as f64; let points = json!([ - [100, y, 0, -90, 90, 0], - [150, y, 1, 90, -90, 360], + [100, y, 0, -90, 90, 0, 0], + [150, y, 1, 90, -90, 360, 1], [200, y, 0.5, null, 30], {"x": 250, "y": y, "tiltX": -45, "pressure": null}, [300, y], diff --git a/crates/engine/src/tests/journal.rs b/crates/engine/src/tests/journal.rs index 93c2390237..0b35b2f772 100644 --- a/crates/engine/src/tests/journal.rs +++ b/crates/engine/src/tests/journal.rs @@ -1290,3 +1290,132 @@ fn a_failed_preview_is_not_journaled_at_commit() { s.commit_interaction().unwrap(); assert_eq!(s.journal.len(), journal); } + +/// `take_shape_drawn` is true once after a shape tool's drag is released, a shape command runs (alone +/// or as a batch step), and false after a drag in progress, a canceled or failed one, a click (which +/// opens the tool's dialog), other commands and saved steps that play. +#[test] +fn take_shape_drawn_follows_the_shapes_that_were_drawn() { + use vectorcraft_tools::{Action, PointerEvent, PointerKind}; + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + assert!(!s.take_shape_drawn(), "a new document draws no shape"); + let v = crate::tooling::ViewInfo { smart_guides: false, ..Default::default() }; + for (tool, kind) in [ + ("rectangle", "Rectangle"), + ("roundedRectangle", "Rectangle"), + ("ellipse", "Ellipse"), + ("polygon", "Polygon"), + ("star", "Star"), + ("lineSegment", "Line"), + ] { + s.select_tool(tool, v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, 50.0, 50.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 120.0, 110.0), v).unwrap(); + assert!(!s.take_shape_drawn(), "{tool}: a drag in progress"); + s.pointer(&PointerEvent::new(PointerKind::Up, 150.0, 130.0), v).unwrap(); + assert!(s.take_shape_drawn(), "{tool} ({kind}): the released drag"); + assert!(!s.take_shape_drawn(), "{tool}: once"); + // Nothing selected, so the next press is not on the new shape's bounding box. + s.execute("select.none", &json!({})).unwrap(); + // A click asks for the tool's dialog and draws nothing yet. + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 200.0), v).unwrap(); + assert!(!s.take_shape_drawn(), "{tool}: a click"); + } + // A canceled drag, and a drag whose preview failed. + let rect = json!({"x": 10, "y": 10, "width": 40, "height": 30}); + s.apply_actions(vec![Action::Begin("Rectangle".into()), Action::Preview("shape.rectangle".into(), rect.clone()), Action::Cancel]).unwrap(); + assert!(!s.take_shape_drawn(), "a canceled drag"); + let bad = json!({"x": 10, "y": 10, "width": "wide", "height": 30}); + s.apply_actions(vec![Action::Begin("Rectangle".into()), Action::Preview("shape.rectangle".into(), bad.clone()), Action::Commit]).unwrap(); + assert!(!s.take_shape_drawn(), "a failed drag"); + // Commands: each shape command, a failed one, a batch with and without a shape, other edits. + for (id, p) in [ + ("shape.rectangle", rect.clone()), + ("shape.ellipse", rect.clone()), + ("shape.polygon", json!({"cx": 100, "cy": 100, "radius": 30})), + ("shape.star", json!({"cx": 100, "cy": 100, "radius1": 30, "radius2": 15, "points": 5})), + ("shape.line", json!({"x1": 0, "y1": 0, "x2": 50, "y2": 50})), + ] { + s.execute(id, &p).unwrap(); + assert!(s.take_shape_drawn(), "{id}"); + } + assert!(s.execute("shape.rectangle", &bad).is_err()); + assert!(!s.take_shape_drawn(), "a failed command"); + s.execute( + "command.batch", + &json!({"commands": [{"command": "shape.ellipse", "params": rect}, {"command": "object.move", "params": {"dx": 5, "dy": 0}}]}), + ) + .unwrap(); + assert!(s.take_shape_drawn(), "a batch that draws"); + s.execute("command.batch", &json!({"commands": [{"command": "object.move", "params": {"dx": 5, "dy": 0}}]})).unwrap(); + assert!(!s.take_shape_drawn(), "a batch that draws nothing"); + s.execute("shape.rectangularGrid", &json!({"x": 0, "y": 0, "width": 100, "height": 100})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.redo", &json!({})).unwrap(); + assert!(!s.take_shape_drawn(), "other commands, undo and redo"); + // Saved steps that play. + s.replay("shape.rectangle", &rect).unwrap(); + s.replay( + "command.batch", + &json!({"commands": [{"command": "shape.star", "params": {"cx": 50, "cy": 50, "radius1": 20, "radius2": 10, "points": 5}}]}), + ) + .unwrap(); + assert!(!s.take_shape_drawn(), "saved steps"); + // A script's commands. + let count = |s: &Session| s.doc().unwrap().doc.layers[0].children().map_or(0, |c| c.len()); + let shapes = count(&s); + s.execute("script.run", &json!({"source": "vc.run('shape.rectangle', {x:100,y:0,width:5,height:5});", "name": "t.js"})).unwrap(); + assert_eq!(count(&s), shapes + 1, "the script drew"); + assert!(!s.take_shape_drawn(), "a script"); +} + +/// With the perspective grid shown and a plane active, a shape tool's drag journals +/// `perspective.draw` naming the shape command: `take_shape_drawn` is true for a Rectangle drawn on +/// the plane and for `perspective.draw` naming a shape command (alone or as a batch step), and false +/// for one naming a shape outside [`crate::DRAWS_SHAPE`]. +#[test] +fn take_shape_drawn_counts_shapes_drawn_in_perspective() { + use vectorcraft_tools::{PointerEvent, PointerKind}; + let (mut s, _) = super::persp_select::persp_session(); + s.execute("perspective.grid.show", &json!({"visible": true})).unwrap(); + s.execute("perspective.plane.set", &json!({"plane": "left"})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + s.take_shape_drawn(); + let v = crate::tooling::ViewInfo { smart_guides: false, ..Default::default() }; + s.select_tool("rectangle", v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, 250.0, 350.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 280.0, 380.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 300.0, 410.0), v).unwrap(); + assert_eq!(s.journal.last().unwrap().0, "perspective.draw"); + assert!(s.take_shape_drawn(), "a Rectangle drawn on the plane"); + let rect = json!({"x": 260, "y": 360, "width": 30, "height": 30}); + s.execute("perspective.draw", &json!({"command": "shape.rectangle", "params": rect})).unwrap(); + assert!(s.take_shape_drawn(), "perspective.draw naming shape.rectangle"); + s.execute("command.batch", &json!({"commands": [{"command": "perspective.draw", "params": {"command": "shape.ellipse", "params": rect}}]})) + .unwrap(); + assert!(s.take_shape_drawn(), "a batch step drawing in perspective"); + s.execute("perspective.draw", &json!({"command": "shape.flare", "params": {"cx": 300, "cy": 380, "diameter": 40}})).unwrap(); + assert!(!s.take_shape_drawn(), "perspective.draw naming a flare"); +} + +/// Show on Shape Creation (`showOnShapeCreation`) is off until set, is set and read through +/// `prefs.set` and `prefs.get`, refuses a value that is not a boolean, and is kept with the saved +/// preferences. +#[test] +fn show_on_shape_creation_is_a_saved_preference() { + let mut s = Session::new(); + assert!(!s.prefs.show_on_shape_creation); + assert_eq!(s.execute("prefs.get", &json!({"key": "showOnShapeCreation"})).unwrap(), json!(false)); + s.execute("prefs.set", &json!({"key": "showOnShapeCreation", "value": true})).unwrap(); + assert!(s.prefs.show_on_shape_creation); + assert_eq!(s.execute("prefs.get", &json!({"key": "showOnShapeCreation"})).unwrap(), json!(true)); + assert!(s.execute("prefs.set", &json!({"key": "showOnShapeCreation", "value": "yes"})).is_err()); + assert!(s.prefs.show_on_shape_creation, "a refused value changes nothing"); + let saved = serde_json::to_value(&s.prefs).unwrap(); + assert_eq!(saved["showOnShapeCreation"], json!(true)); + let read: Prefs = serde_json::from_value(saved).unwrap(); + assert!(read.show_on_shape_creation); +} diff --git a/crates/engine/src/tests/menucmds.rs b/crates/engine/src/tests/menucmds.rs index 32ea203053..ef14bbaef9 100644 --- a/crates/engine/src/tests/menucmds.rs +++ b/crates/engine/src/tests/menucmds.rs @@ -4652,6 +4652,17 @@ fn exit_isolation_leaves_a_locked_guide_path_deselected() { assert_eq!(selected(&s), vec![g]); } +/// A ruler guide is not isolated, and isolation mode stays as it was. +#[test] +fn ruler_guides_are_not_isolated() { + let mut s = session(); + s.execute("guide.add", &json!({"vertical": true, "pos": 50})).unwrap(); + let guide = s.doc().unwrap().doc.ruler_guides()[0].id.unwrap(); + let err = s.execute("object.isolate", &json!({"id": guide.0})).unwrap_err(); + assert!(err.to_string().contains("ruler guides can't be isolated"), "{err}"); + assert_eq!(s.doc().unwrap().isolation, None); +} + /// 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 diff --git a/crates/engine/src/tests/overprint.rs b/crates/engine/src/tests/overprint.rs index 3f18ddf644..e73825e86f 100644 --- a/crates/engine/src/tests/overprint.rs +++ b/crates/engine/src/tests/overprint.rs @@ -281,6 +281,10 @@ fn overprint_black_covers_type_gradients_spots_and_groups() { /// pixel (0 full ink, 255 none). fn plate(doc: &Document, plate: &str) -> Vec { let mut r = Renderer::new(); + plate_with_renderer(&mut r, doc, plate) +} + +fn plate_with_renderer(r: &mut Renderer, doc: &Document, plate: &str) -> Vec { r.threads = 0; let seps = vectorcraft_render::proof::ProofSetup { separations: Some(vec![plate.into()]), ..Default::default() }; let opts = RenderOptions { background: Some([255, 255, 255, 255]), proof: Some(seps), ..Default::default() }; @@ -304,8 +308,18 @@ fn classic_3d_black_overprint_shades_on_the_black_plate() { let (over_doc, flat_doc) = (&over.doc().unwrap().doc, &flat.doc().unwrap().doc); let inked = |p: &[u8]| p.iter().filter(|v| **v < 250).count(); assert!(inked(&plate(over_doc, "Cyan")) > 1000, "the solid is drawn"); + for name in ["Cyan", "Magenta", "Yellow"] { + let shaded = plate(over_doc, name); + let unshaded = plate(flat_doc, name); + let changed = shaded.iter().zip(&unshaded).filter(|(s, u)| s.abs_diff(**u) > 1).count(); + assert_eq!(changed, 0, "Black Overprint changes the {name} plate"); + } assert!(inked(&plate(over_doc, "Black")) > 100, "the shading is on the black plate"); assert_eq!(inked(&plate(flat_doc, "Black")), 0, "No Shading adds no black"); + let mut renderer = Renderer::new(); + let first_cyan = plate_with_renderer(&mut renderer, over_doc, "Cyan"); + assert!(inked(&plate_with_renderer(&mut renderer, over_doc, "Black")) > 100); + assert_eq!(plate_with_renderer(&mut renderer, over_doc, "Cyan"), first_cyan, "switching plates preserves the Cyan preview"); // On screen a shaded face is the cyan darkened, not gray: the black multiplies the cyan. let image = |d: &Document| { let mut r = Renderer::new(); diff --git a/crates/engine/src/tests/package.rs b/crates/engine/src/tests/package.rs index 777db5a381..f146e39941 100644 --- a/crates/engine/src/tests/package.rs +++ b/crates/engine/src/tests/package.rs @@ -747,7 +747,9 @@ fn a_font_named_by_another_of_its_names_is_copied() { let zip = unzip(&vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap()); let report = String::from_utf8(zip["poster Folder/poster Report.txt"].clone()).unwrap(); assert!(report.contains("SourceSans3-Semibold Regular → Fonts/"), "{report}"); - let details = report.lines().find(|l| l.starts_with("SourceSans3-Semibold Regular: ")).unwrap_or_default(); + // The Font Details row: the Fonts rows above it start with the same label. + let font_details = report.split("\nFONT DETAILS\n").nth(1).unwrap_or_default(); + let details = font_details.lines().find(|l| l.starts_with("SourceSans3-Semibold Regular: ")).unwrap_or_default(); assert!(details.contains("embedding allowed") && !details.contains("missing"), "{report}"); } diff --git a/crates/engine/src/tests/stylelib.rs b/crates/engine/src/tests/stylelib.rs index e8623900fd..8f7c410edf 100644 --- a/crates/engine/src/tests/stylelib.rs +++ b/crates/engine/src/tests/stylelib.rs @@ -46,6 +46,7 @@ fn builtin_libraries_are_listed_with_original_styles_using_catalogued_effects() assert!(libs.iter().any(|l| l["id"] == "status-effects" && l["name"] == "Status Effects"), "{libs:?}"); assert!(libs.iter().any(|l| l["id"] == "textures" && l["name"] == "Textures" && l["count"] == 8), "{libs:?}"); assert!(libs.iter().any(|l| l["id"] == "neon-glow" && l["name"] == "Neon & Glow" && l["count"] == 6), "{libs:?}"); + assert!(libs.iter().any(|l| l["id"] == "paper-cutouts" && l["name"] == "Paper Cutouts" && l["count"] == 6), "{libs:?}"); for l in libs { let id = l["id"].as_str().unwrap(); let g = run(&mut s, "graphicStyle.library", json!({"library": id})); @@ -91,6 +92,24 @@ fn builtin_libraries_are_listed_with_original_styles_using_catalogued_effects() assert!(s.execute("graphicStyle.library", &json!({"library": "nope"})).is_err()); } +#[test] +fn paper_cutout_style_applies_to_an_object_and_undoes_together() { + let mut s = session(); + let id = rect(&mut s, 10.0, 20.0, 40.0, 30.0); + let before = doc(&s).node(id).unwrap().appearance.clone(); + let undo_before = undo_len(&s); + let result = + run(&mut s, "graphicStyle.addFromLibrary", json!({"library": "paper-cutouts", "name": "Coral Layers", "apply": true, "ids": [id.0]})); + assert_eq!((names(&result["added"]), result["applied"].as_str()), (vec!["Coral Layers"], Some("Coral Layers"))); + assert_eq!(undo_len(&s), undo_before + 1); + let applied = &doc(&s).node(id).unwrap().appearance; + assert_eq!(applied.items.len(), 3); + assert_eq!(applied.effects[0].id, "stylize.dropShadow"); + assert_eq!(applied.effects[0].params["blur"], 0.0); + run(&mut s, "edit.undo", json!({})); + assert_eq!(doc(&s).node(id).unwrap().appearance, before); +} + #[test] fn painted_and_sketched_styles_set_every_effect_setting_and_reopen_applied() { let mut s = session(); diff --git a/crates/engine/src/tests/swatchcmds.rs b/crates/engine/src/tests/swatchcmds.rs index 306d6b71ad..1b87639ef9 100644 --- a/crates/engine/src/tests/swatchcmds.rs +++ b/crates/engine/src/tests/swatchcmds.rs @@ -569,6 +569,72 @@ fn ungroup_and_sort_by_kind_are_one_undo_step_each() { assert_eq!(n[n.iter().position(|x| x == "Orange").unwrap() + 1], "Ocean", "the spot colour comes after the process ones, then the gradients"); } +/// Color Group Options renames a color group alone, as one undo step: its swatches, their colors +/// and the art linked to them stay as they are. A name another group or a swatch has, an empty +/// name and a parameter that is missing or not a string are errors that change nothing, and the +/// group's own name records no undo step. +#[test] +fn rename_group_renames_only_the_group_in_one_undo_step() { + let mut s = session(); + run(&mut s, "swatch.edit", json!({"name": "Bright Red", "global": true})); + let a = rect_filled(&mut s, json!({"swatch": "Bright Red"})); + let linked = fill(&s, a); + let members = names(&s, Some("Brights")); + let before = doc(&s).clone(); + let undo = undo_len(&s); + assert_eq!(run(&mut s, "swatch.renameGroup", json!({"group": "Brights", "name": " Vivid Colors "}))["name"], "Vivid Colors"); + assert!(doc(&s).swatch_groups.iter().all(|g| g.name != "Brights")); + assert_eq!(names(&s, Some("Vivid Colors")), members); + assert_eq!(fill(&s, a), linked, "linked art keeps its swatch and color"); + assert_eq!(undo_len(&s), undo + 1); + run(&mut s, "edit.undo", json!({})); + assert_eq!(*doc(&s), before); + run(&mut s, "edit.redo", json!({})); + assert_eq!(names(&s, Some("Vivid Colors")), members); + let renamed = doc(&s).clone(); + // The group's own name, trimmed, changes nothing. + assert_eq!(run(&mut s, "swatch.renameGroup", json!({"group": "Vivid Colors", "name": " Vivid Colors"}))["name"], "Vivid Colors"); + assert_eq!(undo_len(&s), undo + 1); + let refused = [ + json!({"group": "Vivid Colors", "name": "Grays"}), + json!({"group": "Vivid Colors", "name": "White"}), + json!({"group": "Vivid Colors", "name": "[None]"}), + json!({"group": "Vivid Colors", "name": "[Registration]"}), + json!({"group": "Vivid Colors", "name": ""}), + json!({"group": "Vivid Colors", "name": " "}), + json!({"group": "Vivid Colors"}), + json!({"group": "Vivid Colors", "name": null}), + json!({"group": "Vivid Colors", "name": 5}), + json!({"name": "Bold"}), + json!({"group": 5, "name": "Bold"}), + json!({"group": "Nope", "name": "Bold"}), + json!({"group": "White", "name": "Bold"}), + ]; + for p in refused { + assert!(s.execute("swatch.renameGroup", &p).is_err(), "{p}"); + assert_eq!(*doc(&s), renamed, "{p}"); + assert_eq!(undo_len(&s), undo + 1, "{p}"); + } +} + +/// A color group renamed while a drag is still in progress keeps its new name when the drag is +/// canceled: the drag becomes a step of its own first, and the rename is the next step. +#[test] +fn rename_group_during_a_drag_is_a_step_of_its_own() { + let mut s = session(); + rect_filled(&mut s, json!({"swatch": "Bright Red"})); + let undo = undo_len(&s); + s.begin_interaction("Move").unwrap(); + s.preview("object.move", &json!({"dx": 7, "dy": 0})).unwrap(); + run(&mut s, "swatch.renameGroup", json!({"group": "Brights", "name": "Vivid"})); + s.cancel_interaction().ok(); + assert!(doc(&s).swatch_groups.iter().any(|g| g.name == "Vivid"), "canceling the drag keeps the rename"); + assert_eq!(undo_len(&s), undo + 2, "the drag and the rename are two steps"); + run(&mut s, "edit.undo", json!({})); + assert!(doc(&s).swatch_groups.iter().any(|g| g.name == "Brights"), "Undo takes back the rename alone"); + assert_eq!(undo_len(&s), undo + 1); +} + #[test] fn a_cmyk_document_starts_with_cmyk_swatches_and_stores_new_colours_as_cmyk() { use vectorcraft_color::Color; diff --git a/crates/engine/src/tests/symbolism_options.rs b/crates/engine/src/tests/symbolism_options.rs new file mode 100644 index 0000000000..b8cb29f213 --- /dev/null +++ b/crates/engine/src/tests/symbolism_options.rs @@ -0,0 +1,789 @@ +//! The Symbolism Tools Options the commands take: Method and pen pressure in `symbol.adjust`, the +//! Symbol Sizer's two options, the Symbol Sprayer's `attributes`, and `symbol.setDensity`. + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, Node, NodeKind}; +use vectorcraft_geom::{Affine, Point, Rect}; + +use crate::*; + +/// A document with the 20 pt square symbol "Dot" (its first instance is at 10, 10) and nothing +/// selected. +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap(); + s.execute("symbol.new", &json!({"name": "Dot"})).unwrap(); + s.select(|_, sel| sel.clear()).unwrap(); + s +} + +/// An instance of Dot centered on (`x`, `y`), not selected. +fn dot(s: &mut Session, x: f64, y: f64) -> NodeId { + let id = NodeId(s.execute("symbol.place", &json!({"name": "Dot", "x": x, "y": y})).unwrap()["id"].as_u64().unwrap()); + s.select(|_, sel| sel.clear()).unwrap(); + id +} + +fn node(s: &Session, id: NodeId) -> Node { + s.doc().unwrap().doc.node(id).cloned().unwrap() +} + +fn bounds(s: &Session, id: NodeId) -> Rect { + node(s, id).geometric_bounds().unwrap() +} + +fn xf(s: &Session, id: NodeId) -> Affine { + match node(s, id).kind { + NodeKind::SymbolInstance { xf, .. } => xf, + other => panic!("not an instance: {other:?}"), + } +} + +fn center(s: &Session, id: NodeId) -> Point { + xf(s, id) * Point::ZERO +} + +/// The instance's rotation in radians. +fn angle(s: &Session, id: NodeId) -> f64 { + let c = xf(s, id).as_coeffs(); + c[1].atan2(c[0]) +} + +fn undo_len(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn state(s: &Session) -> (Document, usize) { + ((*s.doc().unwrap().doc).clone(), undo_len(s)) +} + +fn adjust(s: &mut Session, p: Value) -> Value { + s.execute("symbol.adjust", &p).unwrap() +} + +/// `cmd` with `p` fails with the bad-parameter message `want` and leaves the document and the +/// undo history as they were. +fn refused(s: &mut Session, cmd: &str, p: Value, want: &str) { + let before = state(s); + let r = s.execute(cmd, &p); + assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == want), "{cmd} {p}: {r:?}"); + assert!(state(s) == before, "{cmd} {p} changed the document"); +} + +/// The children of symbol set `set`. +fn members(s: &Session, set: NodeId) -> Vec { + node(s, set).children().unwrap().iter().map(|c| c.id).collect() +} + +/// Method Average brings the sizes, rotations and opacities of the instances under the brush +/// toward their mean, whichever way Alt is; User Defined changes each one by the same amount. +#[test] +fn average_brings_the_instances_under_the_brush_toward_their_mean() { + // Two instances 20 pt apart, the first grown, turned and faded alone. + let pair = || { + let mut s = session(); + let (a, b) = (dot(&mut s, 200.0, 150.0), dot(&mut s, 220.0, 150.0)); + let only_a = json!([[200, 150], [200, 150], [200, 150], [200, 150]]); + for tool in ["size", "spin", "screen"] { + adjust(&mut s, json!({"tool": tool, "points": only_a, "radius": 5, "intensity": 10})); + } + (s, a, b) + }; + let (mut s, a, b) = pair(); + let (wa, wb) = (bounds(&s, a).width(), bounds(&s, b).width()); + let (ra, oa) = (angle(&s, a), node(&s, a).opacity); + assert!(wa > wb + 1.0 && ra.abs() > 0.1 && oa < 0.9, "{wa} {wb} {ra} {oa}"); + assert_eq!((angle(&s, b), node(&s, b).opacity), (0.0, 1.0)); + // User Defined grows both by the same factor: they stay as far apart in size. + let between = json!([[210, 150], [210, 150], [210, 150]]); + let (mut user, ..) = pair(); + adjust(&mut user, json!({"tool": "size", "points": between, "radius": 40, "intensity": 10})); + let ratio = |s: &Session| xf(s, a).determinant() / xf(s, b).determinant(); + assert!((ratio(&user) - ratio(&s)).abs() < 1e-9); + // Average: the two sizes meet at their geometric mean. + let before = ratio(&s); + let product = xf(&s, a).determinant() * xf(&s, b).determinant(); + let (mut alt, ..) = pair(); + adjust(&mut s, json!({"tool": "size", "points": between, "radius": 40, "intensity": 10, "method": "average"})); + assert!((ratio(&s) - 1.0).abs() < (before - 1.0).abs() / 2.0, "{} from {before}", ratio(&s)); + assert!((xf(&s, a).determinant() * xf(&s, b).determinant() / product - 1.0).abs() < 1e-9); + adjust(&mut alt, json!({"tool": "size", "points": between, "radius": 40, "intensity": 10, "method": "average", "alt": true})); + assert_eq!([xf(&alt, a), xf(&alt, b)], [xf(&s, a), xf(&s, b)], "Alt does not reverse an average"); + // The rotations and the opacities meet too. + adjust(&mut s, json!({"tool": "spin", "points": between, "radius": 40, "intensity": 10, "method": "average"})); + let (na, nb) = (angle(&s, a), angle(&s, b)); + assert!((na - nb).abs() < ra.abs() / 2.0 && nb.abs() > 1e-3, "{na} {nb} from {ra}"); + adjust(&mut s, json!({"tool": "screen", "points": between, "radius": 40, "intensity": 10, "method": "average"})); + let (pa, pb) = (node(&s, a).opacity, node(&s, b).opacity); + assert!(pa > oa && pb < 1.0 && (pa - pb).abs() < (1.0 - oa) / 2.0, "{pa} {pb} from {oa}"); +} + +/// `tool.setOption` refuses a Method, a Symbol Sprayer option or a checkbox value the Symbolism Tools +/// Options do not have, and sets none of the values given with it. +#[test] +fn bad_symbolism_tool_options_are_refused() { + let mut s = session(); + let before = s.tool_options_of("symbolSizer"); + for (values, want) in [ + (json!({"proportional": false, "method": "smooth"}), "`method` must be one of userDefined, average, random"), + (json!({"sprayScrunch": "random"}), "`sprayScrunch` must be one of average, userDefined"), + (json!({"method": "average", "usePressure": 1}), "`usePressure` must be true or false"), + (json!({"affectsDensity": "yes"}), "`affectsDensity` must be true or false"), + ] { + let r = s.set_tool_option_cmd(&json!({"tool": "symbolSizer", "values": values})); + assert_eq!(r, Err(want.to_string()), "{values}"); + assert_eq!(s.tool_options_of("symbolSizer"), before, "{values}"); + } + s.set_tool_option_cmd(&json!({"tool": "symbolSizer", "key": "method", "value": "random"})).unwrap(); + assert_eq!(s.tool_options_of("symbolSizer")["method"], json!("random")); +} + +/// Average opacities below the Symbol Screener's least opacity (5%) stay below it: with the Screener +/// the instances meet at their mean, and a sprayed instance takes the mean of those under the brush. +#[test] +fn average_keeps_opacities_below_the_screeners_least() { + let mut s = session(); + let set = NodeId(s.execute("symbol.spray", &json!({"name": "Dot", "points": [[200, 150]], "radius": 4})).unwrap()["id"].as_u64().unwrap()); + let a = members(&s, set)[0]; + let b = dot(&mut s, 220.0, 150.0); + for (id, opacity) in [(a, 0), (b, 2)] { + s.select(|_, sel| sel.set([id])).unwrap(); + s.execute("transparency.set", &json!({"opacity": opacity})).unwrap(); + } + s.select(|_, sel| sel.set([set])).unwrap(); + // A new instance beside the invisible one takes its opacity. + s.execute("symbol.spray", &json!({"name": "Dot", "points": [[185, 150]], "radius": 20})).unwrap(); + let sprayed = *members(&s, set).last().unwrap(); + assert_eq!(node(&s, sprayed).opacity, 0.0); + // The Screener with Average brings 0% and 2% toward 1%, not up to 5%. + s.select(|_, sel| sel.clear()).unwrap(); + adjust(&mut s, json!({"tool": "screen", "points": [[210, 150]], "radius": 40, "intensity": 10, "method": "average"})); + let (pa, pb) = (node(&s, a).opacity, node(&s, b).opacity); + assert!(pa > 0.0 && pa < 0.02 && pb < 0.02 && pb > 0.0, "{pa} {pb}"); +} + +/// Average over instances that already have the mean, or a stroke over no instance, changes +/// nothing and adds no undo step. +#[test] +fn average_at_the_mean_adds_no_undo_step() { + let mut s = session(); + dot(&mut s, 200.0, 150.0); + let before = state(&s); + for tool in ["scrunch", "size", "spin", "stain", "screen", "style"] { + let r = adjust(&mut s, json!({"tool": tool, "points": [[200, 150], [202, 150]], "radius": 30, "intensity": 10, "method": "average"})); + assert_eq!(r["count"], 0, "{tool}"); + assert!(state(&s) == before, "{tool} changed the document"); + } + let r = adjust(&mut s, json!({"tool": "size", "points": [[50, 50]], "radius": 10})); + assert_eq!(r["count"], 0); + assert!(state(&s) == before); +} + +/// Average evens out the Symbol Stainer's amount and the Symbol Scruncher's spacing. +#[test] +fn average_evens_out_the_stain_and_the_spacing() { + let mut s = session(); + let (a, b, c) = (dot(&mut s, 180.0, 150.0), dot(&mut s, 200.0, 150.0), dot(&mut s, 260.0, 150.0)); + adjust(&mut s, json!({"tool": "stain", "points": [[180, 150], [180, 150]], "radius": 5, "intensity": 10, "color": "#ff0000"})); + let amount = |s: &Session, id| node(s, id).appearance.fill().map_or(0.0, |f| f.opacity); + let stained = amount(&s, a); + assert!(stained > 0.2 && amount(&s, b) == 0.0); + adjust( + &mut s, + json!({"tool": "stain", "points": [[190, 150], [190, 150]], "radius": 30, "intensity": 10, "method": "average", "color": "#0000ff"}), + ); + assert!(amount(&s, a) < stained && amount(&s, b) > 0.0, "{} {}", amount(&s, a), amount(&s, b)); + // The stained instance keeps its red, and the other takes the red of the stained one. + for id in [a, b] { + assert_eq!(node(&s, id).appearance.fill().and_then(|f| f.paint.color()).map(|c| c.to_hex()).as_deref(), Some("#ff0000")); + } + // Scrunch: the three are 20 and 60 apart; their distances from their middle even out. + let reach = |s: &Session| { + let xs = [a, b, c].map(|id| center(s, id).x); + let middle = xs.iter().sum::() / 3.0; + xs.map(|x| (x - middle).abs()) + }; + let spread = |r: [f64; 3]| r.iter().cloned().fold(0.0, f64::max) - r.iter().cloned().fold(f64::INFINITY, f64::min); + let before = spread(reach(&s)); + adjust(&mut s, json!({"tool": "scrunch", "points": [[213, 150], [213, 150]], "radius": 120, "intensity": 10, "method": "average"})); + assert!(spread(reach(&s)) < before * 0.8, "{} from {before}", spread(reach(&s))); +} + +/// Method Random gives each instance its own share of the change, the same for a stroke however +/// often it is applied; User Defined changes instances at the same distance alike. +#[test] +fn random_changes_each_instance_by_its_own_share() { + let grown = |method: Option<&str>| { + let mut s = session(); + let ids = [(180.0, 150.0), (220.0, 150.0), (200.0, 130.0), (200.0, 170.0)].map(|(x, y)| dot(&mut s, x, y)); + let mut p = json!({"tool": "size", "points": [[200, 150], [200, 150]], "radius": 60, "intensity": 10}); + if let Some(m) = method { + p["method"] = json!(m); + } + adjust(&mut s, p); + ids.map(|id| bounds(&s, id).width()) + }; + let user = grown(None); + assert!(user.iter().all(|w| (w - user[0]).abs() < 1e-9 && *w > 20.5), "{user:?}"); + assert_eq!(grown(Some("userDefined")), user); + let random = grown(Some("random")); + assert!(random.iter().any(|w| (w - random[0]).abs() > 0.05), "{random:?}"); + // From none of the User Defined change to twice it. + let twice = user[0] * user[0] / 20.0; + assert!(random.iter().all(|w| *w >= 20.0 - 1e-9 && *w <= twice + 1e-9), "{random:?} within 20..{twice}"); + assert_eq!(grown(Some("random")), random); +} + +/// With Method Random the Symbol Styler gives each instance its share of the style scaled by the +/// brush strength: at Intensity 1 a tenth of what it gives at Intensity 10. +#[test] +fn random_style_follows_the_brush_strength() { + let styled = |intensity: u32| { + let mut s = session(); + let ids = [(200.0, 150.0), (201.0, 150.0), (200.0, 151.0), (199.0, 150.0), (200.0, 149.0)].map(|(x, y)| dot(&mut s, x, y)); + let p = json!({"tool": "style", "points": [[200, 150]], "radius": 1000, "intensity": intensity, "method": "random", "color": "#ff0000"}); + adjust(&mut s, p); + ids.map(|id| f64::from(node(&s, id).appearance.fill().map_or(0.0, |f| f.opacity))) + }; + let (full, low) = (styled(10), styled(1)); + assert!(full.iter().any(|o| *o > 0.05), "{full:?}"); + for (f, l) in full.iter().zip(&low) { + assert!((l - f * 0.1).abs() < 1e-3, "{low:?} against {full:?}"); + } +} + +/// A `method` that is none of the three is an error and changes nothing; the Symbol Shifter takes +/// one and shifts as it does without. +#[test] +fn an_unknown_method_is_refused() { + let mut s = session(); + let a = dot(&mut s, 200.0, 150.0); + for (bad, shown) in [(json!("smooth"), "\"smooth\""), (json!(3), "3"), (json!(true), "true"), (json!("Average"), "\"Average\"")] { + for tool in ["size", "shift"] { + let want = format!("`method` must be userDefined, average or random, not {shown}"); + refused(&mut s, "symbol.adjust", json!({"tool": tool, "points": [[200, 150]], "method": bad}), &want); + } + } + let shifted = |method: Value| { + let mut s = session(); + let a = dot(&mut s, 200.0, 150.0); + adjust(&mut s, json!({"tool": "shift", "points": [[200, 150], [215, 150]], "intensity": 10, "method": method})); + center(&s, a) + }; + let moved = shifted(Value::Null); + assert!(moved.x > 205.0); + for method in ["average", "random", "userDefined"] { + assert_eq!(shifted(json!(method)), moved, "{method}"); + } + assert_eq!(center(&s, a), Point::new(200.0, 150.0)); +} + +/// With `usePressure` each point's pen pressure is the intensity there; without it the pressure is +/// not used. A pressure that isn't a number is an error. +#[test] +fn pen_pressure_is_the_intensity_with_use_pressure() { + let width = |points: Value, use_pressure: Option, intensity: f64| { + let mut s = session(); + let a = dot(&mut s, 200.0, 150.0); + let mut p = json!({"tool": "size", "points": points, "radius": 40, "intensity": intensity}); + if let Some(on) = use_pressure { + p["usePressure"] = json!(on); + } + let count = adjust(&mut s, p)["count"].as_u64().unwrap(); + (bounds(&s, a).width(), count) + }; + let (light, _) = width(json!([[200, 150, 0.25]]), Some(true), 5.0); + let (hard, _) = width(json!([[200, 150, 1.0]]), Some(true), 5.0); + assert!(20.0 < light && light < hard, "{light} {hard}"); + // Full pressure is intensity 10, whatever `intensity` says; a point without a pressure has 1. + assert_eq!(width(json!([[200, 150]]), None, 10.0).0, hard); + assert_eq!(width(json!([[200, 150]]), Some(true), 1.0).0, hard); + assert_eq!(width(json!([[200, 150, null]]), Some(true), 1.0).0, hard); + // No pressure: the instance stays as it is. + assert_eq!(width(json!([[200, 150, 0]]), Some(true), 5.0), (20.0, 0)); + // A pressure outside 0..1 is kept within it. + assert_eq!(width(json!([[200, 150, 7]]), Some(true), 5.0).0, hard); + // Without Use Pressure Pen the pressure is not used. + assert_eq!(width(json!([[200, 150, 0.25]]), None, 10.0).0, hard); + assert_eq!(width(json!([[200, 150, 0.25]]), Some(false), 10.0).0, hard); + let mut s = session(); + dot(&mut s, 200.0, 150.0); + for tool in ["size", "shift"] { + refused( + &mut s, + "symbol.adjust", + json!({"tool": tool, "points": [[200, 150, "hard"]], "usePressure": true}), + "a point's pressure must be a number, not \"hard\"", + ); + } + for key in ["usePressure", "proportional", "affectsDensity"] { + let mut p = json!({"tool": "size", "points": [[200, 150]]}); + p[key] = json!("yes"); + refused(&mut s, "symbol.adjust", p, &format!("`{key}` must be true or false")); + } +} + +/// The Symbol Sizer without Proportional Resizing resizes along the drag: a level drag the width, +/// an upright one the height, a click both. +#[test] +fn the_sizer_without_proportional_resizing_resizes_along_the_drag() { + let size = |points: Value, proportional: Option| { + let mut s = session(); + let a = dot(&mut s, 200.0, 150.0); + let mut p = json!({"tool": "size", "points": points, "radius": 60, "intensity": 10}); + if let Some(on) = proportional { + p["proportional"] = json!(on); + } + adjust(&mut s, p); + (bounds(&s, a).width(), bounds(&s, a).height()) + }; + let level = json!([[195, 150], [205, 150]]); + let (w, h) = size(level.clone(), Some(false)); + assert!(w > 21.0 && (h - 20.0).abs() < 1e-9, "{w} x {h}"); + let (w, h) = size(json!([[200, 145], [200, 155]]), Some(false)); + assert!(h > 21.0 && (w - 20.0).abs() < 1e-9, "{w} x {h}"); + let (w, h) = size(json!([[200, 150]]), Some(false)); + assert!(w > 20.5 && (w - h).abs() < 1e-9, "{w} x {h}"); + // Proportional Resizing (the default) keeps the shape for any drag, at the same area. + let (pw, ph) = size(level.clone(), None); + assert!(pw > 20.5 && (pw - ph).abs() < 1e-9, "{pw} x {ph}"); + assert_eq!(size(level.clone(), Some(true)), (pw, ph)); + let (w, h) = size(level, Some(false)); + assert!((w * h - pw * ph).abs() < 1e-6, "{w} x {h} against {pw} x {ph}"); +} + +/// With Resizing Affects Density an instance moves away from the brush's center as it grows and +/// toward it as it shrinks; without, it stays where it is. +#[test] +fn resizing_affects_density_moves_instances_from_the_brush_center() { + let at = |affects: Option, alt: bool| { + let mut s = session(); + let a = dot(&mut s, 220.0, 150.0); + let mut p = json!({"tool": "size", "points": [[200, 150], [200, 150]], "radius": 60, "intensity": 10, "alt": alt}); + if let Some(on) = affects { + p["affectsDensity"] = json!(on); + } + adjust(&mut s, p); + (center(&s, a), bounds(&s, a).width()) + }; + let (stays, grown) = at(None, false); + assert!((stays.x - 220.0).abs() < 1e-9 && grown > 20.5); + assert_eq!(at(Some(false), false), (stays, grown)); + let (away, width) = at(Some(true), false); + assert!(away.x > 220.5 && (away.y - 150.0).abs() < 1e-9 && width > 20.5, "{away:?}"); + let (toward, width) = at(Some(true), true); + assert!(toward.x < 219.5 && width < 19.5, "{toward:?}"); +} + +/// A new instance of the Symbol Sprayer takes the mean of the selected set's instances under the +/// brush for each attribute that is `average`, and the plain value for each that is `userDefined`. +#[test] +fn the_sprayer_gives_new_instances_the_average_or_the_user_defined_values() { + let mut s = session(); + let set = NodeId(s.execute("symbol.spray", &json!({"name": "Dot", "points": [[200, 150]], "radius": 4})).unwrap()["id"].as_u64().unwrap()); + let first = members(&s, set)[0]; + // In an area without instances an average is the plain value. + assert!(node(&s, first).opacity == 1.0 && node(&s, first).appearance.fill().is_none() && angle(&s, first) == 0.0); + // Grow, fade and stain the set's one instance. + let on_it = json!([[200, 150], [200, 150], [200, 150], [200, 150], [200, 150], [200, 150]]); + for tool in ["size", "screen", "stain"] { + adjust(&mut s, json!({"tool": tool, "points": on_it, "radius": 40, "intensity": 10, "color": "#ff0000"})); + } + let look = |s: &Session, id: NodeId| { + let n = node(s, id); + (bounds(s, id).width(), n.opacity, n.appearance.fill().map(|f| (f.paint.color().map(|c| c.to_hex()), f.opacity))) + }; + let (width, opacity, stain) = look(&s, first); + assert!(width > 24.0 && opacity < 0.7 && stain.as_ref().is_some_and(|(_, amount)| *amount > 0.5), "{width} {opacity} {stain:?}"); + let spray = |s: &mut Session, at: Value, extra: Value| { + let mut p = json!({"name": "Dot", "points": at, "radius": 30}); + for (k, v) in extra.as_object().unwrap() { + p[k] = v.clone(); + } + s.execute("symbol.spray", &p).unwrap(); + *members(s, set).last().unwrap() + }; + // Average (the default): the new instance, sprayed beside it, looks like it, at its size. + let near = spray(&mut s, json!([[215, 150]]), json!({})); + let (w, o, f) = look(&s, near); + assert!((w / width - 1.0).abs() < 1e-9, "{w} of {width}"); + assert_eq!((o, f), (opacity, stain.clone())); + // The averages of two instances that look alike are theirs. + let third = spray(&mut s, json!([[208, 165]]), json!({"attributes": {"size": "average", "screen": null}})); + assert_eq!(look(&s, third).1, opacity); + // Style: Average replaces a User Defined stain with the fill of the instances under the brush. + let mixed = spray(&mut s, json!([[205, 160]]), json!({"attributes": {"stain": "userDefined"}, "color": "#0000ff"})); + assert_eq!(look(&s, mixed).2.map(|(c, _)| c), stain.clone().map(|(c, _)| c)); + // Outside the brush's radius of every instance, the plain values: the symbol's own size. + let far = spray(&mut s, json!([[330, 250]]), json!({})); + let (w, o, f) = look(&s, far); + assert!((w / 20.0 - 1.0).abs() < 1e-9 && o == 1.0 && f.is_none(), "{w} {o} {f:?}"); + // User Defined: the symbol's size and opaque; Style: Average still gives the fill under the brush. + let user = json!({"size": "userDefined", "screen": "userDefined", "stain": "userDefined", "spin": "userDefined"}); + let plain = spray(&mut s, json!([[212, 140]]), json!({"attributes": user, "color": "#0000ff"})); + let (w, o, f) = look(&s, plain); + assert!((w / 20.0 - 1.0).abs() < 0.11 && o == 1.0, "{w} {o}"); + assert_eq!(f.map(|(c, _)| c), stain.clone().map(|(c, _)| c)); + assert_eq!(angle(&s, plain), 0.0, "one point has no direction"); + // With no fill under the brush, Stain: User Defined is the fill color in full, and a User Defined + // style without a fill (the document has only the default style) leaves it. + let blue = spray(&mut s, json!([[330, 40]]), json!({"attributes": user, "color": "#0000ff"})); + assert_eq!(look(&s, blue).2, Some((Some("#0000ff".to_string()), 1.0))); + let styled = json!({"stain": "userDefined", "style": "userDefined"}); + let blue = spray(&mut s, json!([[330, 100]]), json!({"attributes": styled, "color": "#0000ff"})); + assert_eq!(look(&s, blue).2, Some((Some("#0000ff".to_string()), 1.0))); + // Spin: User Defined turns the instances the way the stroke runs (here: down the page). + let down = spray(&mut s, json!([[100, 40], [100, 140]]), json!({"attributes": {"spin": "userDefined"}})); + assert!((angle(&s, down) - std::f64::consts::FRAC_PI_2).abs() < 1e-9, "{}", angle(&s, down)); + let level = spray(&mut s, json!([[40, 260], [140, 260]]), json!({})); + assert_eq!(angle(&s, level), 0.0, "Average, with no instance under the brush"); +} + +/// Size: Average is a size on the page, the same measure for every symbol: a 20 pt symbol sprayed +/// beside an 80 pt one is 80 pt, and the Sizer brings the two to 40 pt. With no instance under the +/// brush a sprayed instance has its symbol's own size, whatever `scale` is. +#[test] +fn average_sizes_are_sizes_on_the_page_for_every_symbol() { + let mut s = session(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 200, "width": 80, "height": 80})).unwrap(); + s.execute("symbol.new", &json!({"name": "Big"})).unwrap(); + s.select(|_, sel| sel.clear()).unwrap(); + let set = NodeId(s.execute("symbol.spray", &json!({"name": "Big", "points": [[200, 150]], "radius": 4})).unwrap()["id"].as_u64().unwrap()); + let big = members(&s, set)[0]; + assert!((bounds(&s, big).width() - 80.0).abs() < 1e-9); + let spray = |s: &mut Session, at: Value| { + s.execute("symbol.spray", &json!({"name": "Dot", "points": at, "radius": 30, "scale": 2})).unwrap(); + *members(s, set).last().unwrap() + }; + let near = spray(&mut s, json!([[215, 150]])); + assert!((bounds(&s, near).width() - 80.0).abs() < 1e-9, "{}", bounds(&s, near).width()); + let far = spray(&mut s, json!([[350, 40]])); + assert!((bounds(&s, far).width() - 20.0).abs() < 1e-9, "{}", bounds(&s, far).width()); + // The Sizer: an unscaled Dot and an unscaled Big meet at the geometric mean of 20 and 80. + let mut s = session(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 200, "width": 80, "height": 80})).unwrap(); + s.execute("symbol.new", &json!({"name": "Big"})).unwrap(); + s.select(|_, sel| sel.clear()).unwrap(); + let small = dot(&mut s, 200.0, 150.0); + let big = NodeId(s.execute("symbol.place", &json!({"name": "Big", "x": 220, "y": 150})).unwrap()["id"].as_u64().unwrap()); + s.select(|_, sel| sel.clear()).unwrap(); + let between = json!([[210, 150], [210, 150], [210, 150], [210, 150], [210, 150], [210, 150]]); + adjust(&mut s, json!({"tool": "size", "points": between, "radius": 30, "intensity": 10, "method": "average"})); + let (ws, wb) = (bounds(&s, small).width(), bounds(&s, big).width()); + assert!(ws > 30.0 && wb < 55.0 && (ws * wb / 1600.0 - 1.0).abs() < 1e-9, "{ws} {wb}"); + // A symbol without a recorded size is measured by its art: here 80 pt art drawn at its own size. + let mut s = session(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 200, "width": 20, "height": 20})).unwrap(); + s.execute("symbol.new", &json!({"name": "Loose"})).unwrap(); + s.edit("Forget size", |d, _| { + if let Some(m) = d.unknown.get_mut(vectorcraft_doc::SYMBOL_SIZES).and_then(Value::as_object_mut) { + m.remove("Loose"); + } + for sym in d.symbols.iter_mut().filter(|sym| sym.name == "Loose") { + std::sync::Arc::make_mut(&mut sym.art).transform(Affine::scale(4.0), false); + } + Ok(()) + }) + .unwrap(); + s.select(|_, sel| sel.clear()).unwrap(); + let small = dot(&mut s, 200.0, 150.0); + let loose = NodeId(s.execute("symbol.place", &json!({"name": "Loose", "x": 220, "y": 150})).unwrap()["id"].as_u64().unwrap()); + s.select(|_, sel| sel.clear()).unwrap(); + // Its width as drawn, measured by its symbol's art. + let drawn = |s: &Session| { + let d = &s.doc().unwrap().doc; + node(s, loose).geometric_bounds_with(&d.symbol_boxes()).unwrap().width() + }; + assert!((drawn(&s) - 80.0).abs() < 1e-9, "{}", drawn(&s)); + adjust(&mut s, json!({"tool": "size", "points": between, "radius": 30, "intensity": 10, "method": "average"})); + let (ws, wl) = (bounds(&s, small).width(), drawn(&s)); + assert!(ws > 30.0 && wl < 55.0, "{ws} {wl}"); + // A new set sprayed with Size: Average is spaced by the size it is placed at, not by `scale`. + s.select(|_, sel| sel.clear()).unwrap(); + let stroke: Vec = (0..50).map(|i| json!([100.0 + 4.0 * f64::from(i), 20.0])).collect(); + let r = s.execute("symbol.spray", &json!({"name": "Dot", "points": stroke, "radius": 2, "scale": 100})).unwrap(); + assert!(r["count"].as_u64().unwrap() > 5, "{r}"); + // The 80 pt art of a symbol without a recorded size spaces new instances by its own size. + s.select(|_, sel| sel.clear()).unwrap(); + let stroke: Vec = (0..50).map(|i| json!([100.0 + 4.0 * f64::from(i), 280.0])).collect(); + let r = s.execute("symbol.spray", &json!({"name": "Loose", "points": stroke, "radius": 2})).unwrap(); + assert!(r["count"].as_u64().unwrap() <= 5, "{r}"); +} + +/// Spin: Average turns a new instance to the mean direction of the instances under the brush, and +/// Scrunch: Average spaces new instances as those under the brush are spaced. +#[test] +fn the_sprayer_averages_rotation_and_spacing() { + // A set of six instances 30 pt apart, turned by a drag of the Symbol Spinner; then a stroke + // along the row, 4 pt between its points, with Scrunch as given. Returns the rotations of the + // six, how many instances the stroke added and the rotation of the last one. + let sprayed = |scrunch: &str| { + let mut s = session(); + let row: Vec = (0..6).map(|i| json!([100.0 + 30.0 * f64::from(i), 100.0])).collect(); + let p = json!({"name": "Dot", "points": row, "radius": 2, "density": 10}); + let set = NodeId(s.execute("symbol.spray", &p).unwrap()["id"].as_u64().unwrap()); + assert_eq!(members(&s, set).len(), 6); + adjust(&mut s, json!({"tool": "spin", "points": [[175, 60], [176, 60], [177, 60], [178, 60]], "radius": 200, "intensity": 10})); + let turned: Vec = members(&s, set).iter().map(|id| angle(&s, *id)).collect(); + let stroke: Vec = (0..40).map(|i| json!([100.0 + 4.0 * f64::from(i), 100.0])).collect(); + let p = json!({"name": "Dot", "points": stroke, "radius": 40, "density": 10, "attributes": {"scrunch": scrunch}}); + let n = s.execute("symbol.spray", &p).unwrap()["count"].as_u64().unwrap(); + let new = *members(&s, set).last().unwrap(); + (turned, n, angle(&s, new)) + }; + let (turned, plain, _) = sprayed("userDefined"); + assert!(turned.iter().all(|a| a.abs() > 0.05 && a.signum() == turned[0].signum()), "{turned:?}"); + // User Defined keeps new instances 3 pt apart (20 pt × 0.15 at density 10); Average keeps them + // as far apart as the instances under the brush are, about 30 pt. + let (_, spaced, new_angle) = sprayed("average"); + assert!(spaced < plain, "{spaced} spaced like the row against {plain}"); + assert!(new_angle.signum() == turned[0].signum() && new_angle.abs() > 0.05, "{new_angle} against {turned:?}"); +} + +/// The Symbol Sprayer's `attributes` must be an object of the six keys, each `average` or +/// `userDefined`; anything else is an error and sprays nothing. +#[test] +fn bad_sprayer_attributes_are_refused() { + let mut s = session(); + let calls = [ + (json!("average"), "`attributes` must be an object, not \"average\"".to_string()), + (json!(["size"]), "`attributes` must be an object, not [\"size\"]".to_string()), + (json!({"density": "average"}), "unknown attribute `density`".to_string()), + (json!({"size": "big"}), "attribute `size` must be average or userDefined, not \"big\"".to_string()), + (json!({"spin": true}), "attribute `spin` must be average or userDefined, not true".to_string()), + (json!({"style": "Average"}), "attribute `style` must be average or userDefined, not \"Average\"".to_string()), + ]; + for (attributes, want) in calls { + refused(&mut s, "symbol.spray", json!({"name": "Dot", "points": [[200, 150]], "attributes": attributes}), &want); + } + refused(&mut s, "symbol.spray", json!({"name": "Dot", "points": [[200, 150]], "keepModel": "yes"}), "`keepModel` must be true or false"); + refused(&mut s, "symbol.spray", json!({"name": "Dot", "points": [[200, 150, "x"]]}), "a point's pressure must be a number, not \"x\""); + // Style: User Defined with a style the document does not have; Average does not use it. + let user = json!({"name": "Dot", "points": [[200, 150]], "attributes": {"style": "userDefined"}, "style": "Nope"}); + refused(&mut s, "symbol.spray", user, "unknown graphic style `Nope`"); + let number = json!({"name": "Dot", "points": [[200, 150]], "attributes": {"style": "userDefined"}, "style": 3}); + refused(&mut s, "symbol.spray", number, "`style` must be a graphic style's name, not 3"); + let average = json!({"name": "Dot", "points": [[200, 150]], "style": "Nope"}); + assert_eq!(s.execute("symbol.spray", &average).unwrap()["count"], 1); + let all = json!({"scrunch": "average", "size": "userDefined", "spin": null, "screen": "average", "stain": "average", "style": "average"}); + assert_eq!(s.execute("symbol.spray", &json!({"name": "Dot", "points": [[200, 150]], "attributes": all})).unwrap()["count"], 1); +} + +/// `symbol.setDensity` spaces a symbol set's instances from its middle as the new density packs +/// them, as one undo step, and adds none when no instance moves. +#[test] +fn set_density_spaces_the_instances_of_a_symbol_set() { + let mut s = session(); + let row: Vec = (0..8).map(|i| json!([40.0 + 40.0 * f64::from(i), 150.0])).collect(); + let set = NodeId(s.execute("symbol.spray", &json!({"name": "Dot", "points": row, "radius": 4})).unwrap()["id"].as_u64().unwrap()); + let ids = members(&s, set); + assert_eq!(ids.len(), 8); + let centers = |s: &Session| ids.iter().map(|id| center(s, *id)).collect::>(); + let middle = |c: &[Point]| Point::new(c.iter().map(|p| p.x).sum::() / 8.0, c.iter().map(|p| p.y).sum::() / 8.0); + let (was, steps) = (centers(&s), undo_len(&s)); + // From 5 to 9: 0.25 / 0.65 of each distance from the middle, which stays where it is. + let r = s.execute("symbol.setDensity", &json!({"from": 5, "to": 9})).unwrap(); + assert_eq!(r, json!({"ids": [set.0], "count": 8})); + assert_eq!(undo_len(&s), steps + 1); + let now = centers(&s); + let (m, ratio) = (middle(&was), 0.25 / 0.65); + assert!(middle(&now).distance(m) < 1e-9); + for (before, after) in was.iter().zip(&now) { + assert!(after.distance(m + (*before - m) * ratio) < 1e-9, "{before:?} -> {after:?}"); + } + // Back from 9 to 5: where they were, once for a set named twice. + let r = s.execute("symbol.setDensity", &json!({"from": 9, "to": 5, "ids": [set.0, set.0]})).unwrap(); + assert_eq!(r, json!({"ids": [set.0], "count": 8})); + assert!(centers(&s).iter().zip(&was).all(|(a, b)| a.distance(*b) < 1e-9)); + // The density the set has (5, a `from` of 7 notwithstanding): no instance moves and no undo + // step is added. + let steps = undo_len(&s); + assert_eq!(s.execute("symbol.setDensity", &json!({"from": 7, "to": 5})).unwrap(), json!({"ids": [], "count": 0})); + assert_eq!(undo_len(&s), steps); + // Undo puts a spaced set back. + s.execute("symbol.setDensity", &json!({"from": 5, "to": 1, "id": set.0})).unwrap(); + assert!(centers(&s)[0].distance(was[0]) > 1.0); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(centers(&s).iter().zip(&was).all(|(a, b)| a.distance(*b) < 1e-9)); +} + +/// A set packs from the density it was created at, whatever `from` says and whatever density more +/// instances were sprayed into it at; a set without a recorded density packs from `from`. +#[test] +fn set_density_starts_from_the_density_a_set_was_sprayed_at() { + let mut s = session(); + let row: Vec = (0..4).map(|i| json!([60.0 + 60.0 * f64::from(i), 150.0])).collect(); + let set = NodeId(s.execute("symbol.spray", &json!({"name": "Dot", "points": row, "radius": 4, "density": 2})).unwrap()["id"].as_u64().unwrap()); + let ids = members(&s, set); + let xs = |s: &Session| ids.iter().map(|id| center(s, *id).x).collect::>(); + let was = xs(&s); + let middle = was.iter().sum::() / 4.0; + s.execute("symbol.setDensity", &json!({"from": 5, "to": 9})).unwrap(); + let ratio = 0.25 / 0.95; + for (before, after) in was.iter().zip(xs(&s)) { + assert!((after - (middle + (before - middle) * ratio)).abs() < 1e-9, "{before} -> {after}"); + } + // Given density 2, the set stays at 2 when more instances are sprayed into it at 9. + s.execute("symbol.setDensity", &json!({"from": 5, "to": 2, "ids": [set.0]})).unwrap(); + s.execute("symbol.spray", &json!({"name": "Dot", "points": [[300, 200]], "radius": 4, "density": 9})).unwrap(); + assert_eq!(s.execute("symbol.setDensity", &json!({"from": 9, "to": 2, "ids": [set.0]})).unwrap()["count"], 0); + // Without the record (a set grouped by hand), `from` is the starting density. + let mut s = session(); + let (a, b) = (dot(&mut s, 100.0, 150.0), dot(&mut s, 200.0, 150.0)); + s.select(|_, sel| sel.set([a, b])).unwrap(); + let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.edit("Name", |d, _| { + if let Some(n) = d.node_mut(group) { + n.name = Some("Symbol Set".into()); + } + Ok(()) + }) + .unwrap(); + s.execute("symbol.setDensity", &json!({"from": 5, "to": 9, "ids": [group.0]})).unwrap(); + assert!((center(&s, a).x - (150.0 - 50.0 * 0.25 / 0.65)).abs() < 1e-9, "{:?}", center(&s, a)); +} + +/// A set of one instance takes the new density without moving, as one undo step, so a later change +/// packs it from that density; setting the density it already has adds no undo step. +#[test] +fn set_density_gives_a_set_of_one_instance_the_new_density() { + let mut s = session(); + let set = NodeId(s.execute("symbol.spray", &json!({"name": "Dot", "points": [[100, 150]], "radius": 4})).unwrap()["id"].as_u64().unwrap()); + let steps = undo_len(&s); + assert_eq!(s.execute("symbol.setDensity", &json!({"from": 5, "to": 9, "ids": [set.0]})).unwrap(), json!({"ids": [set.0], "count": 0})); + assert_eq!(undo_len(&s), steps + 1); + assert_eq!(s.execute("symbol.setDensity", &json!({"from": 5, "to": 9, "ids": [set.0]})).unwrap(), json!({"ids": [], "count": 0})); + assert_eq!(undo_len(&s), steps + 1); + // A second instance, then from the set's 9 to 5: 0.65 / 0.25 of each distance from the middle. + s.select(|_, sel| sel.set([set])).unwrap(); + s.execute("symbol.spray", &json!({"name": "Dot", "points": [[200, 150]], "radius": 4, "density": 9})).unwrap(); + let ids = members(&s, set); + assert_eq!(ids.len(), 2); + let was: Vec = ids.iter().map(|id| center(&s, *id)).collect(); + let middle = Point::new((was[0].x + was[1].x) / 2.0, (was[0].y + was[1].y) / 2.0); + s.execute("symbol.setDensity", &json!({"from": 5, "to": 5, "ids": [set.0]})).unwrap(); + for (id, before) in ids.iter().zip(&was) { + let want = middle + (*before - middle) * (0.65 / 0.25); + assert!(center(&s, *id).distance(want) < 1e-9, "{before:?} -> {:?}", center(&s, *id)); + } +} + +/// A locked instance of the set stays where it is, and the others move. +#[test] +fn set_density_leaves_a_locked_instance_in_place() { + let mut s = session(); + let row: Vec = (0..3).map(|i| json!([100.0 + 80.0 * f64::from(i), 150.0])).collect(); + let set = NodeId(s.execute("symbol.spray", &json!({"name": "Dot", "points": row, "radius": 4})).unwrap()["id"].as_u64().unwrap()); + let ids = members(&s, set); + s.edit("Lock", |d, _| { + if let Some(n) = d.node_mut(ids[0]) { + n.locked = true; + } + Ok(()) + }) + .unwrap(); + let was: Vec = ids.iter().map(|id| center(&s, *id)).collect(); + let r = s.execute("symbol.setDensity", &json!({"from": 5, "to": 9, "ids": [set.0]})).unwrap(); + assert!(r["count"].as_u64().is_some_and(|n| (1..=2).contains(&n)), "{r}"); + assert_eq!(center(&s, ids[0]), was[0]); + assert!(center(&s, ids[2]).distance(was[2]) > 1.0); +} + +/// `symbol.setDensity` refuses a density left out, not a number or outside 1..10, an id naming no +/// object, and objects with no symbol set among them. +#[test] +fn set_density_refuses_bad_densities_and_objects_without_a_set() { + let mut s = session(); + let set = + NodeId(s.execute("symbol.spray", &json!({"name": "Dot", "points": [[100, 150], [200, 150]], "radius": 4})).unwrap()["id"].as_u64().unwrap()); + for (p, want) in [ + (json!({"to": 5}), "missing `from`".to_string()), + (json!({"from": 5}), "missing `to`".to_string()), + (json!({"from": "5", "to": 6}), "`from` must be a number from 1 to 10, not \"5\"".to_string()), + (json!({"from": 5, "to": 11}), "`to` must be a number from 1 to 10, not 11".to_string()), + (json!({"from": 0, "to": 5}), "`from` must be a number from 1 to 10, not 0".to_string()), + (json!({"from": null, "to": 5}), "`from` must be a number from 1 to 10, not null".to_string()), + ] { + refused(&mut s, "symbol.setDensity", p, &want); + } + let before = state(&s); + assert!(s.execute("symbol.setDensity", &json!({"from": 5, "to": 9, "ids": [987_654]})).is_err()); + assert!(s.execute("symbol.setDensity", &json!({"from": 5, "to": 9, "ids": "all"})).is_err()); + // An instance is not a set, and neither is nothing selected. + let member = members(&s, set)[0]; + assert!(s.execute("symbol.setDensity", &json!({"from": 5, "to": 9, "ids": [member.0]})).is_err()); + s.select(|_, sel| sel.clear()).unwrap(); + let r = s.execute("symbol.setDensity", &json!({"from": 5, "to": 9})); + assert!(matches!(&r, Err(EngineError::Other(msg)) if msg == "no symbol set selected"), "{r:?}"); + assert!(state(&s) == before); +} + +/// An instance with no size is shifted and screened as before; only Average, which needs its size, +/// leaves it as it is. +#[test] +fn an_instance_without_a_size_is_changed_by_every_method_but_average() { + // A Dot at 200, 150 whose size is 0, and Dots at the other centers. + let flat = |others: &[(f64, f64)]| { + let mut s = session(); + let a = dot(&mut s, 200.0, 150.0); + for (x, y) in others { + dot(&mut s, *x, *y); + } + s.edit("Flatten", |d, _| { + if let Some(NodeKind::SymbolInstance { xf, .. }) = d.node_mut(a).map(|n| &mut n.kind) { + *xf = Affine::new([0.0, 0.0, 0.0, 0.0, 200.0, 150.0]); + } + Ok(()) + }) + .unwrap(); + (s, a) + }; + let (mut s, a) = flat(&[(210.0, 150.0)]); + let r = adjust(&mut s, json!({"tool": "shift", "points": [[200, 150], [205, 150]], "radius": 40, "intensity": 10})); + assert_eq!(r["count"], 2); + assert!(center(&s, a).x > 200.5, "{:?}", center(&s, a)); + let r = adjust(&mut s, json!({"tool": "screen", "points": [[205, 150]], "radius": 40, "intensity": 10})); + assert_eq!(r["count"], 2); + assert!(node(&s, a).opacity < 1.0); + // Average brings the other two toward their mean and leaves the one without a size as it is. + let (mut s, a) = flat(&[(190.0, 150.0), (210.0, 150.0)]); + adjust(&mut s, json!({"tool": "screen", "points": [[190, 150]], "radius": 2, "intensity": 10})); + let r = adjust(&mut s, json!({"tool": "screen", "points": [[200, 150]], "radius": 40, "intensity": 10, "method": "average"})); + assert_eq!(r["count"], 2); + assert_eq!(node(&s, a).opacity, 1.0); + // With only it under the brush there is no mean, and Average changes nothing. + let before = state(&s); + let r = adjust(&mut s, json!({"tool": "screen", "points": [[200, 150]], "radius": 5, "intensity": 10, "method": "average"})); + assert_eq!(r["count"], 0); + assert!(state(&s) == before); +} + +/// A stroke that leaves every instance under the brush as it is (each already at full stain, or +/// at the least opacity) counts none and adds no undo step. +#[test] +fn a_stroke_that_changes_no_instance_adds_no_undo_step() { + let mut s = session(); + dot(&mut s, 200.0, 150.0); + let full = json!(vec![[200, 150]; 12]); + for tool in ["stain", "screen"] { + adjust(&mut s, json!({"tool": tool, "points": full, "radius": 40, "intensity": 10, "color": "#ff0000"})); + let before = state(&s); + let r = adjust(&mut s, json!({"tool": tool, "points": [[200, 150]], "radius": 40, "intensity": 10, "color": "#ff0000"})); + assert_eq!(r["count"], 0, "{tool}"); + assert!(state(&s) == before, "{tool} changed the document"); + } +} + +/// An instance a stroke moves away and back to where it was is not counted, and the stroke adds +/// no undo step: the Shifter's drag out and back moves it 8 pt right, then 8 pt left. +#[test] +fn an_instance_moved_away_and_back_is_not_counted() { + let mut s = session(); + let id = dot(&mut s, 200.0, 150.0); + let before = state(&s); + let r = adjust(&mut s, json!({"tool": "shift", "points": [[196, 166], [212, 166], [196, 166]], "radius": 40, "intensity": 10})); + assert_eq!(bounds(&s, id).center(), Point::new(200.0, 150.0)); + assert_eq!(r["count"], 0); + assert!(state(&s) == before, "the stroke added an undo step"); +} diff --git a/crates/engine/src/tests/xform.rs b/crates/engine/src/tests/xform.rs index a3470617a7..3aea7f3041 100644 --- a/crates/engine/src/tests/xform.rs +++ b/crates/engine/src/tests/xform.rs @@ -480,6 +480,41 @@ fn reflect_and_shear_tools() { assert!((b.width() - 150.0).abs() < 1e-6, "{b:?}"); } +/// Two clicks with the Reflect tool reflect the selection across the line through both points as +/// one undo step; with Alt on the second click, a copy is reflected and Undo removes it. +#[test] +fn two_reflect_clicks_reflect_across_their_line_as_one_undo_step() { + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 100.0, 50.0); + s.select_tool("reflect", ViewInfo::default()).unwrap(); + let click = |s: &mut Session, x: f64, y: f64, alt: bool| { + drag_at(s, PointerKind::Down, (x, y), alt); + drag_at(s, PointerKind::Up, (x, y), alt); + }; + let n = undo_len(&s); + click(&mut s, 300.0, 50.0, false); + assert_eq!(undo_len(&s), n); + assert!(close(bounds(&s, a), Rect::new(100.0, 100.0, 200.0, 150.0))); + click(&mut s, 300.0, 250.0, false); + assert!(close(bounds(&s, a), Rect::new(400.0, 100.0, 500.0, 150.0)), "{:?}", bounds(&s, a)); + assert_eq!(undo_len(&s), n + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(close(bounds(&s, a), Rect::new(100.0, 100.0, 200.0, 150.0))); + + let children = |s: &Session| s.doc().unwrap().doc.layers[0].children().unwrap().len(); + click(&mut s, 50.0, 300.0, false); + click(&mut s, 350.0, 300.0, true); + assert_eq!(children(&s), 2); + assert!(close(bounds(&s, a), Rect::new(100.0, 100.0, 200.0, 150.0))); + // The copy is selected and reflected across y = 300. + let copy = s.doc().unwrap().selection.objects.clone(); + assert!(copy.len() == 1 && copy[0] != a, "{copy:?}"); + assert!(close(bounds(&s, copy[0]), Rect::new(100.0, 450.0, 200.0, 500.0)), "{:?}", bounds(&s, copy[0])); + assert_eq!(undo_len(&s), n + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(children(&s), 1); +} + /// 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. diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 65ea837527..5f36c5a98e 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -35,6 +35,9 @@ pub struct ViewInfo { pub snap_to_glyph: bool, /// View → Show Corner Widget. pub corner_widgets: bool, + /// The Control bar's Show Shape Widgets: selected live shapes show their corner, pie and side + /// widgets to the Selection tool and the shape tools. + pub shape_widgets: bool, /// The document window (none headless): screen-fixed widgets sit in it. pub screen: Option, /// The view's active artboard (an index): artboard rulers measure from it. @@ -55,6 +58,7 @@ impl Default for ViewInfo { snap_to_point: true, snap_to_glyph: false, corner_widgets: true, + shape_widgets: true, screen: None, artboard: 0, } @@ -420,6 +424,7 @@ impl Session { snap_to_glyph: view.snap_to_glyph && smart_guides && !view.snap_to_grid, glyph_snap: self.prefs.glyph_snap, corner_widgets: view.corner_widgets, + shape_widgets: view.shape_widgets, fill_active: self.fill_active, gradient_stop: self.selected_stop(), appearance_item: self.appearance_item(), @@ -476,6 +481,7 @@ impl Session { plane_targets: self.prefs.perspective_widget.targets(), precise_cursors: self.precise_cursors(), global_edit: st.global_edit.as_ref().map_or(&[], |g| g.members.as_slice()), + interaction_doc: st.interaction.as_ref().map(|it| &*it.doc), }; let tool = &mut self.tool; match crate::guard::catch_panic(|| f(tool.as_mut(), &cx)) { @@ -1413,6 +1419,7 @@ impl Session { } // Every value is checked before any is set, so an invalid one changes nothing. vectorcraft_tools::builder::check_builder_options(id, &values)?; + vectorcraft_tools::symbolism::check_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. diff --git a/crates/engine/tests/color_settings.rs b/crates/engine/tests/color_settings.rs index a7d516f8eb..7c0aef252e 100644 --- a/crates/engine/tests/color_settings.rs +++ b/crates/engine/tests/color_settings.rs @@ -8,7 +8,7 @@ use std::sync::{Mutex, MutexGuard}; use serde_json::json; use vectorcraft_color::cms; use vectorcraft_engine::Session; -use vectorcraft_engine::cmd::colormgmt::{PROFILES_KEY, doc_profiles}; +use vectorcraft_engine::cmd::colormgmt::{PROFILES_KEY, ProfileChoice, ProfileIssue, doc_profiles}; use vectorcraft_engine::store::MAX_PRESET_FILE; use vectorcraft_geom::Affine; use vectorcraft_render::{RenderOptions, Renderer}; @@ -1082,3 +1082,615 @@ fn color_management_policies_are_checked_and_kept() { next.attach_color_settings(file); assert_eq!(cms::active_settings(), cms::ColorSettings::default()); } + +/// The Ask boxes of Edit › Color Settings are checked, come back in the reply and are kept in +/// `Color Settings.json`. +#[test] +fn ask_boxes_are_checked_and_kept() { + let _g = settings(); + let dir = fresh_dir("ask-kept"); + let _reset = ColorSettingsReset { profile: None, paths: vec![dir.clone()] }; + let file = dir.join("Color Settings.json"); + let mut s = session(); + s.attach_color_settings(file.clone()); + let r = exec(&mut s, "edit.colorSettings", json!({})); + assert_eq!( + (r["askMismatchOpen"].as_bool(), r["askMismatchPaste"].as_bool(), r["askMissingOpen"].as_bool()), + (Some(false), Some(false), Some(false)) + ); + for bad in [json!({"askMismatchOpen": "yes"}), json!({"askMismatchPaste": 1}), json!({"askMissingOpen": []})] { + assert!(s.execute("edit.colorSettings", &bad).is_err(), "{bad}"); + } + assert!(!file.exists(), "a refused change keeps nothing"); + let r = exec(&mut s, "edit.colorSettings", json!({"askMismatchOpen": true, "askMissingOpen": true})); + assert_eq!( + (r["askMismatchOpen"].as_bool(), r["askMismatchPaste"].as_bool(), r["askMissingOpen"].as_bool()), + (Some(true), Some(false), Some(true)) + ); + let saved: cms::ColorSettings = serde_json::from_slice(&std::fs::read(&file).unwrap()).unwrap(); + assert!(saved.ask_mismatch_open && !saved.ask_mismatch_paste && saved.ask_missing_open); +} + +/// Two saved documents with a blue rectangle (`blue`, filled `blue0`): `tagged`, assigned Wide +/// Gamut RGB, and `plain`, untagged. The files go when it drops, and the Color Settings go back to +/// the defaults. +struct ProfileFiles { + _reset: ColorSettingsReset, + _dir: vectorcraft_testkit::TempDir, + tagged: std::path::PathBuf, + plain: std::path::PathBuf, + blue: vectorcraft_doc::NodeId, + blue0: vectorcraft_color::Color, +} + +#[allow(clippy::unwrap_used, reason = "a test helper: a file that can't be written fails the test")] +fn profile_files(tag: &str) -> ProfileFiles { + let dir = fresh_dir(tag); + let reset = ColorSettingsReset { profile: None, paths: vec![dir.clone()] }; + std::fs::create_dir_all(&dir).unwrap(); + let (tagged, plain) = (dir.join("tagged.vectorcraft"), dir.join("plain.vectorcraft")); + let mut s = session(); + let blue = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + exec(&mut s, "paint.setFill", json!({"ids": [blue.0], "color": "#3366cc"})); + exec(&mut s, "file.saveAs", json!({"path": plain.to_str().unwrap()})); + exec(&mut s, "edit.assignProfile", json!({"rgb": cms::WIDE_GAMUT_RGB})); + exec(&mut s, "file.saveAs", json!({"path": tagged.to_str().unwrap()})); + let blue0 = fill_of(&s, blue); + ProfileFiles { _reset: reset, _dir: dir, tagged, plain, blue, blue0 } +} + +/// The fill color of object `id` in the active document. +#[allow(clippy::unwrap_used, reason = "a test helper: a missing object or fill fails the test")] +fn fill_of(s: &Session, id: vectorcraft_doc::NodeId) -> vectorcraft_color::Color { + s.doc().unwrap().doc.node(id).and_then(|n| n.appearance.fill()).and_then(|f| f.paint.color()).unwrap() +} + +/// `document.open` of `path` with the params `extra` in a new session → the reply, and the session. +#[allow(clippy::unwrap_used, reason = "a test helper: params that are not an object fail the test")] +fn open_with(path: &std::path::Path, extra: serde_json::Value) -> (Result, Session) { + let mut s = session(); + let mut p = json!({"path": path.to_str().unwrap()}); + for (k, v) in extra.as_object().unwrap() { + p[k] = v.clone(); + } + let r = s.execute("document.open", &p).map_err(|e| e.to_string()); + (r, s) +} + +/// `document.open`'s `profileChoice` answers what Color Settings' Profile Mismatches box asks: for +/// a document tagged with another profile than the working space of its color mode it keeps the +/// profile, converts the colors or discards the profile in place of the policy. A missing choice +/// for it is not used. +#[test] +fn profile_choice_answers_a_mismatch() { + let _g = settings(); + let ProfileFiles { tagged, blue, blue0, .. } = &profile_files("profile-mismatch"); + let (tagged, blue, blue0) = (tagged.as_path(), *blue, *blue0); + let fill = |s: &Session| fill_of(s, blue); + let open = open_with; + let mut s = session(); + + // Each choice in place of the policy (Preserve Embedded Profiles). + let (r, kept) = open(tagged, json!({"profileChoice": "useEmbedded"})); + let r = r.unwrap(); + assert_eq!(r["profileChoice"], json!({"issue": "mismatch", "model": "rgb", "choice": "useEmbedded"})); + assert_eq!((doc_profiles(&kept.doc().unwrap().doc).0, fill(&kept)), (Some(cms::WIDE_GAMUT_RGB.into()), blue0)); + let (r, discarded) = open(tagged, json!({"profileChoice": "discard"})); + let r = r.unwrap(); + assert_eq!((doc_profiles(&discarded.doc().unwrap().doc).0, fill(&discarded)), (None, blue0), "the numbers stay"); + assert!(discarded.doc().unwrap().is_dirty()); + assert!(r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("as chosen when it was opened")), "{r}"); + let (r, converted) = open(tagged, json!({"profileChoice": "convert"})); + assert_eq!(r.unwrap()["profileChoice"]["choice"], "convert"); + let source = cms::for_document(Some(cms::WIDE_GAMUT_RGB), None); + let blue1 = fill(&converted); + assert_eq!(doc_profiles(&converted.doc().unwrap().doc).0, None); + assert!(blue1 != blue0 && cms::delta_e2000(source.lab(&blue0), cms::working().lab(&blue1)) < 1.0, "{blue0:?} → {blue1:?}"); + // Under policy Off, Use Embedded keeps the profile. + exec(&mut s, "edit.colorSettings", json!({"rgbPolicy": "off"})); + let (_, kept) = open(tagged, json!({"profileChoice": "useEmbedded"})); + assert_eq!(doc_profiles(&kept.doc().unwrap().doc).0, Some(cms::WIDE_GAMUT_RGB.into())); + // A missing choice for a mismatched document is not used: the policy applies. + let (r, off) = open(tagged, json!({"profileChoice": "leave"})); + assert!(r.unwrap().get("profileChoice").is_none()); + assert_eq!(doc_profiles(&off.doc().unwrap().doc).0, None); +} + +/// `document.open`'s `profileChoice` answers what the Missing Profiles box asks: an untagged +/// document is left, assigned the working space or assigned a profile, its numbers kept. A +/// mismatch choice for it is not used, and wrong choices are refused. +#[test] +fn profile_choice_answers_a_missing_profile() { + let _g = settings(); + let ProfileFiles { tagged, plain, blue, blue0, .. } = &profile_files("profile-missing"); + let (tagged, plain, blue, blue0) = (tagged.as_path(), plain.as_path(), *blue, *blue0); + let fill = |s: &Session| fill_of(s, blue); + let open = open_with; + let (r, left) = open(plain, json!({"profileChoice": "leave"})); + assert_eq!(r.unwrap()["profileChoice"], json!({"issue": "missing", "model": "rgb", "choice": "leave"})); + assert_eq!(doc_profiles(&left.doc().unwrap().doc).0, None); + assert!(!left.doc().unwrap().is_dirty()); + let (_, working) = open(plain, json!({"profileChoice": "assignWorking"})); + assert_eq!(doc_profiles(&working.doc().unwrap().doc).0.as_deref(), Some(cms::canonical_name(cms::SRGB))); + assert!(working.doc().unwrap().is_dirty()); + let (_, p3) = open(plain, json!({"profileChoice": "assign", "assignProfile": cms::DISPLAY_P3})); + assert_eq!((doc_profiles(&p3.doc().unwrap().doc).0, fill(&p3)), (Some(cms::DISPLAY_P3.into()), blue0), "assigning keeps the numbers"); + // A mismatch choice for an untagged document is not used. + let (r, plain_kept) = open(plain, json!({"profileChoice": "convert"})); + assert!(r.unwrap().get("profileChoice").is_none()); + assert_eq!(doc_profiles(&plain_kept.doc().unwrap().doc).0, None); + + for bad in [ + json!({"profileChoice": "bogus"}), + json!({"profileChoice": "assign"}), + json!({"profileChoice": "discard", "assignProfile": cms::DISPLAY_P3}), + json!({"assignProfile": cms::DISPLAY_P3}), + json!({"profileChoice": 3}), + ] { + assert!(open(tagged, bad.clone()).0.is_err(), "{bad}"); + } + let (r, none) = open(plain, json!({"profileChoice": "assign", "assignProfile": cms::DEVICE_CMYK})); + assert!(r.unwrap_err().contains("unknown rgb profile"), "a CMYK profile can't tag an RGB document"); + assert_eq!(none.documents().len(), 1, "nothing opened"); +} + +/// The app's half of the open prompts: a file read with asking stops at the question when its box +/// is on (never without asking), and opens as answered, or as the policy says when it opens +/// unanswered. A refused answer leaves it waiting. +#[test] +fn a_read_waits_for_the_profile_answer() { + let _g = settings(); + let ProfileFiles { tagged, plain, blue, blue0, .. } = &profile_files("profile-wait"); + let (blue, blue0) = (*blue, *blue0); + let fill = |s: &Session| fill_of(s, blue); + let mut s = session(); + let source = cms::for_document(Some(cms::WIDE_GAMUT_RGB), None); + let blue1 = source.convert_into(&cms::working(), &blue0, cms::working().settings().intent); + let bytes = std::fs::read(tagged).unwrap(); + let name = tagged.to_str().unwrap(); + let read = + |ask: bool| vectorcraft_engine::cmd::fileio::read_for_open_asking(name, &bytes, Some(name.into()), &json!({}), false, false, ask).unwrap(); + assert!(read(true).question().is_none(), "the box is off"); + exec(&mut s, "edit.colorSettings", json!({"askMismatchOpen": true, "rgbPolicy": "convert"})); + assert!(read(false).question().is_none(), "document.open never asks"); + let mut waiting = read(true); + let q = waiting.question().unwrap(); + assert_eq!((q.issue, q.profile.as_deref(), q.default.id()), (ProfileIssue::Mismatch, Some(cms::WIDE_GAMUT_RGB), "convert")); + assert_eq!(waiting.name(), "tagged.vectorcraft"); + waiting.answer(ProfileChoice::Discard).unwrap(); + assert!(waiting.question().is_none(), "answered"); + let mut opened = session(); + let r = vectorcraft_engine::cmd::fileio::open_read(&mut opened, waiting).unwrap(); + assert_eq!(r["profileChoice"]["choice"], "discard"); + assert_eq!((doc_profiles(&opened.doc().unwrap().doc).0, fill(&opened)), (None, blue0)); + // Unanswered, it opens as the policy (Convert to Working Space) says. + let mut opened = session(); + vectorcraft_engine::cmd::fileio::open_read(&mut opened, read(true)).unwrap(); + assert_eq!((doc_profiles(&opened.doc().unwrap().doc).0, fill(&opened)), (None, blue1)); + // A missing answer to a mismatch is not used: the policy decides. + let mut waiting = read(true); + waiting.answer(ProfileChoice::Leave).unwrap(); + let mut opened = session(); + let r = vectorcraft_engine::cmd::fileio::open_read(&mut opened, waiting).unwrap(); + assert!(r.get("profileChoice").is_none()); + assert_eq!(fill(&opened), blue1); + // Missing Profiles: Ask When Opening, starting on assigning the working space under Convert. + exec(&mut s, "edit.colorSettings", json!({"askMismatchOpen": false, "askMissingOpen": true})); + assert!(read(true).question().is_none(), "the mismatch box is off now"); + let plain_bytes = std::fs::read(plain).unwrap(); + let mut waiting = + vectorcraft_engine::cmd::fileio::read_for_open_asking("plain.vectorcraft", &plain_bytes, None, &json!({}), false, false, true).unwrap(); + let q = waiting.question().unwrap(); + assert_eq!((q.issue, q.profile.as_deref(), q.default.id()), (ProfileIssue::Missing, None, "assignWorking")); + assert!(waiting.answer(ProfileChoice::Assign(cms::DEVICE_CMYK.into())).is_err(), "not an RGB profile"); + assert!(waiting.question().is_some(), "still waiting after a refused answer"); + waiting.answer(ProfileChoice::Assign(cms::DISPLAY_P3.into())).unwrap(); + let mut opened = session(); + vectorcraft_engine::cmd::fileio::open_read(&mut opened, waiting).unwrap(); + assert_eq!(doc_profiles(&opened.doc().unwrap().doc).0, Some(cms::DISPLAY_P3.into())); +} + +/// An answer is taken only while the question it answers stands: once Color Settings change the +/// working space so that the question goes away or names another working space, the answer is +/// refused and the file keeps waiting. Asked again, it takes the answer to the question it asks now. +#[test] +fn a_profile_answer_waits_for_the_question_it_answers() { + let _g = settings(); + let ProfileFiles { tagged, blue, blue0, .. } = &profile_files("profile-changed"); + let (blue, blue0) = (*blue, *blue0); + let mut s = session(); + exec(&mut s, "edit.colorSettings", json!({"askMismatchOpen": true})); + let bytes = std::fs::read(tagged).unwrap(); + let name = tagged.to_str().unwrap(); + let mut waiting = vectorcraft_engine::cmd::fileio::read_for_open_asking(name, &bytes, Some(name.into()), &json!({}), false, false, true).unwrap(); + assert_eq!(waiting.question().unwrap().working, cms::canonical_name(cms::SRGB)); + // The working space becomes the file's profile: the question is gone. + exec(&mut s, "edit.colorSettings", json!({"rgb": cms::WIDE_GAMUT_RGB})); + assert!(waiting.answer(ProfileChoice::Discard).is_err(), "the question it answers is gone"); + // Another working space: the question names it. + exec(&mut s, "edit.colorSettings", json!({"rgb": cms::DISPLAY_P3})); + let err = waiting.answer(ProfileChoice::Discard).unwrap_err().to_string(); + assert!(err.contains("the profile question changed since it was asked"), "{err}"); + assert_eq!(waiting.ask().unwrap().working, cms::canonical_name(cms::DISPLAY_P3)); + waiting.answer(ProfileChoice::Discard).unwrap(); + let mut opened = session(); + let r = vectorcraft_engine::cmd::fileio::open_read(&mut opened, waiting).unwrap(); + assert_eq!(r["profileChoice"]["choice"], "discard"); + assert_eq!((doc_profiles(&opened.doc().unwrap().doc).0, fill_of(&opened, blue)), (None, blue0)); +} + +/// Swatch conflicts are checked against the colors as the paste brings them: a global swatch whose +/// name and color match the destination's conflicts once the paste converts it, and pasting back +/// into its own document with conversion compares its swatches too. +#[test] +fn swatch_conflicts_follow_the_profile_conversion() { + let _g = settings(); + let _reset = ColorSettingsReset { profile: None, paths: vec![] }; + let mut s = session(); + exec(&mut s, "swatch.new", json!({"name": "Brand", "color": "#3366cc", "global": true})); + let r = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + exec(&mut s, "paint.setFill", json!({"ids": [r.0], "swatch": "Brand"})); + exec(&mut s, "edit.assignProfile", json!({"rgb": cms::WIDE_GAMUT_RGB})); + select(&mut s, &[r]); + exec(&mut s, "edit.copy", json!({})); + exec(&mut s, "file.new", json!({"width": 100, "height": 100})); + exec(&mut s, "swatch.new", json!({"name": "Brand", "color": "#3366cc", "global": true})); + let conflicts = |s: &mut Session, p: serde_json::Value| exec(s, "clipboard.conflicts", p)["swatches"].as_array().unwrap().len(); + assert_eq!(conflicts(&mut s, json!({})), 0, "the numbers are kept: the same color"); + assert_eq!(conflicts(&mut s, json!({"profileMismatch": "convert"})), 1, "converted, it differs"); + assert!(s.execute("clipboard.conflicts", &json!({"profileMismatch": "keep"})).is_err()); + // Back in the first document, under another working space, a converting paste compares too. + exec(&mut s, "document.activate", json!({"index": 0})); + exec(&mut s, "edit.assignProfile", json!({"rgb": null})); + assert_eq!(conflicts(&mut s, json!({})), 0); + assert_eq!(conflicts(&mut s, json!({"profileMismatch": "convert"})), 1); +} + +/// A paste is a mismatch only for the models the copied colors use: CMYK art from a document with +/// other RGB and CMYK profiles is a CMYK mismatch alone, and so is an artboard copied without art +/// whose background is CMYK. +#[test] +fn a_paste_mismatches_only_the_models_its_colors_use() { + let _g = settings(); + let _reset = ColorSettingsReset { profile: None, paths: vec![] }; + let mut s = session(); + let ink = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + exec(&mut s, "paint.setFill", json!({"ids": [ink.0], "color": {"c": 20, "m": 40, "y": 60, "k": 10}})); + exec(&mut s, "paint.setStroke", json!({"ids": [ink.0], "none": true})); + exec(&mut s, "edit.assignProfile", json!({"rgb": cms::WIDE_GAMUT_RGB, "cmyk": cms::DEVICE_CMYK})); + select(&mut s, &[ink]); + exec(&mut s, "edit.copy", json!({})); + exec(&mut s, "file.new", json!({"width": 100, "height": 100})); + let models = |s: &mut Session| -> Vec { + let r = exec(s, "clipboard.profileMismatch", json!({})); + r["mismatches"].as_array().unwrap().iter().map(|m| m["model"].as_str().unwrap().to_string()).collect() + }; + assert_eq!(models(&mut s), ["cmyk"]); + exec(&mut s, "document.activate", json!({"index": 0})); + exec(&mut s, "artboard.setProps", json!({"index": 0, "color": {"c": 0, "m": 100, "y": 0, "k": 0}})); + exec(&mut s, "artboard.copy", json!({"index": 0})); + exec(&mut s, "document.activate", json!({"index": 1})); + assert_eq!(models(&mut s), ["cmyk"]); +} + +/// An artboard copied without art from a document with another profile is a mismatch through its +/// background color, which converts with a paste that converts. +#[test] +fn a_pasted_artboard_background_converts() { + let _g = settings(); + let _reset = ColorSettingsReset { profile: None, paths: vec![] }; + let mut s = session(); + exec(&mut s, "artboard.setProps", json!({"index": 0, "color": "#3366cc"})); + exec(&mut s, "edit.assignProfile", json!({"rgb": cms::WIDE_GAMUT_RGB})); + exec(&mut s, "artboard.copy", json!({"index": 0})); + exec(&mut s, "file.new", json!({"width": 100, "height": 100})); + assert_eq!(exec(&mut s, "clipboard.profileMismatch", json!({}))["mismatches"][0]["model"], "rgb"); + let r = exec(&mut s, "edit.paste", json!({"profileMismatch": "convert"})); + let i = r["artboards"][0].as_u64().unwrap() as usize; + let paper = s.doc().unwrap().doc.artboards[i].color.unwrap(); + let blue0 = vectorcraft_color::Color::from_hex("#3366cc").unwrap(); + let source = cms::for_document(Some(cms::WIDE_GAMUT_RGB), None); + assert!(paper != blue0 && cms::delta_e2000(source.lab(&blue0), cms::working().lab(&paper)) < 1.0, "{blue0:?} → {paper:?}"); +} + +/// Paste compares the profiles the copied colors showed through with the destination's: a model +/// whose profile differs and whose colors the objects use is a mismatch (clipboard.profileMismatch). +/// Its colors keep their numbers or convert, as `profileMismatch` says, else as the policy says; +/// the reply lists what was done. +#[test] +fn paste_keeps_or_converts_colors_from_another_profile() { + let _g = settings(); + let _reset = ColorSettingsReset { profile: None, paths: vec![] }; + let mut s = session(); + let blue = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + exec(&mut s, "paint.setFill", json!({"ids": [blue.0], "color": "#3366cc"})); + exec(&mut s, "edit.assignProfile", json!({"rgb": cms::WIDE_GAMUT_RGB, "cmyk": cms::DEVICE_CMYK})); + select(&mut s, &[blue]); + exec(&mut s, "edit.copy", json!({})); + let blue0 = vectorcraft_color::Color::from_hex("#3366cc").unwrap(); + // Back in the same document: nothing to compare. + assert_eq!(exec(&mut s, "clipboard.profileMismatch", json!({}))["mismatches"], json!([])); + exec(&mut s, "file.new", json!({"width": 100, "height": 100})); + let r = exec(&mut s, "clipboard.profileMismatch", json!({})); + // Only RGB: the objects use no CMYK color. + let srgb = cms::canonical_name(cms::SRGB); + assert_eq!( + r["mismatches"], + json!([{"model": "rgb", "clipboard": cms::WIDE_GAMUT_RGB, "document": srgb, "default": "preserveNumbers", "convertible": true}]) + ); + let pasted = |s: &mut Session, p: serde_json::Value| { + let r = exec(s, "edit.paste", p); + let id = vectorcraft_doc::NodeId(r["ids"][0].as_u64().unwrap()); + let c = s.doc().unwrap().doc.node(id).and_then(|n| n.appearance.fill()).and_then(|f| f.paint.color()).unwrap(); + (r, c) + }; + let (r, kept) = pasted(&mut s, json!({})); + assert_eq!(kept, blue0, "the policy (Preserve Embedded Profiles) keeps the numbers"); + assert_eq!(r["profileMismatch"][0]["choice"], "preserveNumbers"); + let (r, moved) = pasted(&mut s, json!({"profileMismatch": "convert"})); + assert_eq!(r["profileMismatch"][0]["choice"], "convert"); + let source = cms::for_document(Some(cms::WIDE_GAMUT_RGB), None); + assert!(moved != blue0 && cms::delta_e2000(source.lab(&blue0), cms::working().lab(&moved)) < 1.0, "{blue0:?} → {moved:?}"); + exec(&mut s, "edit.colorSettings", json!({"rgbPolicy": "convert"})); + assert_eq!(exec(&mut s, "clipboard.profileMismatch", json!({}))["mismatches"][0]["default"], "convert"); + let (_, by_policy) = pasted(&mut s, json!({})); + assert_eq!(by_policy, moved, "Convert to Working Space converts"); + let (_, numbers) = pasted(&mut s, json!({"profileMismatch": "preserveNumbers"})); + assert_eq!(numbers, blue0); + for bad in [json!({"profileMismatch": "keep"}), json!({"profileMismatch": true})] { + assert!(s.execute("edit.paste", &bad).is_err(), "{bad}"); + } + // A drag from the first document follows the policy too. + let source = s.documents()[0].uid; + let r = exec(&mut s, "edit.dropSelection", json!({"sourceDocument": source, "ids": [blue.0], "grab": [5, 5], "at": [50, 50]})); + let dropped = vectorcraft_doc::NodeId(r["ids"][0].as_u64().unwrap()); + let c = s.doc().unwrap().doc.node(dropped).and_then(|n| n.appearance.fill()).and_then(|f| f.paint.color()).unwrap(); + assert_eq!(c, moved, "dropped colors convert under Convert to Working Space"); + // A destination assigned the source's profile has nothing to compare. + exec(&mut s, "edit.assignProfile", json!({"rgb": cms::WIDE_GAMUT_RGB})); + assert_eq!(exec(&mut s, "clipboard.profileMismatch", json!({}))["mismatches"], json!([])); + let (r, same) = pasted(&mut s, json!({})); + assert!(r.get("profileMismatch").is_none()); + assert_eq!(same, blue0); +} + +/// A drag between documents is a paste for Profile Mismatches: clipboard.profileMismatch with +/// `sourceDocument` and `ids` lists what the drop brings, edit.dropSelection takes `profileMismatch` +/// and reports what it did, and a wrong choice drops nothing. +#[test] +fn a_drop_takes_the_profile_mismatch_choice() { + let _g = settings(); + let _reset = ColorSettingsReset { profile: None, paths: vec![] }; + let mut s = session(); + let blue = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + exec(&mut s, "paint.setFill", json!({"ids": [blue.0], "color": "#3366cc"})); + exec(&mut s, "edit.assignProfile", json!({"rgb": cms::WIDE_GAMUT_RGB})); + let source = s.documents()[0].uid; + exec(&mut s, "file.new", json!({"width": 100, "height": 100})); + let blue0 = vectorcraft_color::Color::from_hex("#3366cc").unwrap(); + assert_eq!(exec(&mut s, "clipboard.profileMismatch", json!({}))["mismatches"], json!([]), "the clipboard is empty"); + let dragged = json!({"sourceDocument": source, "ids": [blue.0]}); + let srgb = cms::canonical_name(cms::SRGB); + assert_eq!( + exec(&mut s, "clipboard.profileMismatch", dragged.clone())["mismatches"], + json!([{"model": "rgb", "clipboard": cms::WIDE_GAMUT_RGB, "document": srgb, "default": "preserveNumbers", "convertible": true}]) + ); + for bad in [json!({"sourceDocument": source}), json!({"ids": [blue.0]}), json!({"sourceDocument": 999_999, "ids": [blue.0]})] { + assert!(s.execute("clipboard.profileMismatch", &bad).is_err(), "{bad}"); + } + let dropped = |s: &mut Session, choice: Option<&str>| { + let mut p = json!({"sourceDocument": source, "ids": [blue.0], "grab": [5, 5], "at": [50, 50]}); + if let Some(c) = choice { + p["profileMismatch"] = json!(c); + } + let r = exec(s, "edit.dropSelection", p); + let id = vectorcraft_doc::NodeId(r["ids"][0].as_u64().unwrap()); + (r, s.doc().unwrap().doc.node(id).and_then(|n| n.appearance.fill()).and_then(|f| f.paint.color()).unwrap()) + }; + let (r, kept) = dropped(&mut s, None); + assert_eq!((kept, &r["profileMismatch"][0]["choice"]), (blue0, &json!("preserveNumbers")), "the policy keeps the numbers"); + let (r, moved) = dropped(&mut s, Some("convert")); + assert_eq!(r["profileMismatch"][0]["choice"], "convert"); + let from = cms::for_document(Some(cms::WIDE_GAMUT_RGB), None); + assert!(moved != blue0 && cms::delta_e2000(from.lab(&blue0), cms::working().lab(&moved)) < 1.0, "{blue0:?} → {moved:?}"); + let objects = |s: &Session| s.doc().unwrap().doc.layers[0].children().map_or(0, |c| c.len()); + let before = objects(&s); + let bad = json!({"sourceDocument": source, "ids": [blue.0], "grab": [5, 5], "at": [50, 50], "profileMismatch": "keep"}); + assert!(s.execute("edit.dropSelection", &bad).is_err()); + assert_eq!(objects(&s), before, "a refused choice drops nothing"); +} + +/// `assignProfile` beside another choice than `assign` is refused with a message that says it goes +/// with `assign` only. +#[test] +fn assign_profile_goes_with_assign_only() { + let _g = settings(); + let ProfileFiles { tagged, .. } = &profile_files("profile-assign-only"); + let err = open_with(tagged, json!({"profileChoice": "discard", "assignProfile": cms::DISPLAY_P3})).0.unwrap_err(); + assert!(err.contains("`assignProfile` goes with `profileChoice`: \"assign\" only"), "{err}"); +} + +/// `profileMismatch: {rgb?, cmyk?}` gives each model its own choice, and a model left out follows +/// its policy; a key other than rgb and cmyk, or a value other than the two choices, is refused and +/// pastes nothing. +#[test] +fn paste_takes_a_choice_for_each_model() { + let _g = settings(); + let _reset = ColorSettingsReset { profile: None, paths: vec![] }; + let mut s = session(); + let both = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + exec(&mut s, "paint.setFill", json!({"ids": [both.0], "color": "#3366cc"})); + exec(&mut s, "paint.setStroke", json!({"ids": [both.0], "color": {"c": 20, "m": 40, "y": 60, "k": 10}})); + exec(&mut s, "edit.assignProfile", json!({"rgb": cms::WIDE_GAMUT_RGB, "cmyk": cms::DEVICE_CMYK})); + let stroke_of = |s: &Session, id: vectorcraft_doc::NodeId| { + s.doc().unwrap().doc.node(id).and_then(|n| n.appearance.stroke()).and_then(|f| f.paint.color()).unwrap() + }; + let ink0 = stroke_of(&s, both); + select(&mut s, &[both]); + exec(&mut s, "edit.copy", json!({})); + exec(&mut s, "file.new", json!({"width": 100, "height": 100})); + exec(&mut s, "edit.colorSettings", json!({"cmykPolicy": "convert"})); + let blue0 = vectorcraft_color::Color::from_hex("#3366cc").unwrap(); + let pasted = |s: &mut Session, choice: serde_json::Value| { + let r = exec(s, "edit.paste", json!({ "profileMismatch": choice })); + let id = vectorcraft_doc::NodeId(r["ids"][0].as_u64().unwrap()); + let fill = s.doc().unwrap().doc.node(id).and_then(|n| n.appearance.fill()).and_then(|f| f.paint.color()).unwrap(); + let picked = |model: &str| r["profileMismatch"].as_array().unwrap().iter().find(|m| m["model"] == model).map(|m| m["choice"].clone()); + (fill, stroke_of(s, id), picked("rgb"), picked("cmyk")) + }; + // The CMYK policy (Convert to Working Space) converts the stroke from Device CMYK into the + // working CMYK space, as a paste that leaves both models to their policies does. + let (_, ink, rgb_policy, cmyk_policy) = pasted(&mut s, serde_json::Value::Null); + assert_eq!((rgb_policy, &cmyk_policy), (Some(json!("preserveNumbers")), &Some(json!("convert")))); + let device = cms::for_document(None, Some(cms::DEVICE_CMYK)); + assert!(ink != ink0 && cms::delta_e2000(device.lab(&ink0), cms::working().lab(&ink)) < 2.0, "{ink0:?} → {ink:?}"); + let converted_ink = ink; + let (fill, ink, rgb, cmyk) = pasted(&mut s, json!({"rgb": "convert"})); + assert_eq!((rgb, &cmyk, ink), (Some(json!("convert")), &cmyk_policy, converted_ink), "CMYK follows its policy"); + let source = cms::for_document(Some(cms::WIDE_GAMUT_RGB), None); + assert!(fill != blue0 && cms::delta_e2000(source.lab(&blue0), cms::working().lab(&fill)) < 1.0, "{blue0:?} → {fill:?}"); + let (fill, ink, rgb, cmyk) = pasted(&mut s, json!({"cmyk": "preserveNumbers"})); + assert_eq!((fill, ink, rgb, cmyk), (blue0, ink0, Some(json!("preserveNumbers")), Some(json!("preserveNumbers"))), "the inks keep their values"); + let objects = |s: &Session| s.doc().unwrap().doc.layers[0].children().map_or(0, |c| c.len()); + let before = objects(&s); + for bad in [json!({"lab": "convert"}), json!({"rgb": "keep"}), json!({"rgb": 1}), json!([]), json!(true)] { + assert!(s.execute("edit.paste", &json!({ "profileMismatch": bad })).is_err(), "{bad}"); + assert!(s.execute("clipboard.conflicts", &json!({ "profileMismatch": bad })).is_err(), "{bad}"); + } + assert_eq!(objects(&s), before, "a refused choice pastes nothing"); +} + +/// The fill color of the first object a paste reply `r` names, in the active document. +#[allow(clippy::unwrap_used, reason = "a test helper: a reply without objects fails the test")] +fn pasted_fill(s: &Session, r: &serde_json::Value) -> vectorcraft_color::Color { + fill_of(s, vectorcraft_doc::NodeId(r["ids"][0].as_u64().unwrap())) +} + +/// A document assigned a profile that was removed since draws through the working space, and its +/// copied colors come from the working space too: pasted into a document with another profile, they +/// convert from it as `profileMismatch` says. +#[test] +fn a_removed_assigned_profile_pastes_as_the_working_space() { + const NAME: &str = "Removed Wide RGB"; + let _g = settings(); + let _reset = ColorSettingsReset { profile: Some(NAME), paths: vec![] }; + cms::register_icc(&cms::icc_bytes(cms::WIDE_GAMUT_RGB).unwrap(), Some(NAME.into())).unwrap(); + let mut s = session(); + let blue = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + exec(&mut s, "paint.setFill", json!({"ids": [blue.0], "color": "#3366cc"})); + exec(&mut s, "edit.assignProfile", json!({"rgb": NAME})); + exec(&mut s, "color.removeProfile", json!({"name": NAME})); + select(&mut s, &[blue]); + exec(&mut s, "edit.copy", json!({})); + exec(&mut s, "file.new", json!({"width": 100, "height": 100})); + exec(&mut s, "edit.assignProfile", json!({"rgb": cms::DISPLAY_P3})); + let m = exec(&mut s, "clipboard.profileMismatch", json!({}))["mismatches"][0].clone(); + assert_eq!((&m["clipboard"], &m["convertible"]), (&json!(cms::canonical_name(cms::SRGB)), &json!(true)), "{m}"); + let r = exec(&mut s, "edit.paste", json!({"profileMismatch": "convert"})); + assert_eq!(r["profileMismatch"][0]["choice"], "convert"); + let (blue0, moved) = (vectorcraft_color::Color::from_hex("#3366cc").unwrap(), pasted_fill(&s, &r)); + let p3 = cms::for_document(Some(cms::DISPLAY_P3), None); + assert!(moved != blue0 && cms::delta_e2000(cms::working().lab(&blue0), p3.lab(&moved)) < 1.0, "{blue0:?} → {moved:?}"); +} + +/// Colors copied from a document whose profile was removed after the copy can't convert: the +/// mismatch says so (convertible false, and default preserveNumbers under a converting policy), and +/// a paste that asks to convert keeps their numbers. +#[test] +fn colors_from_a_profile_removed_after_the_copy_keep_their_numbers() { + const NAME: &str = "Copied Wide RGB"; + let _g = settings(); + let _reset = ColorSettingsReset { profile: Some(NAME), paths: vec![] }; + cms::register_icc(&cms::icc_bytes(cms::WIDE_GAMUT_RGB).unwrap(), Some(NAME.into())).unwrap(); + let mut s = session(); + let blue = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + exec(&mut s, "paint.setFill", json!({"ids": [blue.0], "color": "#3366cc"})); + exec(&mut s, "edit.assignProfile", json!({"rgb": NAME})); + select(&mut s, &[blue]); + exec(&mut s, "edit.copy", json!({})); + exec(&mut s, "file.new", json!({"width": 100, "height": 100})); + exec(&mut s, "edit.colorSettings", json!({"rgbPolicy": "convert"})); + let m = exec(&mut s, "clipboard.profileMismatch", json!({}))["mismatches"][0].clone(); + assert_eq!((&m["default"], &m["convertible"]), (&json!("convert"), &json!(true)), "both profiles are here: {m}"); + exec(&mut s, "color.removeProfile", json!({"name": NAME})); + let m = exec(&mut s, "clipboard.profileMismatch", json!({}))["mismatches"][0].clone(); + assert_eq!((&m["clipboard"], &m["default"], &m["convertible"]), (&json!(NAME), &json!("preserveNumbers"), &json!(false)), "{m}"); + let r = exec(&mut s, "edit.paste", json!({"profileMismatch": "convert"})); + assert_eq!(r["profileMismatch"][0]["choice"], "preserveNumbers"); + assert_eq!(pasted_fill(&s, &r), vectorcraft_color::Color::from_hex("#3366cc").unwrap()); +} + +/// Paste on All Artboards leaves copied artboards behind, so their backgrounds raise no mismatch for +/// it: clipboard.profileMismatch with allArtboards lists none, and the paste reports none. A plain +/// paste, which brings the artboard, still lists the background's model. +#[test] +fn paste_on_all_artboards_leaves_artboard_backgrounds_out() { + let _g = settings(); + let _reset = ColorSettingsReset { profile: None, paths: vec![] }; + let mut s = session(); + let ink = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + exec(&mut s, "paint.setFill", json!({"ids": [ink.0], "color": {"c": 20, "m": 40, "y": 60, "k": 10}})); + exec(&mut s, "paint.setStroke", json!({"ids": [ink.0], "none": true})); + exec(&mut s, "artboard.setProps", json!({"index": 0, "color": "#3366cc"})); + exec(&mut s, "edit.assignProfile", json!({"rgb": cms::WIDE_GAMUT_RGB})); + exec(&mut s, "artboard.copy", json!({"index": 0})); + exec(&mut s, "file.new", json!({"width": 100, "height": 100})); + let models = |s: &mut Session, p: serde_json::Value| exec(s, "clipboard.profileMismatch", p)["mismatches"].as_array().unwrap().len(); + assert_eq!(models(&mut s, json!({})), 1, "a plain paste brings the RGB background"); + assert_eq!(models(&mut s, json!({"allArtboards": true})), 0); + assert!(s.execute("clipboard.profileMismatch", &json!({"allArtboards": "yes"})).is_err()); + let r = exec(&mut s, "edit.pasteOnAllArtboards", json!({"profileMismatch": "convert"})); + assert!(r.get("profileMismatch").is_none(), "{r}"); +} + +/// A converting paste back into the document the objects came from (its profile changed since the +/// copy) still takes its image blobs as the document's own: an image whose blob under its key +/// changed since keeps that key, and so shows the document's blob. +#[test] +fn a_converting_paste_into_its_own_document_keeps_its_image_keys() { + let _g = settings(); + let _reset = ColorSettingsReset { profile: None, paths: vec![] }; + let mut s = session(); + let blue = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + exec(&mut s, "paint.setFill", json!({"ids": [blue.0], "color": "#3366cc"})); + let blob = |b: u8| vectorcraft_doc::ImageBlob::png(vec![b; 8]); + let image = s + .edit("Place", |d, _| { + d.images.insert("pic".into(), blob(1)); + let id = d.alloc_id(); + let im = vectorcraft_doc::ImageObject { + key: "pic".into(), + width: 4, + height: 4, + xf: Affine::translate((20.0, 0.0)), + link: None, + placement: Default::default(), + pixels: None, + }; + d.insert(d.default_layer(), 0, vectorcraft_doc::Node::new(id, vectorcraft_doc::NodeKind::Image(Box::new(im))))?; + Ok(id) + }) + .unwrap(); + select(&mut s, &[blue, image]); + exec(&mut s, "edit.copy", json!({})); + s.edit("Replace Image", |d, _| { + d.images.insert("pic".into(), blob(2)); + Ok(()) + }) + .unwrap(); + exec(&mut s, "edit.assignProfile", json!({"rgb": cms::WIDE_GAMUT_RGB})); + let r = exec(&mut s, "edit.paste", json!({"profileMismatch": "convert"})); + assert_eq!(r["profileMismatch"][0]["choice"], "convert"); + let doc = &s.doc().unwrap().doc; + let keys: Vec = r["ids"] + .as_array() + .unwrap() + .iter() + .filter_map(|id| match &doc.node(vectorcraft_doc::NodeId(id.as_u64().unwrap()))?.kind { + vectorcraft_doc::NodeKind::Image(im) => Some(im.key.clone()), + _ => None, + }) + .collect(); + assert_eq!(keys, ["pic"]); + assert_eq!(doc.images.len(), 1, "no copy of the old blob"); +} diff --git a/crates/engine/tests/it/dimensions.rs b/crates/engine/tests/it/dimensions.rs index 17391ae98a..28417f031a 100644 --- a/crates/engine/tests/it/dimensions.rs +++ b/crates/engine/tests/it/dimensions.rs @@ -2080,6 +2080,39 @@ fn a_dimension_of_the_same_points_lines_up_and_the_line_follows_the_pointer() { assert_eq!(recipe(&s, id).line_ends(), (pt(200.0, 186.0), pt(300.0, 186.0))); } +/// A command that moves or hides a dimension while another is placed (Real-time Drawing on) does +/// not leave the placed dimension on a level the committed document does not have: committed with +/// its line near the other dimension's line as the document has it then, it is on that level, and +/// otherwise at the pointer. +#[test] +fn a_dimension_placed_after_a_command_lines_up_with_the_committed_document() { + let plain = ViewInfo::default(); + for (cmd, params, y) in [("dimension.update", json!({"offset": -10.0}), 192.0), ("object.hide", json!({}), 172.0)] { + let (mut s, first) = level_start(plain); + run(&mut s, "prefs.set", json!({"key": "realTimeDrawing", "value": true})); + // The bottom edge dragged out onto the level of the first line. + for (kind, y) in [(PointerKind::Move, 300.0), (PointerKind::Down, 300.0), (PointerKind::Drag, 240.0), (PointerKind::Drag, 172.0)] { + s.pointer(&PointerEvent::new(kind, 160.0, y), plain).unwrap(); + } + let mut params = params; + params["ids"] = json!([first]); + run(&mut s, cmd, params); + if cmd == "dimension.update" { + assert_eq!(recipe(&s, first).line_ends().0.y, 190.0, "moved before the release"); + } + // Released without a drag in between: the release places the dimension. + s.pointer(&PointerEvent::new(PointerKind::Up, 160.0, y), plain).unwrap(); + let placed = s.doc().unwrap().selection.objects[0].0; + assert_ne!(placed, first, "{cmd}: a new dimension"); + let reference = s.doc().unwrap().doc.node(NodeId(first)).map(|n| (n.visible, recipe(&s, first).line_ends().0.y)); + let expected = match reference { + Some((true, level)) if (level - y).abs() <= 4.0 => level, + _ => y, + }; + assert_eq!(recipe(&s, placed).line_ends().0.y, expected, "{cmd}: the other dimension is {reference:?}"); + } +} + /// A dimension dragged out from a segment, with its line within the Smart Guides snapping /// tolerance of the level of another dimension's parallel line, lands on that level. #[test] diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 9227ee199d..eccd6e08b6 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -27,6 +27,7 @@ mod param_keys; mod paste_many; mod pen_click_after_smooth; mod pen_endpoint_picking; +mod pen_rubber_band; mod ruler_guide_nodes; mod ruler_guide_perf; mod ruler_origin; diff --git a/crates/engine/tests/it/pen_rubber_band.rs b/crates/engine/tests/it/pen_rubber_band.rs new file mode 100644 index 0000000000..4d97f1c06b --- /dev/null +++ b/crates/engine/tests/it/pen_rubber_band.rs @@ -0,0 +1,264 @@ +//! The Pen's rubber band after a smooth anchor is the segment the next click adds: a new corner, +//! a close on the first anchor, or a join with an end of another open path. + +use serde_json::json; +use vectorcraft_doc::NodeKind; +use vectorcraft_engine::{Session, ViewInfo}; +use vectorcraft_geom::{CubicBez, PathData, PathEl, Point}; +use vectorcraft_tools::{Overlay, PointerEvent, PointerKind}; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + s +} + +fn view() -> ViewInfo { + ViewInfo { zoom: 1.0, smart_guides: false, snap_to_grid: false, snap_to_pixel: false, snap_to_point: false, ..Default::default() } +} + +fn at(s: &mut Session, v: ViewInfo, kind: PointerKind, p: Point) { + s.pointer(&PointerEvent::new(kind, p.x, p.y), v).unwrap(); +} + +/// A press at `p` dragged to `out`: a smooth anchor with its outgoing handle at `out`. +fn smooth(s: &mut Session, v: ViewInfo, p: Point, out: Point) { + at(s, v, PointerKind::Down, p); + at(s, v, PointerKind::Drag, out); + at(s, v, PointerKind::Up, out); +} + +fn click(s: &mut Session, v: ViewInfo, p: Point) { + at(s, v, PointerKind::Down, p); + at(s, v, PointerKind::Up, p); +} + +/// The rubber band shown with the pointer hovering at `h`, as one cubic segment. +fn band(s: &mut Session, v: ViewInfo, h: Point) -> CubicBez { + at(s, v, PointerKind::Move, h); + let paths: Vec> = + s.overlays(v).into_iter().filter_map(|o| if let Overlay::Path { path, .. } = o { Some(path.elements().to_vec()) } else { None }).collect(); + match paths.as_slice() { + [els] => match els.as_slice() { + [PathEl::MoveTo(p0), PathEl::CurveTo(p1, p2, p3)] => CubicBez::new(*p0, *p1, *p2, *p3), + other => panic!("the rubber band is one curve, got {other:?}"), + }, + other => panic!("one rubber band, got {other:?}"), + } +} + +/// How many rubber bands show with the pointer hovering at `h` with Alt held as `alt` says. +fn bands(s: &mut Session, v: ViewInfo, h: Point, alt: bool) -> usize { + let mut ev = PointerEvent::new(PointerKind::Move, h.x, h.y); + ev.mods.alt = alt; + s.pointer(&ev, v).unwrap(); + s.overlays(v).into_iter().filter(|o| matches!(o, Overlay::Path { .. })).count() +} + +/// The measurement label shown with the pointer hovering at `h`. +fn label(s: &mut Session, v: ViewInfo, h: Point) -> String { + at(s, v, PointerKind::Move, h); + let labels: Vec = + s.overlays(v).into_iter().filter_map(|o| if let Overlay::Measure { text, .. } = o { Some(text) } else { None }).collect(); + match labels.as_slice() { + [text] => text.clone(), + other => panic!("one measurement label, got {other:?}"), + } +} + +fn paths(s: &Session) -> Vec { + let mut v = vec![]; + s.doc().unwrap().doc.walk(|n| { + if let NodeKind::Path { path, .. } = &n.kind { + v.push(path.clone()); + } + }); + v +} + +/// An open path whose first anchor, at `end`, is smooth with its incoming handle at `h_in`. +fn smooth_ended_path(s: &mut Session, end: Point, h_in: Point, other: Point) { + s.execute( + "path.create", + &json!({"anchors": [{"x": end.x, "y": end.y, "in": [h_in.x, h_in.y], "out": [2.0 * end.x - h_in.x, 2.0 * end.y - h_in.y]}, {"x": other.x, "y": other.y}]}), + ) + .unwrap(); + s.execute("select.none", &json!({})).unwrap(); +} + +#[test] +fn rubber_band_is_the_corner_a_click_adds() { + let (mut s, v) = (session(), view()); + s.select_tool("pen", v).unwrap(); + smooth(&mut s, v, Point::new(100.0, 100.0), Point::new(150.0, 60.0)); + let h = Point::new(300.0, 200.0); + let preview = band(&mut s, v, h); + click(&mut s, v, h); + let [path] = paths(&s).try_into().unwrap(); + assert_eq!(path.subpaths[0].segment(0), preview); +} + +#[test] +fn rubber_band_on_the_first_anchor_is_the_closing_segment() { + let (mut s, v) = (session(), view()); + s.select_tool("pen", v).unwrap(); + let first = Point::new(100.0, 100.0); + smooth(&mut s, v, first, Point::new(150.0, 60.0)); + click(&mut s, v, Point::new(300.0, 100.0)); + smooth(&mut s, v, Point::new(300.0, 300.0), Point::new(350.0, 340.0)); + // Within the pick tolerance of the first anchor: the band ends on the anchor, not the pointer. + let preview = band(&mut s, v, Point::new(102.0, 101.0)); + assert_eq!(preview.p3, first); + click(&mut s, v, Point::new(102.0, 101.0)); + let [path] = paths(&s).try_into().unwrap(); + let sp = &path.subpaths[0]; + assert!(sp.closed); + assert_eq!(sp.segment(2), preview); +} + +#[test] +fn rubber_band_on_another_paths_end_is_the_joining_segment() { + let (mut s, v) = (session(), view()); + let end = Point::new(400.0, 300.0); + smooth_ended_path(&mut s, end, Point::new(430.0, 250.0), Point::new(500.0, 300.0)); + s.select_tool("pen", v).unwrap(); + smooth(&mut s, v, Point::new(100.0, 100.0), Point::new(150.0, 60.0)); + let preview = band(&mut s, v, Point::new(402.0, 301.0)); + assert_eq!((preview.p2, preview.p3), (Point::new(430.0, 250.0), end)); + click(&mut s, v, Point::new(402.0, 301.0)); + let [path] = paths(&s).try_into().unwrap(); + assert_eq!(path.subpaths[0].anchors.len(), 3); + assert_eq!(path.subpaths[0].segment(0), preview); +} + +#[test] +fn rubber_band_picks_the_end_at_the_pointer_before_grid_snapping() { + let mut s = session(); + let mut prefs = s.prefs.clone(); + prefs.gridline_every = 100.0; + prefs.grid_subdivisions = 1; + s.apply_prefs(prefs); + let v = ViewInfo { snap_to_grid: true, ..view() }; + // The end is off the grid: the pointer next to it snaps to (100, 300), out of its pick tolerance, + // and a press there still joins at the pointer. + let end = Point::new(63.0, 303.0); + smooth_ended_path(&mut s, end, Point::new(90.0, 250.0), Point::new(13.0, 303.0)); + s.select_tool("pen", v).unwrap(); + smooth(&mut s, v, Point::new(300.0, 500.0), Point::new(350.0, 450.0)); + let pointer = Point::new(64.0, 303.0); + let preview = band(&mut s, v, pointer); + assert_eq!((preview.p2, preview.p3), (Point::new(90.0, 250.0), end)); + click(&mut s, v, pointer); + let [path] = paths(&s).try_into().unwrap(); + assert_eq!(path.subpaths[0].anchors.len(), 3); + assert_eq!(path.subpaths[0].segment(0), preview); +} + +#[test] +fn rubber_band_joins_an_end_the_grid_snaps_to_from_a_corner() { + let mut s = session(); + let mut prefs = s.prefs.clone(); + prefs.gridline_every = 100.0; + prefs.grid_subdivisions = 1; + s.apply_prefs(prefs); + let v = ViewInfo { snap_to_grid: true, ..view() }; + // The end is on the grid and the pointer is out of its pick tolerance: only the snapped point + // joins. The path ends on a corner, so only the end's own handle makes the segment a curve. + let end = Point::new(100.0, 300.0); + smooth_ended_path(&mut s, end, Point::new(130.0, 250.0), Point::new(13.0, 300.0)); + s.select_tool("pen", v).unwrap(); + click(&mut s, v, Point::new(300.0, 500.0)); + let pointer = Point::new(88.0, 300.0); + let preview = band(&mut s, v, pointer); + assert_eq!((preview.p1, preview.p2, preview.p3), (Point::new(300.0, 500.0), Point::new(130.0, 250.0), end)); + click(&mut s, v, pointer); + let [path] = paths(&s).try_into().unwrap(); + assert_eq!(path.subpaths[0].anchors.len(), 3); + assert_eq!(path.subpaths[0].segment(0), preview); +} + +#[test] +fn measurement_label_measures_the_segment_a_click_adds() { + let mut s = session(); + let mut prefs = s.prefs.clone(); + prefs.gridline_every = 100.0; + prefs.grid_subdivisions = 1; + s.apply_prefs(prefs); + let grid = ViewInfo { snap_to_grid: true, ..view() }; + let end = Point::new(63.0, 303.0); + smooth_ended_path(&mut s, end, Point::new(90.0, 250.0), Point::new(13.0, 303.0)); + s.select_tool("pen", grid).unwrap(); + smooth(&mut s, grid, Point::new(300.0, 500.0), Point::new(350.0, 450.0)); + // The pointer snaps to (100, 300), and the click joins at the end: the label measures to the end. + let joining = label(&mut s, grid, Point::new(64.0, 303.0)); + assert_eq!(joining, label(&mut s, view(), end)); +} + +#[test] +fn no_rubber_band_over_the_last_anchor() { + let (mut s, v) = (session(), view()); + s.select_tool("pen", v).unwrap(); + smooth(&mut s, v, Point::new(100.0, 100.0), Point::new(150.0, 60.0)); + smooth(&mut s, v, Point::new(300.0, 300.0), Point::new(350.0, 340.0)); + // A click there retracts the last anchor's outgoing handle and adds no segment. + let h = Point::new(303.0, 300.0); + assert_eq!(bands(&mut s, v, h, false), 0); + click(&mut s, v, h); + let [path] = paths(&s).try_into().unwrap(); + assert_eq!(path.subpaths[0].anchors.len(), 2); +} + +#[test] +fn no_rubber_band_where_alt_converts_an_anchor() { + let (mut s, v) = (session(), view()); + // Another path, in front, starts on an inner anchor of the path being drawn. + let shared = Point::new(300.0, 100.0); + let drawn = s + .execute( + "path.create", + &json!({"anchors": [{"x": 100.0, "y": 100.0, "out": [150.0, 60.0]}, {"x": shared.x, "y": shared.y}, {"x": 300.0, "y": 300.0, "in": [250.0, 260.0], "out": [350.0, 340.0]}]}), + ) + .unwrap()["id"] + .as_u64() + .unwrap(); + smooth_ended_path(&mut s, shared, Point::new(330.0, 50.0), Point::new(400.0, 50.0)); + s.execute("select.set", &json!({"ids": [drawn]})).unwrap(); + s.select_tool("pen", v).unwrap(); + // A click on the last anchor goes on drawing the path. + click(&mut s, v, Point::new(300.0, 300.0)); + let paths_before = paths(&s).len(); + let h = Point::new(301.0, 100.0); + assert_eq!(band(&mut s, v, h).p3, shared); + // With Alt the click hands the anchor under the pointer to the Anchor Point tool and joins nothing. + assert_eq!(bands(&mut s, v, h, true), 0); + let mut down = PointerEvent::new(PointerKind::Down, h.x, h.y); + down.mods.alt = true; + s.pointer(&down, v).unwrap(); + let mut up = PointerEvent::new(PointerKind::Up, h.x, h.y); + up.mods.alt = true; + s.pointer(&up, v).unwrap(); + assert_eq!(paths(&s).len(), paths_before); +} + +#[test] +fn no_rubber_band_where_a_join_merges_the_ends() { + let (mut s, v) = (session(), view()); + // Another path's end lies less than the join's merge distance from where this path ends. + let drawn = s + .execute("path.create", &json!({"anchors": [{"x": 100.0, "y": 100.0, "out": [150.0, 60.0]}, {"x": 300.0, "y": 300.0, "in": [250.0, 260.0], "out": [350.0, 340.0]}]})) + .unwrap()["id"] + .as_u64() + .unwrap(); + smooth_ended_path(&mut s, Point::new(300.000_000_9, 300.0), Point::new(330.0, 250.0), Point::new(400.0, 300.0)); + s.execute("select.set", &json!({"ids": [drawn]})).unwrap(); + s.select_tool("pen", v).unwrap(); + // A click on the last anchor goes on drawing the path. + click(&mut s, v, Point::new(300.0, 300.0)); + // Just out of the pick tolerance of the last anchor and in it of the other end: the click + // merges the two ends into one anchor and adds no segment. + let h = Point::new(305.000_000_5, 300.0); + assert_eq!(bands(&mut s, v, h, false), 0); + click(&mut s, v, h); + let [path] = paths(&s).try_into().unwrap(); + assert_eq!(path.subpaths[0].anchors.len(), 3); +} diff --git a/crates/engine/tests/scissors_snap.rs b/crates/engine/tests/scissors_snap.rs new file mode 100644 index 0000000000..f44b0e6f66 --- /dev/null +++ b/crates/engine/tests/scissors_snap.rs @@ -0,0 +1,156 @@ +//! Scissors receives the view's Smart Guides setting and keeps the split endpoint selected. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use serde_json::json; +use vectorcraft_doc::NodeId; +use vectorcraft_engine::{Session, ViewInfo}; +use vectorcraft_geom::{Affine, PathData, Point}; +use vectorcraft_tools::{Overlay, PointerEvent, PointerKind}; + +fn path(session: &Session, id: NodeId) -> PathData { + session.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().clone() +} + +/// Pixel Preview disables Smart Guides at the Session boundary, rather than asking the tool to +/// interpret that view option. A selected rectangle wins the cut over the crossing line above it. +#[test] +fn scissors_snap_follows_pixel_preview_and_restores_the_cut_selection() { + let mut observed = Vec::new(); + for pixel_preview in [false, true] { + let mut session = Session::new(); + session.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + let rectangle = + NodeId(session.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap()); + let crossing = NodeId(session.execute("shape.line", &json!({"x1": 145, "y1": 90, "x2": 165, "y2": 130})).unwrap()["id"].as_u64().unwrap()); + session.execute("select.set", &json!({"ids": [rectangle.0]})).unwrap(); + let view = ViewInfo { pixel_preview, ..ViewInfo::default() }; + session.select_tool("scissors", view).unwrap(); + let original = path(&session, rectangle); + let line = path(&session, crossing); + let selection_before = session.doc().unwrap().selection.clone(); + let undo_before = session.doc().unwrap().history.undo.len(); + assert!(original.is_closed()); + + session.pointer(&PointerEvent::new(PointerKind::Move, 152.0, 101.5), view).unwrap(); + let intersection = session.overlays(view).iter().any(|o| matches!(o, Overlay::Label { text, .. } if text == "intersect")); + for kind in [PointerKind::Down, PointerKind::Up] { + session.pointer(&PointerEvent::new(kind, 152.0, 101.5), view).unwrap(); + } + + let opened = path(&session, rectangle); + assert_eq!(opened.subpaths.len(), 1); + assert!(!opened.is_closed()); + let anchors = &opened.subpaths[0].anchors; + assert_eq!(anchors.len(), 6); + let cut = anchors.first().unwrap().p; + assert_eq!(anchors.last().unwrap().p, cut, "the cut ends coincide"); + let selected = &session.doc().unwrap().selection; + assert_eq!(selected.objects, [rectangle]); + assert_eq!(selected.anchors.len(), 1); + assert_eq!(selected.partial(rectangle).unwrap().iter().copied().collect::>(), [(0, 0)]); + assert!(selected.segments.is_empty(), "one cut endpoint, not a segment, is selected"); + let selection_after = selected.clone(); + assert_eq!(path(&session, crossing), line); + assert_eq!(session.doc().unwrap().history.undo.len(), undo_before + 1); + + session.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(path(&session, rectangle), original); + assert_eq!(path(&session, crossing), line); + assert_eq!(session.doc().unwrap().selection, selection_before); + assert_eq!(session.doc().unwrap().history.undo.len(), undo_before); + session.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(path(&session, rectangle), opened); + assert_eq!(path(&session, crossing), line); + assert_eq!(session.doc().unwrap().selection, selection_after); + assert_eq!(session.doc().unwrap().history.undo.len(), undo_before + 1); + observed.push((pixel_preview, cut, intersection)); + } + + // Observe both producer rows before checking the original failure: without Scissors snapping, + // Smart Guides on cuts at (152, 100), rather than the intersection at (150, 100). + for (pixel_preview, cut, intersection) in observed { + let expected = Point::new(if pixel_preview { 152.0 } else { 150.0 }, 100.0); + assert!(cut.distance(expected) < 1e-6, "Pixel Preview {pixel_preview}: cut {cut:?}, expected {expected:?}"); + assert_eq!(intersection, !pixel_preview, "Pixel Preview {pixel_preview}: intersection feedback"); + } +} + +/// A command that ends an actual drag must settle its deferred move before Scissors reads the +/// document. Real-time drawing is the control: both routes cut the same moved geometry. +#[test] +fn scissors_cuts_after_a_command_settles_a_deferred_move() { + for real_time_drawing in [true, false] { + let mut session = Session::new(); + session.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + let rectangle = + NodeId(session.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap()); + let crossing = NodeId(session.execute("shape.line", &json!({"x1": 185, "y1": 110, "x2": 205, "y2": 150})).unwrap()["id"].as_u64().unwrap()); + session.execute("select.set", &json!({"ids": [rectangle.0]})).unwrap(); + session.execute("prefs.set", &json!({"key": "realTimeDrawing", "value": real_time_drawing})).unwrap(); + let drag_view = ViewInfo { smart_guides: false, snap_to_point: false, snap_to_grid: false, snap_to_pixel: false, ..ViewInfo::default() }; + session.select_tool("selection", drag_view).unwrap(); + let original = path(&session, rectangle); + let moved = original.transformed(Affine::translate((40.0, 20.0))); + let line = path(&session, crossing); + let undo_before = session.doc().unwrap().history.undo.len(); + + session.pointer(&PointerEvent::new(PointerKind::Down, 150.0, 150.0), drag_view).unwrap(); + session.pointer(&PointerEvent::new(PointerKind::Drag, 190.0, 170.0), drag_view).unwrap(); + assert!(session.in_interaction(), "the pointer drag is still held"); + if real_time_drawing { + assert_eq!(path(&session, rectangle), moved); + assert!(!session.interaction_unapplied(), "the real-time preview is already applied"); + } else { + assert_eq!(path(&session, rectangle), original, "the non-real-time drag has not changed the stored geometry yet"); + assert!(session.interaction_unapplied(), "an actual Selection move is pending"); + let state = session.doc().unwrap(); + let (command, params) = state.interaction.as_ref().unwrap().preview.as_ref().unwrap(); + assert_eq!(command, "object.transform"); + let matrix: Vec = params["matrix"].as_array().unwrap().iter().map(|value| value.as_f64().unwrap()).collect(); + assert_eq!(matrix, [1.0, 0.0, 0.0, 1.0, 40.0, 20.0], "the pending move keeps its exact translation"); + } + // command.batch settles the interaction before its steps; selecting the same object + // changes no geometry and adds no separate undo step. + session + .execute( + "command.batch", + &json!({ + "label": "Keep selection", "commands": [{"command": "select.set", "params": {"ids": [rectangle.0]}}] + }), + ) + .unwrap(); + assert!(!session.in_interaction()); + assert_eq!(path(&session, rectangle), moved, "the command keeps the pending move: real-time={real_time_drawing}"); + assert!(path(&session, rectangle).is_closed()); + assert_eq!(path(&session, crossing), line); + assert_eq!(session.doc().unwrap().history.undo.len(), undo_before + 1); + + // Finish the physical gesture before changing tools. Releasing after the command has + // settled it must neither repeat the transform nor discard its committed geometry. + session.pointer(&PointerEvent::new(PointerKind::Up, 190.0, 170.0), drag_view).unwrap(); + assert!(!session.in_interaction()); + assert_eq!(path(&session, rectangle), moved, "release keeps exactly one move"); + assert_eq!(path(&session, crossing), line); + assert_eq!(session.doc().unwrap().history.undo.len(), undo_before + 1); + + let cut_view = ViewInfo::default(); + session.select_tool("scissors", cut_view).unwrap(); + session.pointer(&PointerEvent::new(PointerKind::Move, 192.0, 121.5), cut_view).unwrap(); + for kind in [PointerKind::Down, PointerKind::Up] { + session.pointer(&PointerEvent::new(kind, 192.0, 121.5), cut_view).unwrap(); + } + let opened = path(&session, rectangle); + assert!(!opened.is_closed()); + let anchors = &opened.subpaths[0].anchors; + let cut = anchors.first().unwrap().p; + assert!(cut.distance(Point::new(190.0, 120.0)) < 1e-6, "the current moved path snaps to its intersection"); + assert_eq!(anchors.last().unwrap().p, cut); + assert_eq!(path(&session, crossing), line); + assert_eq!(session.doc().unwrap().history.undo.len(), undo_before + 2); + session.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(path(&session, rectangle), moved, "undoing the cut retains the earlier settled move"); + assert_eq!(path(&session, crossing), line); + assert_eq!(session.doc().unwrap().selection.objects, [rectangle]); + assert_eq!(session.doc().unwrap().history.undo.len(), undo_before + 1); + } +} diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index 3c2b229e1f..22d3203e3b 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -10636,8 +10636,9 @@ fn a_brushs_mask_art_isnt_written_as_a_styled_object_with_its_id() { } /// Settings the other tests don't use come back: a Calligraphic brush varying with tilt and bearing, -/// a Scatter brush keeping its art's colors whose rotation doesn't follow the path, and brushes whose -/// modes aren't given (the reader gives them, the same ones). +/// a Scatter brush keeping its art's colors whose rotation doesn't follow the path, a Calligraphic +/// and a Scatter brush whose size follows an airbrush pen's finger wheel, and brushes whose modes +/// aren't given (the reader gives them, the same ones). #[test] fn more_brush_settings_are_read_back() { use vectorcraft_brush::{Brush, BrushKind, Calligraphic, Colorization, Scatter, Variation}; @@ -10662,8 +10663,20 @@ fn more_brush_settings_are_read_back() { let lib = vec![ Brush { name: "Tilted".into(), kind: BrushKind::Calligraphic(tilted.clone()) }, Brush { name: "Still".into(), kind: BrushKind::Scatter(scatter.clone()) }, - Brush { name: "Unset nib".into(), kind: BrushKind::Calligraphic(Calligraphic { modes: None, ..tilted }) }, - Brush { name: "Unset spray".into(), kind: BrushKind::Scatter(Scatter { modes: None, ..scatter }) }, + Brush { name: "Unset nib".into(), kind: BrushKind::Calligraphic(Calligraphic { modes: None, ..tilted.clone() }) }, + Brush { name: "Unset spray".into(), kind: BrushKind::Scatter(Scatter { modes: None, ..scatter.clone() }) }, + Brush { + name: "Wheel nib".into(), + kind: BrushKind::Calligraphic(Calligraphic { modes: Some([Variation::Fixed, Variation::Fixed, Variation::StylusWheel]), ..tilted }), + }, + Brush { + name: "Wheel spray".into(), + kind: BrushKind::Scatter(Scatter { + size: (40.0, 160.0), + modes: Some([Variation::StylusWheel, Variation::Fixed, Variation::Fixed, Variation::Fixed]), + ..scatter + }), + }, ]; let mut doc = Document::new(300.0, 200.0); vectorcraft_brush::store(&mut doc, &lib); diff --git a/crates/eps/src/ai_editing/writer/brushes.rs b/crates/eps/src/ai_editing/writer/brushes.rs index ac7ca48ac8..c24dbdf1d7 100644 --- a/crates/eps/src/ai_editing/writer/brushes.rs +++ b/crates/eps/src/ai_editing/writer/brushes.rs @@ -96,6 +96,7 @@ fn code(v: Variation) -> f64 { Variation::Fixed => 0.0, Variation::Random => 1.0, Variation::Pressure => 2.0, + Variation::StylusWheel => 3.0, Variation::Tilt => 4.0, Variation::Bearing => 5.0, Variation::Rotation => 6.0, diff --git a/crates/eps/src/import/ai/brush.rs b/crates/eps/src/import/ai/brush.rs index da7f4c3576..ab2473ae4f 100644 --- a/crates/eps/src/import/ai/brush.rs +++ b/crates/eps/src/import/ai/brush.rs @@ -209,12 +209,13 @@ fn numbers(s: &str) -> Option> { s.split_whitespace().map(|w| w.parse::().ok().filter(|v| v.is_finite())).collect() } -/// How a value varies, by its code: `None` for the stylus wheel and codes that aren't known. +/// How a value varies, by its code: `None` for codes that aren't known. fn variation(code: f64) -> Option { match code { 0.0 => Some(Variation::Fixed), 1.0 => Some(Variation::Random), 2.0 => Some(Variation::Pressure), + 3.0 => Some(Variation::StylusWheel), 4.0 => Some(Variation::Tilt), 5.0 => Some(Variation::Bearing), 6.0 => Some(Variation::Rotation), diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index ab7165c7a1..b33800934e 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -11161,11 +11161,11 @@ fn a_gradients_br_is_not_a_brush() { /// The Brush Options codes for how a Calligraphic brush's values vary: Tilt, Bearing and Rotation /// are the pen's other channels (#372: a 6D Art Pen brush varies its diameter with the pressure, -/// its roundness with the bearing and its angle with the barrel's rotation). The stylus wheel isn't -/// read: it varies at random, as an unknown code does. +/// its roundness with the bearing and its angle with the barrel's rotation), and code 3 is an +/// airbrush pen's finger wheel. An unknown code varies at random. #[test] fn a_calligraphic_brushs_pen_channels_come_in_by_their_codes() { - use vectorcraft_brush::Variation::{Bearing, Fixed, Pressure, Random, Rotation, Tilt}; + use vectorcraft_brush::Variation::{Bearing, Fixed, Pressure, Random, Rotation, StylusWheel, Tilt}; let modes = |params: &str| { let d = brush::parse_tool_object(brush::Tool::Calligraphic, "Pen", params).unwrap(); let brush::DraftKind::Calligraphic(c) = d.kind else { panic!("{d:?}") }; @@ -11173,8 +11173,9 @@ fn a_calligraphic_brushs_pen_channels_come_in_by_their_codes() { }; assert_eq!(modes("1 51 69 13 57 -346 14 2 5 6 0"), [Rotation, Bearing, Pressure]); assert_eq!(modes("1 2 6 40 60 -30 10 4 4 4 0"), [Tilt, Tilt, Tilt]); - assert_eq!(modes("1 2 6 40 60 -30 10 3 3 3 0"), [Random, Random, Random], "the stylus wheel"); - assert_eq!(modes("1 4 4 50 50 10 10 3 9 9 0"), [Fixed, Fixed, Fixed], "nothing to vary"); + assert_eq!(modes("1 2 6 40 60 -30 10 3 3 3 0"), [StylusWheel, StylusWheel, StylusWheel], "the stylus wheel"); + assert_eq!(modes("1 2 6 40 60 -30 10 7 9 7 0"), [Random, Random, Random], "unknown codes"); + assert_eq!(modes("1 4 4 50 50 10 10 7 9 9 0"), [Fixed, Fixed, Fixed], "nothing to vary"); } /// A 6D Art Pen brush: diameter 4 to 8 with the pressure, roundness 30 to 50 with the bearing and diff --git a/crates/eps/src/import/ate.rs b/crates/eps/src/import/ate.rs index 96a408ae7d..ef765c5909 100644 --- a/crates/eps/src/import/ate.rs +++ b/crates/eps/src/import/ate.rs @@ -1189,6 +1189,12 @@ impl Story { self.text.len() } + /// Is frame `frame` of the story point type with nothing but spaces and line ends (its last + /// `\r` left out), which [`Self::node`] doesn't make: it draws nothing. + pub(super) fn blank_point(&self, frame: usize) -> bool { + frame == 0 && matches!(self.frames.first(), Some(FrameKind::Point(_))) && self.is_blank() + } + /// The point frame's matrix (the first frame's, when it is one), else the identity. fn matrix(&self) -> [f64; 6] { match self.frames.first() { @@ -1260,6 +1266,24 @@ impl Story { /// document), or `None` for type that is mirrored, has no size, or a frame past the first of /// threaded type (the first frame holds the whole story). pub(super) fn node(&self, id: NodeId, frame: usize, template: (f64, f64), to_doc: Affine) -> Option { + self.made_node(id, frame, template, to_doc, false) + } + + /// For a blank story (nothing but spaces and line ends) in an area frame or on a path, an empty + /// text object with that frame or path, as [`Self::node`] would make it, as VectorCraft's Type + /// tool keeps such an empty frame (#85, #154). Its text is the story's, spaces kept. `None` for + /// any other story or frame. + pub(super) fn blank_frame_node(&self, id: NodeId, frame: usize, template: (f64, f64), to_doc: Affine) -> Option { + self.is_blank().then(|| self.made_node(id, frame, template, to_doc, true)).flatten() + } + + /// Is the story's text nothing but spaces and line ends (`\r`, and `\x03`, a line break)? + pub(super) fn is_blank(&self) -> bool { + self.text.chars().all(|c| c.is_whitespace() || c == '\x03') + } + + /// [`Self::node`]; with `blank_frame`, a blank story in an area frame or on a path is made too. + fn made_node(&self, id: NodeId, frame: usize, template: (f64, f64), to_doc: Affine, blank_frame: bool) -> Option { let kind = self.frames.get(frame)?; let threaded = frame > 0; let (scale, xf, kind) = match kind { @@ -1301,7 +1325,9 @@ impl Story { }) .collect() }; - if text.trim().is_empty() && !threaded { + // A blank story isn't made here: the page may still have type for its object. What is left + // of one, an area frame or a path, is made by [`Self::blank_frame_node`]. + if text.trim().is_empty() && !threaded && !(blank_frame && !matches!(kind, TextKind::Point)) { return None; } // The text document measures in the art's units too: the document's scale carries its diff --git a/crates/eps/src/import/native/build.rs b/crates/eps/src/import/native/build.rs index 5a2282f807..2cba146548 100644 --- a/crates/eps/src/import/native/build.rs +++ b/crates/eps/src/import/native/build.rs @@ -531,12 +531,12 @@ pub(super) fn build_weighing( clip_by_type(&mut layers, &type_clips, &filled); doc.layers = layers; made.sort(); - let threaded_frames: BTreeSet = - made.chunk_by(|a, b| a.0 == b.0).filter(|thread| thread.len() > 1).flatten().map(|(_, _, id)| *id).collect(); + let threads = threads_of(&made); + let threaded_frames: BTreeSet = threads.iter().flat_map(|(_, ids)| ids.iter().copied()).collect(); if !unread.is_empty() { let Some(frame) = frame.as_ref() else { return Err(unread_error(&unread)) }; let mut copied = BTreeSet::new(); - let kinds = replace_unread(&mut doc, frame, &unread, &unread_elsewhere, &threaded_frames, &mut copied)?; + let kinds = replace_unread(&mut doc, frame, &unread, &unread_elsewhere, &held_frames(&infos, &stories, &threads), &mut copied)?; // With the text objects filled, the page art chosen can differ from the first try's: the // page's type set aside for it, and no other, must be in it. let all_copied = |o: &Vec>| !o.is_empty() && o.iter().all(|n| copied.contains(&n.id)); @@ -545,12 +545,8 @@ pub(super) fn build_weighing( } notes.push(format!("{}: they came in as the page's art", kinds.join(", "))); } - // A story in several frames is threaded type: its frames in order (the first holds the story). - for thread in made.chunk_by(|a, b| a.0 == b.0) { - if thread.len() > 1 { - doc.text_threads.push(thread.iter().map(|(_, _, id)| *id).collect()); - } - } + // The frames still threaded: a blank story's frame an unread object left alone isn't. + let threaded_frames = add_threads(&mut doc, threads, &threaded_frames, !unread.is_empty()); // Area type flows around the wrap objects above it before it is compared with the page. resolve_text_wrap(&mut doc)?; let bound_text = bound_slots(&doc, &bindings, &xml_ids, VariableKind::Text); @@ -1485,7 +1481,9 @@ fn slot_content( ) -> Result<(Vec, bool), String> { let made = make_slots(infos, stories, template, to_doc, notes); if let Some(own) = own.filter(|_| readable_all(infos, &made)) { - return Ok((made_only(infos, made, [own, pages[1]], notes), true)); + let mut content = made_only(infos, stories, made, [own, pages[1]], notes); + settle_blank_stories(infos, stories, template, to_doc, &mut content, notes); + return Ok((content, true)); } // The page's type is matched with every text object whose type isn't made, and weighed against // where every made one draws: that has its limits (the slots of type that looks draw are within @@ -1494,7 +1492,100 @@ fn slot_content( if open > MAX_SLOTS || infos.len().saturating_mul(pages[0].len()) > MAX_PAIRS { return Err("it has too many text objects".into()); } - Ok((plan(infos, stories, made, template, to_doc, pages, notes), false)) + let mut content = plan(infos, stories, made, template, to_doc, pages, notes); + settle_blank_stories(infos, stories, template, to_doc, &mut content, notes); + Ok((content, false)) +} + +/// The threads of the text objects `made` (story, frame and id of each, sorted): each story in +/// several frames, with its frames in order (the first holds the story). +fn threads_of(made: &[(u32, usize, NodeId)]) -> Vec<(u32, Vec)> { + made.chunk_by(|a, b| a.0 == b.0) + .filter(|thread| thread.len() > 1) + .map(|thread| (thread[0].0, thread.iter().map(|(_, _, id)| *id).collect())) + .collect() +} + +/// The frames of `threads` that an unread object can't take with it: those of a blank story's thread +/// hold no type, so they may go. +fn held_frames(infos: &[SlotInfo], stories: &[Option>], threads: &[(u32, Vec)]) -> BTreeSet { + let blank: BTreeSet = + infos.iter().zip(stories).filter(|(_, s)| s.as_ref().is_some_and(|s| s.is_blank())).filter_map(|(i, _)| i.story).collect(); + threads.iter().filter(|(story, _)| !blank.contains(story)).flat_map(|(_, ids)| ids.iter().copied()).collect() +} + +/// `threads` as `doc`'s text threads, and the frames of the threads added. With `replaced` (unread +/// objects were replaced by page art), the frames they took with them (`frames` that `doc` no longer +/// has, only a blank story's) are left out, and so is a thread left with one frame. +fn add_threads(doc: &mut Document, threads: Vec<(u32, Vec)>, frames: &BTreeSet, replaced: bool) -> BTreeSet { + let present = replaced.then(|| doc.index_paths(frames.iter().copied())); + let mut threaded = BTreeSet::new(); + for (_, mut ids) in threads { + if let Some(present) = &present { + ids.retain(|id| present.contains_key(id)); + } + if ids.len() > 1 { + threaded.extend(ids.iter().copied()); + doc.text_threads.push(ids); + } + } + threaded +} + +/// The slots of blank stories (nothing but spaces and line ends) that neither the text document nor +/// the page fills: blank point type draws nothing and has nothing to keep, so it is left out without +/// a note, as VectorCraft's Type tool discards empty point type (#85, #154); blank area type and +/// type on a path come in as an empty text object with their frame or path, as the Type tool keeps +/// such an empty frame, also where the page's type went to another text object (`Merged`). An empty +/// frame draws nothing, so the page can't show it: it is kept without being weighed against the +/// page (`prune_unseen` would take it out), and so are the later frames of its thread, which the +/// text document makes empty. Type that a look draws is left as it is. +fn settle_blank_stories( + infos: &[SlotInfo], + stories: &[Option>], + template: Option<(f64, f64)>, + to_doc: Affine, + content: &mut [Content], + notes: &mut Vec, +) { + // The stories whose first frame came in as an empty frame: their later frames stay with it. + let mut kept = BTreeSet::new(); + for ((story, info), c) in stories.iter().zip(infos).zip(content.iter_mut()) { + let Some(story) = story.as_ref().filter(|s| s.is_blank() && info.look.is_none()) else { continue }; + let unfilled = match c { + Content::Empty => true, + Content::Page(parts) => parts.is_empty(), + _ => false, + }; + if story.blank_point(info.frame) { + if unfilled { + *c = Content::Merged; + } + } else if (unfilled || matches!(c, Content::Merged)) + && let Some((node, region)) = template.and_then(|t| super::plan::blank_frame(info, story, t, to_doc)) + { + *c = Content::Made(node, region.filter(|_| info.shown), true); + kept.extend(info.story); + // Its paragraphs' settings are read as made type's are, with the same notes. + for (left_out, note) in [ + (story.tabs_left_out(), crate::import::ate::TABS_LEFT_OUT), + (story.kinsoku_sets_left_out(), crate::import::ate::KINSOKU_SETS_LEFT_OUT), + ] { + if left_out && !notes.iter().any(|n| n == note) { + notes.push(note.into()); + } + } + } + } + for (info, c) in infos.iter().zip(content.iter_mut()) { + if let Content::Made(_, _, seen) = c + && info.frame > 0 + && info.look.is_none() + && info.story.is_some_and(|s| kept.contains(&s)) + { + *seen = true; + } + } } /// The layers `doc` don't draw as the page (`why`), `unseen` text objects of them taken out: the diff --git a/crates/eps/src/import/native/plan.rs b/crates/eps/src/import/native/plan.rs index 005b89397e..17107dded9 100644 --- a/crates/eps/src/import/native/plan.rs +++ b/crates/eps/src/import/native/plan.rs @@ -66,17 +66,10 @@ pub(super) fn make_slots( .map(|(k, info)| { let t = template?; let story = stories.get(k)?.as_ref()?; - let mut node = story.node(NodeId(0), info.frame, t, to_doc)?; + let node = story.node(NodeId(0), info.frame, t, to_doc)?; tabs_left_out |= story.tabs_left_out(); kinsoku_left_out |= story.kinsoku_sets_left_out(); - let mut region = story.region(t, to_doc); - // The first line where the file has it, in the text document's frame (that of a - // copied object is its original's, as its lines are). - story.place_first_line(&mut node, info.frame, t, to_doc); - // Area type and type on a path in the object's own frame: the text document's frame - // of a copied object keeps its original's path. - frame_text_from_art(info, &mut node, &mut region); - story.flip_on_path(&mut node, info.frame); + let (mut node, region) = placed(info, story, node, t, to_doc); if let NodeKind::Text(text) = &mut node.kind && story.fit_first_line(text) { @@ -109,6 +102,28 @@ pub(super) fn make_slots( made } +/// The empty text object a slot of a blank story in an area frame or on a path comes in as, placed +/// as [`make_slots`] places made type: its frame or path, the object's own where it has one +/// ([`Story::blank_frame_node`]). `None` for any other slot. +pub(super) fn blank_frame(info: &SlotInfo, story: &Story, template: (f64, f64), to_doc: Affine) -> Option { + let node = story.blank_frame_node(NodeId(0), info.frame, template, to_doc)?; + let (node, region) = placed(info, story, node, template, to_doc); + Some((Box::new(node), region)) +} + +/// `node`, made from `story` for slot `info`, placed where the file has it, with the region it +/// draws in: the first line where the file has it, in the text document's frame (that of a copied +/// object is its original's, as its lines are); area type and type on a path in the object's own +/// frame (the text document's frame of a copied object keeps its original's path); type on a path +/// flipped as its frame keeps it. +fn placed(info: &SlotInfo, story: &Story, mut node: Node, template: (f64, f64), to_doc: Affine) -> (Node, Option) { + let mut region = story.region(template, to_doc); + story.place_first_line(&mut node, info.frame, template, to_doc); + frame_text_from_art(info, &mut node, &mut region); + story.flip_on_path(&mut node, info.frame); + (node, region) +} + /// Does the file's text document make the type of every slot that shows (at least one does)? Type /// that a look draws doesn't count: only the page has it. pub(super) fn readable_all(infos: &[SlotInfo], made: &[Option]) -> bool { @@ -122,7 +137,13 @@ pub(super) fn readable_all(infos: &[SlotInfo], made: &[Option]) -> bool { /// that no made type takes, shown or not, is left out with a note in `warn`. Slots that don't show /// and whose type isn't made take the page's type that doesn't show (`pages`: the page's text /// objects that show and that don't), by painting order. -pub(super) fn made_only(infos: &[SlotInfo], made: Vec>, pages: [&[Vec>]; 2], warn: &mut Vec) -> Vec { +pub(super) fn made_only( + infos: &[SlotInfo], + stories: &[Option>], + made: Vec>, + pages: [&[Vec>]; 2], + warn: &mut Vec, +) -> Vec { let [shown, hidden] = pages; let mut content = made_content(infos, made); // The page's type where no made type draws, in the copies that looks draw, is theirs (past @@ -154,7 +175,7 @@ pub(super) fn made_only(infos: &[SlotInfo], made: Vec>, pages: [&[V None => warn.push(PAGE_TYPE_UNCHECKED.into()), } drop_look_slots(infos, &mut content); - fill_hidden(infos, &mut content, hidden); + fill_hidden(infos, stories, &mut content, hidden); content } @@ -421,8 +442,10 @@ pub(super) fn plan( } fill_look_slots(infos, &mut content, &mut spare); // What is left of the page goes by painting order into the shown slots the file can't say. - let loose: Vec = - infos.iter().enumerate().filter(|(k, i)| i.shown && matches!(content.get(*k), Some(Content::Empty))).map(|(k, _)| k).collect(); + let loose = readable_first( + stories, + infos.iter().enumerate().filter(|(k, i)| i.shown && matches!(content.get(*k), Some(Content::Empty))).map(|(k, _)| k).collect(), + ); if loose.is_empty() { // Type of the page that no text object says it owns goes with the nearest text object that has // type of the page (never into made type); with none, it is left out. @@ -466,17 +489,28 @@ pub(super) fn plan( warn.push("the text is on the layers in the order the page paints it, so a text object may be in another group than it was".into()); } } - fill_hidden(infos, &mut content, hidden); + fill_hidden(infos, stories, &mut content, hidden); content } +/// The slots `open` that are to take the page's type left over, by painting order: those of blank +/// stories (nothing but spaces and line ends) only when no other slot is open, as such a story has +/// no type of its own; the blank ones left out come in empty or not at all (see +/// `settle_blank_stories`). +fn readable_first(stories: &[Option>], open: Vec) -> Vec { + let blank = |k: &usize| stories.get(*k).and_then(Option::as_ref).is_some_and(|s| s.is_blank()); + if open.iter().all(blank) { open } else { open.into_iter().filter(|k| !blank(k)).collect() } +} + /// The page's type that doesn't show (`hidden`) goes by painting order into the slots that don't -/// show and have nothing yet, but for what is the type of made type that doesn't show: a page object +/// show and have nothing yet ([`readable_first`]), but for what is the type of made type that doesn't show: a page object /// with words and at least half of it where such type draws, while the type has all its words left /// (each word an object takes is the type's no longer). Past `MAX_PAIRS` comparisons all of it goes. -fn fill_hidden(infos: &[SlotInfo], content: &mut [Content], hidden: &[Vec>]) { - let unread: Vec = - infos.iter().enumerate().filter(|(k, i)| !i.shown && matches!(content.get(*k), Some(Content::Empty))).map(|(k, _)| k).collect(); +fn fill_hidden(infos: &[SlotInfo], stories: &[Option>], content: &mut [Content], hidden: &[Vec>]) { + let unread = readable_first( + stories, + infos.iter().enumerate().filter(|(k, i)| !i.shown && matches!(content.get(*k), Some(Content::Empty))).map(|(k, _)| k).collect(), + ); if unread.is_empty() { return; } diff --git a/crates/eps/src/import/native/slots.rs b/crates/eps/src/import/native/slots.rs index bce43140d1..ebd6deef88 100644 --- a/crates/eps/src/import/native/slots.rs +++ b/crates/eps/src/import/native/slots.rs @@ -2,7 +2,7 @@ use super::build::MADE; use super::{AppearanceItem, Arc, BTreeSet, BlendMode, Document, Node, NodeId, NodeKind, PathData, Point, Rect, ai, slot_of}; /// The notes that say the import left out something the file has (see [`is_loss`]). -pub(super) const TEXT_LEFT_OUT: &str = "text objects on hidden layers or hidden objects couldn't be read, so they are left out"; +pub(super) const TEXT_LEFT_OUT: &str = "text objects whose type couldn't be read from the file's text document or its page are left out"; /// The same for a file without a page to take shown type from. pub(super) const TYPE_LEFT_OUT: &str = "text objects of kinds VectorCraft doesn't read from the file's text document yet are left out"; @@ -230,7 +230,8 @@ pub(super) enum Content { /// Text objects (with the strokes round them) of the page. Page(Vec>), /// A text object made from the file's text document, where it draws on the document (when it - /// shows), and whether the page has type where it is. + /// shows), and whether it is kept without being weighed against the page: the page has type + /// where it is, or it draws nothing (an empty frame of a blank story). Made(Box, Option, bool), /// Nothing the file lets this read. Empty, diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index dc0f225872..f809141202 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -3830,7 +3830,7 @@ fn type_with_a_frame_it_cant_read_is_left_out_with_a_note() { let art = native_with_text(&(layer("Back", true, &square(10, 10)) + &layer("Spare", false, &text_object(0))), &doc); let r = import(&eps(&page_square(10, 10), &art)).unwrap(); assert!(text_of(&r.document.layers[1]).is_empty()); - assert!(r.warnings.iter().any(|w| w.contains("1 text objects on hidden layers")), "{:?}", r.warnings); + assert!(r.warnings.iter().any(|w| w.contains("1 text objects whose type couldn't be read")), "{:?}", r.warnings); assert!(crate::is_loss(r.warnings.iter().find(|w| w.contains("couldn't be read")).unwrap())); } @@ -5030,6 +5030,274 @@ fn area_type_keeps_its_area_type_options() { assert_eq!(texts[2].area, vectorcraft_doc::AreaOptions::default()); } +/// A blank story in an area frame, hidden or shown, comes in as a text object that keeps its frame +/// and draws nothing (its spaces kept), as VectorCraft's Type tool keeps an empty frame (#85, #154). +/// As point type, hidden or shown, it draws nothing and has nothing to keep: it is left out, without +/// a note that something wasn't read. +#[test] +fn blank_stories_keep_their_area_frame_and_leave_point_type_out_quietly() { + let frames = [area_frame(10.0, 50.0, 90.0, 90.0), point_frame(20.0, 20.0), point_frame(30.0, 30.0), area_frame(60.0, 10.0, 90.0, 40.0)]; + let stories = [ + story("\\r", &[0], "/0 0", "/1 6.0"), + story("\\r", &[1], "/0 0", "/1 6.0"), + story(" \\r", &[2], "/0 0", "/1 6.0"), + story(" \\r", &[3], "/0 0", "/1 6.0"), + ]; + let doc = document_of(&frames, &stories); + // A shown blank area frame too: it draws nothing, so the page can't show it, and it stays. + let shown = square(10, 10) + &text_object(2) + &text_object(3); + let art = native_with_text(&(layer("Back", true, &shown) + &layer("Spare", false, &(text_object(0) + &text_object(1)))), &doc); + let r = import(&eps(&page_square(10, 10), &art)).unwrap(); + let texts = text_of(&r.document.layers[1]); + assert_eq!(texts.len(), 1, "{:?}", r.warnings); + assert_eq!(texts[0].plain_text(), ""); + let vectorcraft_doc::TextKind::Area { frame } = &texts[0].kind else { panic!("area type: {:?}", texts[0].kind) }; + // Art y 50..90 is 10..50 down the 100 pt page. + let b = frame.bounds().unwrap(); + assert!((b.x0 - 10.0).abs() < 1e-6 && (b.y0 - 10.0).abs() < 1e-6 && (b.x1 - 90.0).abs() < 1e-6 && (b.y1 - 50.0).abs() < 1e-6, "{b:?}"); + let shown = text_of(&r.document.layers[0]); + assert_eq!(shown.len(), 1, "{:?}", r.warnings); + assert_eq!(shown[0].plain_text(), " "); + let vectorcraft_doc::TextKind::Area { frame } = &shown[0].kind else { panic!("area type: {:?}", shown[0].kind) }; + // Art y 10..40 is 60..90 down the page. + let b = frame.bounds().unwrap(); + assert!((b.x0 - 60.0).abs() < 1e-6 && (b.y0 - 60.0).abs() < 1e-6 && (b.x1 - 90.0).abs() < 1e-6 && (b.y1 - 90.0).abs() < 1e-6, "{b:?}"); + assert!(!r.warnings.iter().any(|w| w.contains("couldn't be read")), "{:?}", r.warnings); +} + +/// A blank story whose object the page still draws type for takes the page's type, as before: the +/// empty frame is only for a slot nothing else fills. +#[test] +fn a_blank_area_story_the_page_draws_type_for_takes_the_pages_type() { + let doc = document_of(&[area_frame(10.0, 50.0, 90.0, 90.0)], &[story("\\r", &[0], "/0 0", "/1 6.0")]); + let art = native_with_text(&layer("Art", true, &text_object(0)), &doc); + let page = "0 0 0 1 setcmykcolor /Helvetica findfont 14 scalefont setfont 20 75 moveto (Hi there) show"; + let r = import(&eps(page, &art)).unwrap(); + let mut all = vec![]; + r.document.walk(|n| { + if let NodeKind::Text(t) = &n.kind { + all.push(t.plain_text()); + } + }); + assert_eq!(all, ["Hi there".to_string()], "{:?}", r.warnings); +} + +/// The text objects of `d`: each one's text and kind, in the layers' order. +fn text_kinds(d: &Document) -> Vec<(String, &'static str)> { + let mut out = vec![]; + d.walk(|n| { + if let NodeKind::Text(t) = &n.kind { + let kind = match t.kind { + vectorcraft_doc::TextKind::Area { .. } => "area", + vectorcraft_doc::TextKind::OnPath { .. } => "path", + _ => "point", + }; + out.push((t.plain_text(), kind)); + } + }); + out +} + +/// A blank story threaded through two shown area frames comes in as both frames, empty and still +/// one thread: the later frame the text document makes empty stays with the first. +#[test] +fn a_blank_story_threaded_through_two_shown_frames_keeps_both() { + let frames = [area_frame(10.0, 60.0, 40.0, 80.0), area_frame(50.0, 60.0, 80.0, 80.0)]; + let doc = document_of(&frames, &[story("\\r", &[0, 1], "/0 0", "/1 10.0")]); + let art = native_with_text(&layer("Art", true, &(square(10, 10) + &frame_object(0, 0) + &frame_object(0, 1))), &doc); + let r = import(&eps(&page_square(10, 10), &art)).unwrap(); + // The thread names only text objects the document has. + assert!(r.document.text_threads.iter().flatten().all(|id| r.document.node(*id).is_some()), "{:?} {:?}", r.document.text_threads, r.warnings); + assert_eq!(text_kinds(&r.document), [("".to_string(), "area"), ("".to_string(), "area")], "{:?}", r.warnings); + let ids: Vec<_> = r.document.layers[0].children().unwrap().iter().filter(|n| matches!(n.kind, NodeKind::Text(_))).map(|n| n.id).collect(); + assert_eq!(r.document.text_threads, [ids]); +} + +/// A blank story threaded from a hidden frame into a shown one: both frames come in, one thread. +#[test] +fn a_blank_story_threaded_from_a_hidden_frame_into_a_shown_one_keeps_both() { + let frames = [area_frame(10.0, 60.0, 40.0, 80.0), area_frame(50.0, 60.0, 80.0, 80.0)]; + let doc = document_of(&frames, &[story("\\r", &[0, 1], "/0 0", "/1 10.0")]); + let art = native_with_text(&(layer("Back", true, &(square(10, 10) + &frame_object(0, 1))) + &layer("Spare", false, &frame_object(0, 0))), &doc); + let r = import(&eps(&page_square(10, 10), &art)).unwrap(); + assert!(r.document.text_threads.iter().flatten().all(|id| r.document.node(*id).is_some()), "{:?} {:?}", r.document.text_threads, r.warnings); + assert_eq!(text_kinds(&r.document), [("".to_string(), "area"), ("".to_string(), "area")], "{:?}", r.warnings); + assert_eq!(r.document.text_threads.len(), 1, "{:?}", r.warnings); + assert_eq!(r.document.text_threads[0].len(), 2, "{:?}", r.warnings); +} + +/// An unread group holding a frame of a blank story's thread is replaced by its page art as for +/// any other text object (the frame holds no type): the layers are read, and the thread, left with +/// one frame, isn't one any more. +#[test] +fn unread_group_holding_a_blank_threaded_frame_is_replaced() { + let frames = [ + format!("<< /0 << /0 [ 0 0 ] /1 << /0 [ {} ] >> /2 << /0 1 >> >> >>", canvas_rect(50.0, 10.0, 54.0, 14.0)), + format!("<< /0 << /0 [ 0 0 ] /1 << /0 [ {} ] >> /2 << /0 1 >> >> >>", canvas_rect(70.0, 10.0, 74.0, 14.0)), + ]; + let text = document_of(&frames, &[story("\\r", &[0, 1], "/0 0", "/1 10.0")]); + for removed in [0, 1] { + let grouped = os1_group(&format!("{}\n{}\nZZ", square(if removed == 0 { 50 } else { 70 }, 10), frame_object(0, removed))); + let other = frame_object(0, 1 - removed); + let art = native_with_text(&(layer("Back", true, &square(10, 10)) + &layer("Mixed", true, &format!("{grouped}\n{other}"))), &text); + let (doc, notes, read) = crate::layered_ai(&private(&art), pdf_three_squares(), vec![], false, true, 1.0); + assert!(read, "removed frame {removed}: {notes:?}"); + assert!(doc.text_threads.is_empty(), "removed frame {removed}: {:?} {notes:?}", doc.text_threads); + assert_eq!(text_kinds(&doc), [("".to_string(), "area")], "removed frame {removed}: {notes:?}"); + } +} + +/// A blank story on a path comes in as empty type on that path. +#[test] +fn a_blank_story_on_a_path_keeps_its_path() { + let (a, b, c) = (canvas(10.0, 70.0), canvas(30.0, 70.0), canvas(50.0, 70.0)); + let path = format!( + "<< /0 << /0 [ 0 0 ] /1 << /0 [ {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} ] >> /2 << /0 2 /6 [ 0.5 2.0 ] >> >> >>", + a.0, a.1, a.0, a.1, b.0, b.1, b.0, b.1, b.0, b.1, b.0, b.1, c.0, c.1, c.0, c.1 + ); + let doc = document_of(&[path], &[story("\\r", &[0], "/0 0", "/1 8.0")]); + let art = native_with_text(&layer("Art", true, &(square(10, 10) + &text_object(0))), &doc); + let r = import(&eps(&page_square(10, 10), &art)).unwrap(); + assert_eq!(text_kinds(&r.document), [("".to_string(), "path")], "{:?}", r.warnings); + let mut on_path = vec![]; + r.document.walk(|n| { + if let NodeKind::Text(t) = &n.kind + && let vectorcraft_doc::TextKind::OnPath { path, start, end } = &t.kind + { + on_path.push((path.bounds(), *start, *end)); + } + }); + // The path as `area_type_and_type_on_a_path_come_from_the_text_document` reads it: 40 pt long, + // the type from a quarter of the way along. + let [(Some(b), start, end)] = on_path.as_slice() else { panic!("{on_path:?}") }; + assert!((b.width() - 40.0).abs() < 1e-6 && (start - 0.25).abs() < 1e-3 && end.is_none(), "{b:?} {start} {end:?}"); +} + +/// Where every shown text object's type comes from the text document (the page isn't matched with +/// them), a hidden blank area story still comes in as its empty frame, and blank point type is left +/// out without a note. +#[test] +fn blank_stories_beside_type_the_text_document_makes() { + let frames = [point_frame(20.0, 20.0), area_frame(10.0, 50.0, 90.0, 90.0), point_frame(30.0, 30.0)]; + let stories = [story("Hi there\\r", &[0], "/0 0", "/1 6.0"), story("\\r", &[1], "/0 0", "/1 6.0"), story("\\r", &[2], "/0 0", "/1 6.0")]; + let doc = document_of(&frames, &stories); + let art = native_with_text( + &(layer("Back", true, &(square(10, 10) + &text_object(0))) + &layer("Spare", false, &(text_object(1) + &text_object(2)))), + &doc, + ); + // The page draws the square and "Hi there" where the text document sets it. + let page = format!("{}\n0 0 0 1 setcmykcolor /Helvetica findfont 6 scalefont setfont 20 20 moveto (Hi there) show", page_square(10, 10)); + let r = import(&eps(&page, &art)).unwrap(); + assert_eq!(text_kinds(&r.document), [("Hi there".to_string(), "point"), ("".to_string(), "area")], "{:?}", r.warnings); + assert!(!r.warnings.iter().any(|w| w.contains("couldn't be read")), "{:?}", r.warnings); +} + +/// Without a page (the editing data alone), a blank area story comes in as its empty frame and +/// blank point type is left out, without the note for type of kinds that aren't read. +#[test] +fn blank_stories_without_a_page() { + let frames = [area_frame(10.0, 50.0, 90.0, 90.0), point_frame(30.0, 30.0)]; + let doc = document_of(&frames, &[story("\\r", &[0], "/0 0", "/1 6.0"), story(" \\r", &[1], "/0 0", "/1 6.0")]); + let art = native_with_text(&layer("Art", true, &(text_object(0) + &text_object(1))), &doc); + let (d, notes) = crate::ai_alone(&private(&art)).unwrap(); + assert_eq!(text_kinds(&d), [("".to_string(), "area")], "{notes:?}"); + assert!(!notes.iter().any(|w| w.contains("left out")), "{notes:?}"); +} + +/// The page's spare type goes to a shown text object the text document can't make, not to a blank +/// story beside it, whichever the page paints first: the blank area story comes in as its empty +/// frame. A blank slot takes the page's type only where no other slot is open. +#[test] +fn spare_page_type_goes_to_the_unread_object_not_the_blank_one() { + // Story 0's frame is of a kind this doesn't read, so neither shown object is made: the page's + // one piece of type is spare. + let frames = [point_frame(20.0, 20.0).replace("/2 << /2 [", "/2 << /0 9 /2 ["), area_frame(10.0, 50.0, 90.0, 90.0)]; + let doc = document_of(&frames, &[story("Hi there\\r", &[0], "/0 0", "/1 6.0"), story("\\r", &[1], "/0 0", "/1 6.0")]); + let page = "0 0 0 1 setcmykcolor /Helvetica findfont 6 scalefont setfont 20 20 moveto (Hi there) show"; + for (order, body) in [("blank first", text_object(1) + &text_object(0)), ("blank last", text_object(0) + &text_object(1))] { + let art = native_with_text(&layer("Art", true, &body), &doc); + let r = import(&eps(page, &art)).unwrap(); + let mut texts = text_kinds(&r.document); + texts.sort(); + assert_eq!(texts, [("".to_string(), "area"), ("Hi there".to_string(), "point")], "{order}: {:?}", r.warnings); + } +} + +/// Two shown blank area stories and one piece of the page's type that no text object owns: with no +/// other slot open, the blank ones take it by painting order; the one left without type comes in as +/// its empty frame, not dropped as merged type. +#[test] +fn a_blank_area_story_the_spare_page_type_skips_keeps_its_frame() { + let frames = [area_frame(10.0, 50.0, 90.0, 90.0), area_frame(10.0, 5.0, 40.0, 30.0)]; + let doc = document_of(&frames, &[story("\\r", &[0], "/0 0", "/1 6.0"), story("\\r", &[1], "/0 0", "/1 6.0")]); + let art = native_with_text(&layer("Art", true, &(text_object(0) + &text_object(1))), &doc); + // Away from both frames, so neither owns it. + let page = "0 0 0 1 setcmykcolor /Helvetica findfont 6 scalefont setfont 60 40 moveto (Hi there) show"; + let r = import(&eps(page, &art)).unwrap(); + let mut texts = text_kinds(&r.document); + texts.sort(); + assert_eq!(texts, [("".to_string(), "area"), ("Hi there".to_string(), "point")], "{:?}", r.warnings); +} + +/// A warp or an envelope holding the second frame of a blank story threaded from a frame outside +/// it: a thread names only text objects the document has. The warped frame stays type, and the +/// thread stays whole, as for other threaded type, whatever the warp's look draws; the frame in the +/// envelope comes in as the envelope's drawn art, and no thread is left. +#[test] +fn a_warp_or_an_envelope_holding_a_frame_of_a_blank_thread_keeps_its_thread_of_text() { + let frames = [area_frame(10.0, 5.0, 40.0, 30.0), area_frame(20.0, 40.0, 80.0, 70.0)]; + let doc = document_of(&frames, &[story("\\r", &[0, 1], "/0 0", "/1 10.0")]); + let envelope = type_envelope_of(0, &arc_keys(0.3), &format!("{}\n", square(30, 50)), "").replace("%_0 /FrameIndex ,", "%_1 /FrameIndex ,"); + assert!(envelope.contains("%_1 /FrameIndex ,")); + let warp: String = frame_object(0, 1).lines().map(|l| format!("%_{l}\n")).collect(); + let warped = format!("u\n0 1 1 0 1 0 0 Xa\n2 2 m\n9 2 L\n9 9 L\n2 9 L\nf\nU\n9 () XW\n{warp}1 (Warped) XW\n"); + let check = |what: &str, d: &Document, notes: &[String]| { + assert!( + d.text_threads.iter().flatten().all(|id| d.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Text(_)))), + "{what}: {:?} {notes:?}", + d.text_threads + ); + }; + let art = native_with_text(&layer("Art", true, &format!("{}\n{}\n{envelope}", square(10, 10), frame_object(0, 0))), &doc); + // The page draws the envelope's drawn art. + let r = import(&eps(&format!("{}\n{}", page_square(10, 10), page_square(30, 50)), &art)).unwrap(); + check("envelope, with the page", &r.document, &r.warnings); + assert!(r.document.text_threads.is_empty(), "{:?} {:?}", r.document.text_threads, r.warnings); + let (d, notes) = crate::ai_alone(&private(&art)).unwrap(); + check("envelope, editing data alone", &d, ¬es); + assert!(d.text_threads.is_empty(), "{:?} {notes:?}", d.text_threads); + let art = native_with_text(&(warped_style(40.0, WarpOn::Object) + &layer("Art", true, &format!("{}\n{warped}", frame_object(0, 0)))), &doc); + let (d, notes) = crate::ai_alone(&private(&art)).unwrap(); + check("warp", &d, ¬es); + assert_eq!(d.text_threads.len(), 1, "{notes:?}"); + assert!(!notes.iter().any(|w| w.starts_with(crate::import::ai::WARPED_TYPE_DRAWN)), "{notes:?}"); +} + +/// A blank story's thread whose first frame an unread group takes with it leaves its other frame +/// alone, no longer threaded: in a warp, that frame is weighed against its look as any warped text +/// object is (the look draws a square the empty frame doesn't, so the look takes its place). +#[test] +fn a_blank_frame_an_unread_group_leaves_alone_in_a_warp_is_weighed_as_lone_type() { + let frames = [ + format!("<< /0 << /0 [ 0 0 ] /1 << /0 [ {} ] >> /2 << /0 1 >> >> >>", canvas_rect(50.0, 10.0, 54.0, 14.0)), + format!("<< /0 << /0 [ 0 0 ] /1 << /0 [ {} ] >> /2 << /0 1 >> >> >>", canvas_rect(70.0, 10.0, 74.0, 14.0)), + ]; + let text = document_of(&frames, &[story("\\r", &[0, 1], "/0 0", "/1 10.0")]); + let grouped = os1_group(&format!("{}\n{}\nZZ", square(50, 10), frame_object(0, 0))); + let own: String = frame_object(0, 1).lines().map(|l| format!("%_{l}\n")).collect(); + let warped = format!("u\n0 1 1 0 1 0 0 Xa\n70 10 m\n74 10 L\n74 14 L\n70 14 L\nf\nU\n9 () XW\n{own}1 (Warped) XW\n"); + let art = native_with_text( + &(warped_style(40.0, WarpOn::Object) + &layer("Back", true, &square(10, 10)) + &layer("Mixed", true, &format!("{grouped}\n{warped}"))), + &text, + ); + let (doc, notes, read) = crate::layered_ai(&private(&art), pdf_three_squares(), vec![], false, true, 1.0); + assert!(read, "{notes:?}"); + assert!(doc.text_threads.is_empty(), "{:?} {notes:?}", doc.text_threads); + assert!(notes.iter().any(|w| w.starts_with(crate::import::ai::WARPED_TYPE_DRAWN)), "{notes:?}"); + // The look took the frame's place: no text object is left. + assert!(text_kinds(&doc).is_empty(), "{:?} {notes:?}", text_kinds(&doc)); +} + /// A point type frame at the point (`x`, `y`) of the art. fn point_frame(x: f64, y: f64) -> String { let (cx, cy) = canvas(x, y); diff --git a/crates/geom/src/curvature.rs b/crates/geom/src/curvature.rs new file mode 100644 index 0000000000..304f20557e --- /dev/null +++ b/crates/geom/src/curvature.rs @@ -0,0 +1,424 @@ +//! The circle that touches a curve at one of its points with the curve's curvature there (its +//! osculating circle): the circle the curve bends along at that point. + +use kurbo::{CubicBez, ParamCurve, ParamCurveDeriv, Point, Vec2}; + +use crate::{AnchorKind, SubPath}; + +/// Why no circle matches a curve at a point. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum NoCircle { + /// The curve is straight there (a straight segment, or the turn of an S curve): the circle + /// would have no end. + Straight, + /// The curve has no single direction there: a cusp, a handle drawn back onto its anchor, or a + /// segment with no length. + Cusp, + /// Two segments meet at an anchor at an angle: the path has no single direction there. + Corner, +} + +/// The circle that touches a curve at one point and bends as the curve does there. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct CurvatureCircle { + /// The point where the circle touches the curve. + pub at: Point, + pub center: Point, + pub radius: f64, + /// The segment is the usual cubic of a circular arc of 90° or less ([`circular_arc`]), and the + /// circle has that arc's own radius rather than the cubic's curvature at the point. + pub nominal: bool, +} + +/// Largest turn (radians) of an arc that [`circular_arc`] takes: a quarter turn. +const MAX_ARC: f64 = std::f64::consts::FRAC_PI_2 * (1.0 + 1e-9); +/// How far apart (as a share of the radius) the arc's two ends may lie from its center. +const RADIUS_TOL: f64 = 1e-4; +/// How far each handle's length may differ from the circular arc's (as a share of it). +const HANDLE_TOL: f64 = 1e-3; +/// Below this sine of the angle between the curve's first two derivatives, the curve is straight. +const STRAIGHT_SIN: f64 = 1e-10; +/// Below this share of the control polygon's length, the curve's direction is not defined. +const CUSP_SHARE: f64 = 1e-9; +/// The largest turn (radians) at an anchor not marked smooth that still counts as smooth: half a +/// degree, which takes in handles rounded to a few decimals in imported files. +const SMOOTH_TURN: f64 = 0.5 * std::f64::consts::PI / 180.0; + +/// The circle that touches segment `c` at `t` (0 to 1) with its curvature there, on the side the +/// segment bends toward, or on the other side with `convex`. A segment that is the usual cubic of +/// a circular arc of 90° or less gives a circle of that arc's radius: on the concave side it is the +/// arc's own circle, and it touches the arc's circle at the point nearest `c` at `t`; on the convex +/// side it touches `c` at `t`, its center one radius out from there. A `t` outside 0 to +/// 1 and a segment whose points are not finite give [`NoCircle::Cusp`]. +pub fn curvature_circle(c: CubicBez, t: f64, convex: bool) -> Result { + let finite = [c.p0, c.p1, c.p2, c.p3].iter().all(|p| p.is_finite()); + if !finite || !(0.0..=1.0).contains(&t) { + return Err(NoCircle::Cusp); + } + let at = c.eval(t); + let (center, radius, nominal) = match circular_arc(c) { + Some((center, radius)) => { + let out = at - center; + let len = out.hypot(); + if len == 0.0 || !len.is_finite() { + return Err(NoCircle::Cusp); + } + if convex { + // One radius out from `at`, so the circle touches the segment at `at` even where + // the cubic strays a little from the arc's circle. + return Ok(CurvatureCircle { at, center: at + out * (radius / len), radius, nominal: true }); + } + // The point of the arc's circle nearest `at`: the circle touches the segment there. + let on = center + out * (radius / len); + return Ok(CurvatureCircle { at: on, center, radius, nominal: true }); + } + None => { + let (center, radius) = osculating(c, t)?; + (center, radius, false) + } + }; + let center = if convex { at + (at - center) } else { center }; + Ok(CurvatureCircle { at, center, radius, nominal }) +} + +/// [`curvature_circle`] at `t` on segment `seg` of `sp`. At an end of the segment where it meets +/// the next or previous segment at a corner, the path has no single direction: that is a +/// [`NoCircle::Corner`]. A segment `sp` lacks is a [`NoCircle::Cusp`]. Segments with no length +/// between the two are passed over, and a closed subpath with one segment of length meets itself. +/// The anchor is smooth when it is marked smooth, with both handles pulled out and no segment of no +/// length passed over to reach it, and the path turns there by less than 90°, or when +/// the two segments leave it within [`SMOOTH_TURN`] of one direction. +pub fn curvature_circle_on(sp: &SubPath, seg: usize, t: f64, convex: bool) -> Result { + let n = sp.segment_count(); + if seg >= n { + return Err(NoCircle::Cusp); + } + let c = sp.segment(seg); + let corner = if start_direction(c) == Vec2::ZERO { + false + } else if t == 0.0 { + neighbor(sp, seg, false).is_some_and(|(prev, skipped)| !smooth(sp, seg, skipped, end_direction(prev), start_direction(c))) + } else if t == 1.0 { + neighbor(sp, seg, true).is_some_and(|(next, skipped)| !smooth(sp, (seg + 1) % n, skipped, end_direction(c), start_direction(next))) + } else { + false + }; + if corner { + return Err(NoCircle::Corner); + } + curvature_circle(c, t, convex) +} + +/// The nearest segment with length before (or with `forward`, after) segment `seg`, and whether +/// segments with no length lay between; `None` at an open end of the subpath. In a closed subpath +/// whose only segment with length is `seg`, that is `seg` itself. +fn neighbor(sp: &SubPath, seg: usize, forward: bool) -> Option<(CubicBez, bool)> { + let n = sp.segment_count(); + for k in 1..=n { + let i = if forward { (seg + k < n || sp.closed).then(|| (seg + k) % n)? } else { (seg >= k || sp.closed).then(|| (seg + n - k) % n)? }; + let s = sp.segment(i); + if start_direction(s) != Vec2::ZERO { + return Some((s, k > 1)); + } + } + None +} + +/// Is the join at anchor `anchor` smooth: marked smooth (with no segment of no length passed +/// over) with the directions `a` into it and `b` out of it less than 90° apart, or `a` and `b` the +/// same within [`SMOOTH_TURN`]? +fn smooth(sp: &SubPath, anchor: usize, skipped: bool, a: Vec2, b: Vec2) -> bool { + let marked = !skipped && sp.anchors.get(anchor).is_some_and(|an| an.kind == AnchorKind::Smooth && an.has_in() && an.has_out()); + let (la, lb) = (a.hypot(), b.hypot()); + let ahead = la > 0.0 && lb > 0.0 && a.dot(b) > 0.0; + ahead && (marked || a.cross(b).abs() <= SMOOTH_TURN.sin() * la * lb) +} + +/// The direction a segment leaves its first anchor in: toward its first control point that is +/// not on that anchor; zero for a segment with no length. +fn start_direction(c: CubicBez) -> Vec2 { + [c.p1 - c.p0, c.p2 - c.p0, c.p3 - c.p0].into_iter().find(|v| v.hypot() > 0.0).unwrap_or_default() +} + +/// The direction a segment reaches its last anchor in, as [`start_direction`] finds it. +fn end_direction(c: CubicBez) -> Vec2 { + [c.p3 - c.p2, c.p3 - c.p1, c.p3 - c.p0].into_iter().find(|v| v.hypot() > 0.0).unwrap_or_default() +} + +/// The center and radius of the circle of curvature of `c` at `t`. +fn osculating(c: CubicBez, t: f64) -> Result<(Point, f64), NoCircle> { + let polygon = c.p0.distance(c.p1) + c.p1.distance(c.p2) + c.p2.distance(c.p3); + let d = c.deriv().eval(t).to_vec2(); + let dd = c.deriv().deriv().eval(t).to_vec2(); + let speed = d.hypot(); + if polygon <= 0.0 || !polygon.is_finite() { + return Err(NoCircle::Cusp); + } + // All four control points on one line: a straight segment, whatever its handles. + let (v1, v2, v3) = (c.p1 - c.p0, c.p2 - c.p0, c.p3 - c.p0); + if [v1.cross(v2), v1.cross(v3), v2.cross(v3)].iter().all(|a| a.abs() <= 1e-12 * polygon * polygon) { + return Err(NoCircle::Straight); + } + if speed <= CUSP_SHARE * polygon { + return Err(NoCircle::Cusp); + } + let cross = d.cross(dd); + if cross.abs() <= STRAIGHT_SIN * speed * dd.hypot().max(polygon) { + return Err(NoCircle::Straight); + } + // The center lies along the normal toward the side the curve turns to, `|d|² / cross` of the + // normal `(-d.y, d.x)` away: its length is the radius, `|d|³ / |cross|`. + let center = c.eval(t) + Vec2::new(-d.y, d.x) * (d.hypot2() / cross); + let radius = speed.powi(3) / cross.abs(); + if !center.is_finite() || !radius.is_finite() { + return Err(NoCircle::Straight); + } + Ok((center, radius)) +} + +/// The center and radius of the circular arc `c` draws, when it is the usual cubic of an arc of +/// 90° or less: its two ends are the same distance from the point where the lines square to its +/// handles meet, and each handle is `4/3 · tan(θ/4)` of the radius long for an arc of θ, pointing +/// along the arc. +pub fn circular_arc(c: CubicBez) -> Option<(Point, f64)> { + let (d0, d3, chord) = (c.p1 - c.p0, c.p3 - c.p2, c.p3 - c.p0); + let (l0, l3) = (d0.hypot(), d3.hypot()); + let usable = |v: f64| v.is_finite() && v != 0.0; + if !usable(l0) || !usable(l3) || !usable(chord.hypot()) || d0.dot(chord) <= 0.0 || d3.dot(chord) <= 0.0 { + return None; + } + // The ends' normals: p0 + s·n0 = p3 + u·n3. + let (n0, n3) = (Vec2::new(-d0.y, d0.x), Vec2::new(-d3.y, d3.x)); + let den = n0.cross(n3); + if den.abs() <= 1e-12 * l0 * l3 { + return None; + } + let center = c.p0 + n0 * (chord.cross(n3) / den); + let (r0, r3) = (c.p0.distance(center), c.p3.distance(center)); + let radius = (r0 + r3) / 2.0; + if !center.is_finite() || !usable(radius) || (r0 - r3).abs() > RADIUS_TOL * radius { + return None; + } + let (a, b) = (c.p0 - center, c.p3 - center); + let turn = a.cross(b).abs().atan2(a.dot(b)); + if turn.is_nan() || turn <= 0.0 || turn > MAX_ARC { + return None; + } + let handle = 4.0 / 3.0 * (turn / 4.0).tan() * radius; + ((l0 - handle).abs() <= HANDLE_TOL * handle && (l3 - handle).abs() <= HANDLE_TOL * handle).then_some((center, radius)) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{Anchor, shapes}; + use kurbo::Rect; + + /// Every segment of a circle drawn by [`shapes::ellipse`] is the usual cubic of a quarter + /// turn, and the circle at any point of it is the circle itself: radius 100, center (150, 150). + #[test] + fn the_curvature_circle_of_a_circle_is_the_circle() { + let pd = shapes::ellipse(Rect::new(50.0, 50.0, 250.0, 250.0)); + let sp = &pd.subpaths[0]; + for seg in 0..sp.segment_count() { + for t in [0.0, 0.3, 0.5, 1.0] { + let got = curvature_circle(sp.segment(seg), t, false).unwrap(); + assert!(got.nominal, "{seg} {t}"); + assert!((got.radius - 100.0).abs() < 1e-9 && got.center.distance(Point::new(150.0, 150.0)) < 1e-9, "{seg} {t}: {got:?}"); + assert!((got.at.distance(got.center) - 100.0).abs() < 1e-9, "the circle touches on its own edge"); + } + } + } + + /// A quarter circle of radius 10,000 whose handles are 0.09% longer than the usual cubic's still + /// counts as the arc, and its middle lies a few points off the arc's circle: on the convex side + /// the circle still touches the segment at that point, one radius from its center. + #[test] + fn the_convex_circle_of_a_near_arc_touches_the_segment() { + let r = 10_000.0; + let k = 4.0 / 3.0 * (std::f64::consts::FRAC_PI_8).tan() * r * 1.0009; + let c = CubicBez::new(Point::new(r, 0.0), Point::new(r, k), Point::new(k, r), Point::new(0.0, r)); + assert!(circular_arc(c).is_some()); + let at = c.eval(0.5); + assert!((at.distance(Point::ORIGIN) - r).abs() > 1.0, "the middle lies off the arc's circle"); + let got = curvature_circle(c, 0.5, true).unwrap(); + assert!(got.nominal); + assert_eq!(got.at, at); + assert!((got.center.distance(at) - got.radius).abs() < 1e-6, "{got:?}"); + assert!(got.center.distance(Point::ORIGIN) > got.radius, "the center is on the side away from the arc's"); + } + + /// The cubic's own radius of curvature on a quarter circle's segment is about 2.2% larger than + /// the circle's at its ends and 0.6% larger at its middle: the nominal radius is the circle's. + #[test] + fn a_circle_segment_bends_near_its_radius() { + let pd = shapes::ellipse(Rect::new(-100.0, -100.0, 100.0, 100.0)); + let seg = pd.subpaths[0].segment(0); + for t in [0.0, 0.5, 1.0] { + let (center, r) = osculating(seg, t).unwrap(); + assert!((r - 100.0).abs() < 2.5 && center.distance(Point::ORIGIN) < 2.5, "{t}: {center:?} {r}"); + } + } + + /// On the parabola y = x² / 200, the curvature at its vertex is 1/100: drawn as a cubic from + /// (-100, 50) to (100, 50), the circle at the middle has radius 100 and center (0, 100), above + /// the curve on the side it bends toward; Shift's other side puts the center at (0, -100). + #[test] + fn the_curvature_circle_at_a_parabola_vertex() { + // The quadratic (-100, 50), (0, -50), (100, 50) raised to a cubic. + let (p0, q, p3) = (Point::new(-100.0, 50.0), Point::new(0.0, -50.0), Point::new(100.0, 50.0)); + let c = CubicBez::new(p0, p0 + (q - p0) * (2.0 / 3.0), p3 + (q - p3) * (2.0 / 3.0), p3); + assert_eq!(circular_arc(c), None); + let got = curvature_circle(c, 0.5, false).unwrap(); + assert!(!got.nominal && got.at.distance(Point::ORIGIN) < 1e-9, "{got:?}"); + assert!((got.radius - 100.0).abs() < 1e-9 && got.center.distance(Point::new(0.0, 100.0)) < 1e-9, "{got:?}"); + let other = curvature_circle(c, 0.5, true).unwrap(); + assert!((other.radius - 100.0).abs() < 1e-9 && other.center.distance(Point::new(0.0, -100.0)) < 1e-9, "{other:?}"); + } + + /// A straight segment, with its handles on its line or on its anchors, and the + /// turning point of an S curve have no curvature circle. + #[test] + fn a_straight_segment_has_no_circle() { + let (a, b) = (Point::new(10.0, 20.0), Point::new(130.0, 70.0)); + let on_line = CubicBez::new(a, a.lerp(b, 0.3), a.lerp(b, 0.7), b); + assert_eq!(curvature_circle(on_line, 0.4, false), Err(NoCircle::Straight)); + // A line's handles sit on its anchors: straight at its ends too. + for t in [0.0, 0.5, 1.0] { + assert_eq!(curvature_circle(CubicBez::new(a, a, b, b), t, false), Err(NoCircle::Straight), "{t}"); + } + let s = CubicBez::new(Point::new(0.0, 0.0), Point::new(50.0, 50.0), Point::new(50.0, -50.0), Point::new(100.0, 0.0)); + assert_eq!(curvature_circle(s, 0.5, false), Err(NoCircle::Straight)); + assert!(curvature_circle(s, 0.25, false).is_ok()); + } + + /// A cusp, a handle drawn back onto its anchor at that end, a segment with no length, points + /// that are not finite and a `t` outside 0 to 1 have no curvature circle. + #[test] + fn a_cusp_has_no_circle() { + let cusp = CubicBez::new(Point::new(0.0, 0.0), Point::new(100.0, 100.0), Point::new(0.0, 100.0), Point::new(100.0, 0.0)); + assert_eq!(curvature_circle(cusp, 0.5, false), Err(NoCircle::Cusp)); + let p = Point::new(5.0, 5.0); + let retracted = CubicBez::new(Point::new(0.0, 0.0), Point::new(0.0, 0.0), Point::new(60.0, 40.0), Point::new(100.0, 0.0)); + assert_eq!(curvature_circle(retracted, 0.0, false), Err(NoCircle::Cusp)); + assert_eq!(curvature_circle(CubicBez::new(p, p, p, p), 0.5, false), Err(NoCircle::Cusp)); + let far = CubicBez::new(Point::new(f64::NAN, 0.0), p, p, Point::new(9.0, 0.0)); + assert_eq!(curvature_circle(far, 0.5, false), Err(NoCircle::Cusp)); + for t in [-0.1, 1.5, f64::NAN] { + assert_eq!(curvature_circle(cusp, t, false), Err(NoCircle::Cusp), "{t}"); + } + } + + /// At an anchor where a curve meets a line at a corner, the path has no single direction, from + /// either segment; at a smooth anchor of a circle, and at the open ends of a path, the circle is + /// drawn. A segment the subpath lacks has none. + #[test] + fn a_corner_anchor_has_no_circle() { + let bp = kurbo::BezPath::from_svg("M0 0 C50 -50 100 -50 150 0 L300 0").unwrap(); + let sp = &crate::PathData::from_bezpath(&bp).subpaths[0]; + assert_eq!(curvature_circle_on(sp, 0, 1.0, false), Err(NoCircle::Corner)); + assert_eq!(curvature_circle_on(sp, 1, 0.0, false), Err(NoCircle::Corner)); + assert_eq!(curvature_circle_on(sp, 1, 0.5, false), Err(NoCircle::Straight)); + assert!(curvature_circle_on(sp, 0, 0.0, false).is_ok() && curvature_circle_on(sp, 0, 0.5, false).is_ok()); + assert_eq!(curvature_circle_on(sp, 2, 0.5, false), Err(NoCircle::Cusp)); + let circle = &shapes::ellipse(Rect::new(0.0, 0.0, 100.0, 100.0)).subpaths[0]; + for seg in 0..4 { + for t in [0.0, 1.0] { + assert!(curvature_circle_on(circle, seg, t, false).is_ok_and(|c| c.nominal), "{seg} {t}"); + } + } + // A closed triangle of curves: the anchor where the last segment meets the first is a corner. + let bp = kurbo::BezPath::from_svg("M0 0 C10 -10 90 -10 100 0 C110 10 60 90 50 100 C40 90 -10 30 0 0 Z").unwrap(); + let tri = &crate::PathData::from_bezpath(&bp).subpaths[0]; + assert!(tri.closed); + assert_eq!(curvature_circle_on(tri, 0, 0.0, false), Err(NoCircle::Corner)); + } + + /// A closed subpath whose only segment with length loops back to its start meets itself at its + /// point: a teardrop's tip is a corner, from both ends of the loop. + #[test] + fn a_loop_that_meets_itself_at_an_angle_has_no_circle_there() { + let a = Point::new(0.0, 0.0); + let tip = |out: Point, back: Point| SubPath::new(vec![Anchor::with_handles(a, a, out), Anchor::with_handles(a, back, a)], true); + let drop = tip(Point::new(100.0, -100.0), Point::new(100.0, 100.0)); + assert_eq!(drop.segment_count(), 2); + assert_eq!(curvature_circle_on(&drop, 0, 0.0, false), Err(NoCircle::Corner)); + assert_eq!(curvature_circle_on(&drop, 0, 1.0, false), Err(NoCircle::Corner)); + assert!(curvature_circle_on(&drop, 0, 0.5, false).is_ok()); + } + + /// A segment with no length between a curve and a line, or a closed subpath whose last anchor + /// repeats its first, still leaves a corner there: the segments with no length are passed over. + #[test] + fn a_corner_behind_a_segment_with_no_length_has_no_circle() { + let (a, b, c) = (Point::new(0.0, 0.0), Point::new(150.0, 0.0), Point::new(300.0, 0.0)); + let curve_in = Anchor::with_handles(b, Point::new(100.0, -50.0), b); + let open = SubPath::new(vec![Anchor::with_handles(a, a, Point::new(50.0, -50.0)), curve_in, Anchor::corner(b), Anchor::corner(c)], false); + assert_eq!(curvature_circle_on(&open, 0, 1.0, false), Err(NoCircle::Corner)); + assert_eq!(curvature_circle_on(&open, 2, 0.0, false), Err(NoCircle::Corner), "from the line's side too"); + assert_eq!(curvature_circle_on(&open, 2, 0.5, false), Err(NoCircle::Straight)); + // A closed triangle of curves drawn back to its first anchor before it closes. + let tri = SubPath::new( + vec![ + Anchor::with_handles(a, a, Point::new(10.0, -10.0)), + Anchor::with_handles(Point::new(100.0, 0.0), Point::new(90.0, -10.0), Point::new(110.0, 10.0)), + Anchor::with_handles(Point::new(50.0, 100.0), Point::new(60.0, 90.0), Point::new(40.0, 90.0)), + Anchor::with_handles(a, Point::new(-10.0, 30.0), a), + ], + true, + ); + assert_eq!(tri.segment_count(), 4); + assert_eq!(curvature_circle_on(&tri, 0, 0.0, false), Err(NoCircle::Corner)); + assert_eq!(curvature_circle_on(&tri, 2, 1.0, false), Err(NoCircle::Corner)); + } + + /// An anchor whose handles turn by a thousandth of a radian, as rounded coordinates leave them, + /// is smooth; one marked smooth is smooth unless its handles turn by 90° or more; a turn of 2° + /// is a corner. + #[test] + fn a_nearly_smooth_or_marked_smooth_anchor_has_a_circle() { + let mid = |out_x: f64, kind: AnchorKind| { + let p = Point::new(100.0, 0.0); + let mut an = Anchor::with_handles(p, Point::new(100.0, -50.0), Point::new(out_x, 50.0)); + an.kind = kind; + let ends = |q: Point, h: Point| Anchor::with_handles(q, h, h); + SubPath::new(vec![ends(Point::new(0.0, 0.0), Point::new(0.0, -50.0)), an, ends(Point::new(0.0, 100.0), Point::new(0.0, 150.0))], false) + }; + let rounded = mid(100.05, AnchorKind::Corner); + assert!(curvature_circle_on(&rounded, 0, 1.0, false).is_ok() && curvature_circle_on(&rounded, 1, 0.0, false).is_ok()); + let turned = 50.0 * 2f64.to_radians().tan(); + assert_eq!(curvature_circle_on(&mid(100.0 - turned, AnchorKind::Corner), 0, 1.0, false), Err(NoCircle::Corner)); + assert!(curvature_circle_on(&mid(100.0 - turned, AnchorKind::Smooth), 0, 1.0, false).is_ok()); + // Marked smooth, with the out handle pointing back along the in handle. + let mut back = mid(100.0, AnchorKind::Smooth); + back.anchors.get_mut(1).unwrap().h_out = Point::new(100.0, -40.0); + assert_eq!(curvature_circle_on(&back, 0, 1.0, false), Err(NoCircle::Corner)); + assert_eq!(curvature_circle_on(&back, 1, 0.0, false), Err(NoCircle::Corner)); + // Marked smooth, with the out handle square to the in handle: a turn of 90°. + let mut square = mid(100.0, AnchorKind::Smooth); + square.anchors.get_mut(1).unwrap().h_out = Point::new(150.0, 0.0); + assert_eq!(curvature_circle_on(&square, 0, 1.0, false), Err(NoCircle::Corner)); + } + + /// An arc's cubic is taken only up to a quarter turn, with both ends on one circle and handles + /// of the arc's length: a third of a circle, a circle squashed into an ellipse and handles 1% + /// too long give the cubic's own curvature. + #[test] + fn only_a_true_arc_of_a_quarter_turn_or_less_is_nominal() { + let arc = |deg: f64, r: f64, stretch: f64, handle: f64| { + let th = deg.to_radians(); + let k = 4.0 / 3.0 * (th / 4.0).tan() * r * handle; + let (p0, p3) = (Point::new(r, 0.0), Point::new(r * th.cos() * stretch, r * th.sin())); + CubicBez::new(p0, p0 + Vec2::new(0.0, k), p3 + Vec2::new(th.sin(), -th.cos()) * k, p3) + }; + let (center, r) = circular_arc(arc(60.0, 50.0, 1.0, 1.0)).unwrap(); + assert!(center.distance(Point::ORIGIN) < 1e-9 && (r - 50.0).abs() < 1e-9); + assert!(circular_arc(arc(90.0, 50.0, 1.0, 1.0)).is_some()); + assert_eq!(circular_arc(arc(120.0, 50.0, 1.0, 1.0)), None); + assert_eq!(circular_arc(arc(60.0, 50.0, 1.1, 1.0)), None); + assert_eq!(circular_arc(arc(60.0, 50.0, 1.0, 1.01)), None); + // On the convex side, the circle touches the arc's circle from outside. + let c = curvature_circle(arc(60.0, 50.0, 1.0, 1.0), 0.0, true).unwrap(); + assert!(c.nominal && c.center.distance(Point::new(100.0, 0.0)) < 1e-9 && (c.radius - 50.0).abs() < 1e-9, "{c:?}"); + } +} diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index 7d3e3f0f4b..3f11c71062 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -11,6 +11,7 @@ pub mod anchors; pub mod arc; pub mod bez; pub mod corners; +pub mod curvature; pub mod hit; pub mod path; pub mod projective; diff --git a/crates/geom/src/shapes.rs b/crates/geom/src/shapes.rs index 838015115b..5641900186 100644 --- a/crates/geom/src/shapes.rs +++ b/crates/geom/src/shapes.rs @@ -441,6 +441,96 @@ pub fn straight_star_inner_radius(r1: f64, points: u32) -> f64 { r1 * (PI / n * 2.0).cos() / (PI / n).cos() } +/// The smallest circle that holds every one of `points`: its center and radius. Points that are +/// not finite are skipped; `None` when no finite point is left. One point gives a circle of +/// radius 0 around it. +pub fn enclosing_circle(points: &[Point]) -> Option<(Point, f64)> { + let mut world = convex_hull(points.iter().copied().filter(|p| p.is_finite()).collect()); + // A fixed shuffle keeps the expected work linear for any order of the points, and the same + // points always give the same circle. + let mut seed: u64 = 0x9E37_79B9_7F4A_7C15; + for i in (1..world.len()).rev() { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + world.swap(i, (seed % (i as u64 + 1)) as usize); + } + // The work is done relative to one of the points, so the rounding allowance in `holds` scales + // with the size of the points' spread, not with their distance from the origin. + let origin = *world.first()?; + let rel = |p: &Point| (*p - origin).to_point(); + let first = Point::ORIGIN; + let holds = |(c, r): (Point, f64), p: Point| (p - c).hypot() <= r + 1e-12 * (r + c.to_vec2().hypot()); + let diameter = |a: Point, b: Point| (a.midpoint(b), (b - a).hypot() / 2.0); + let mut circle = (first, 0.0); + for (i, pi) in world.iter().map(rel).enumerate().skip(1) { + if holds(circle, pi) { + continue; + } + circle = (pi, 0.0); + for (j, pj) in world.iter().map(rel).enumerate().take(i) { + if holds(circle, pj) { + continue; + } + circle = diameter(pi, pj); + for pk in world[..j].iter().map(rel) { + if holds(circle, pk) { + continue; + } + circle = circle_through(pi, pj, pk).unwrap_or_else(|| { + // Three points on one line: the circle on the two farthest apart. + let pairs = [(pi, pj), (pj, pk), (pk, pi)]; + let far = pairs.into_iter().fold((pi, pj), |a, b| if (b.1 - b.0).hypot2() > (a.1 - a.0).hypot2() { b } else { a }); + diameter(far.0, far.1) + }); + } + } + } + // The radius reaches the farthest point from the center returned, whatever rounding the steps + // above and the move back from `origin` left. + let center = circle.0 + origin.to_vec2(); + let radius = world.iter().map(|p| (*p - center).hypot()).fold(0.0, f64::max); + (center.is_finite() && radius.is_finite()).then_some((center, radius)) +} + +/// The corners of the convex hull of `points`, counter-clockwise in a y-up frame, without points +/// on its edges. Fewer than three points, or points on one line, give their ends. Points that are +/// not finite are left out. +pub fn convex_hull(mut points: Vec) -> Vec { + points.retain(|p| p.is_finite()); + // -0.0 and 0.0 are one coordinate: adding 0.0 turns -0.0 into 0.0, so the sort below puts + // points with the same x in y order. + for p in &mut points { + *p = Point::new(p.x + 0.0, p.y + 0.0); + } + points.sort_by(|a, b| a.x.total_cmp(&b.x).then(a.y.total_cmp(&b.y))); + points.dedup(); + if points.len() < 3 { + return points; + } + // Andrew's monotone chain: the lower chain left to right, then the upper chain right to left. + let mut hull: Vec = Vec::with_capacity(points.len() + 1); + chain(&mut hull, points.iter().copied()); + chain(&mut hull, points.iter().rev().copied()); + hull +} + +/// Adds to `hull` the chain of `points` that turns left at every corner, without its last point, +/// which starts the next chain. +fn chain(hull: &mut Vec, points: impl Iterator) { + let start = hull.len(); + for p in points { + while let [.., o, a] = hull[start..] { + if (a - o).cross(p - o) > 0.0 { + break; + } + hull.pop(); + } + hull.push(p); + } + hull.pop(); +} + /// Open straight line. pub fn line(a: Point, b: Point) -> PathData { PathData::single(SubPath::polyline(&[a, b], false)) @@ -795,6 +885,87 @@ mod tests { assert_eq!(circle_through(a, b, Point::new(0.0, 1e-12)), None); } + /// The smallest circle around a set of points: two points far apart are its diameter and the + /// points between them change nothing; an acute triangle's corners lie on it; a right triangle + /// is held by the circle on its hypotenuse; and points on one line give the circle on the two + /// ends. + #[test] + fn the_enclosing_circle_is_the_smallest_that_holds_every_point() { + let near = |(c, r): (Point, f64), want: Point, wr: f64| c.distance(want) < 1e-9 && (r - wr).abs() < 1e-9; + let pts = [Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(5.0, 1.0), Point::new(4.0, -2.0)]; + let got = enclosing_circle(&pts).unwrap(); + assert!(near(got, Point::new(5.0, 0.0), 5.0), "{got:?}"); + // An equilateral triangle of side 6: radius 6 / √3, center at its centroid. + let h = 27.0_f64.sqrt(); + let tri = [Point::new(0.0, 0.0), Point::new(6.0, 0.0), Point::new(3.0, h), Point::new(3.0, 1.0)]; + let got = enclosing_circle(&tri).unwrap(); + assert!(near(got, Point::new(3.0, h / 3.0), 6.0 / 3.0_f64.sqrt()), "{got:?}"); + let right = [Point::new(0.0, 0.0), Point::new(8.0, 0.0), Point::new(0.0, 6.0)]; + assert!(near(enclosing_circle(&right).unwrap(), Point::new(4.0, 3.0), 5.0)); + let line: Vec = (0..20).map(|i| Point::new(f64::from(i), 2.0 * f64::from(i))).collect(); + let got = enclosing_circle(&line).unwrap(); + assert!(near(got, Point::new(9.5, 19.0), Point::new(19.0, 38.0).distance(Point::ORIGIN) / 2.0), "{got:?}"); + } + + /// Many points on a circle, in any order and far from the origin, give that circle; every + /// point is held. One point gives a circle of radius 0, and no finite point gives none. + #[test] + fn the_enclosing_circle_holds_every_point_in_any_order() { + let c = Point::new(4.0e5, -3.0e5); + let mut pts: Vec = (0..997).map(|i| c + Vec2::from_angle(f64::from(i) * 0.37) * 120.0).collect(); + pts.extend((0..500).map(|i| c + Vec2::from_angle(f64::from(i)) * (f64::from(i % 97) + 1.0))); + for order in 0..3 { + if order == 1 { + pts.reverse(); + } else if order == 2 { + pts.sort_by(|a, b| a.x.total_cmp(&b.x)); + } + let (center, r) = enclosing_circle(&pts).unwrap(); + assert!(center.distance(c) < 1e-6 && (r - 120.0).abs() < 1e-6, "{center:?} {r}"); + assert!(pts.iter().all(|p| p.distance(center) <= r + 1e-9), "a point is outside"); + } + // Small art far from the origin keeps its smallest circle. + let far = [Point::new(1.0e12, 5.0), Point::new(1.0e12 + 1.0, 5.0)]; + assert_eq!(enclosing_circle(&far), Some((Point::new(1.0e12 + 0.5, 5.0), 0.5))); + // Where the center rounds on its way back from the first point, the radius still reaches + // every point from the center returned. + let wide = [Point::new(2f64.powi(53), 0.0), Point::new(2f64.powi(53) + 2.0, 0.0)]; + let (center, r) = enclosing_circle(&wide).unwrap(); + assert!(wide.iter().all(|p| p.distance(center) <= r), "{center:?} {r}"); + let one = Point::new(3.0, 4.0); + assert_eq!(enclosing_circle(&[one, one, Point::new(f64::NAN, 1.0)]), Some((one, 0.0))); + assert_eq!(enclosing_circle(&[]), None); + assert_eq!(enclosing_circle(&[Point::new(f64::INFINITY, 0.0)]), None); + } + + /// The hull keeps a square's corners counter-clockwise (y up) from the lowest-leftmost one, + /// without points inside, points on its edges, repeated corners or points that are not finite; + /// points on one line give their ends, and one or two points give themselves. + #[test] + fn the_convex_hull_keeps_only_the_corners() { + let p = Point::new; + let pts = vec![ + p(5.0, 5.0), + p(10.0, 10.0), + p(0.0, 10.0), + p(5.0, 0.0), + p(0.0, 0.0), + p(10.0, 0.0), + p(10.0, 10.0), + p(0.0, 5.0), + p(f64::NAN, 3.0), + p(2.0, 7.0), + ]; + assert_eq!(convex_hull(pts), vec![p(0.0, 0.0), p(10.0, 0.0), p(10.0, 10.0), p(0.0, 10.0)]); + let line: Vec = (0..9).rev().map(|i| p(f64::from(i), 2.0 * f64::from(i))).collect(); + assert_eq!(convex_hull(line), vec![p(0.0, 0.0), p(8.0, 16.0)]); + assert_eq!(convex_hull(vec![p(3.0, 1.0), p(1.0, 2.0)]), vec![p(1.0, 2.0), p(3.0, 1.0)]); + assert_eq!(convex_hull(vec![p(1.0, 1.0), p(1.0, 1.0)]), vec![p(1.0, 1.0)]); + assert_eq!(convex_hull(vec![p(f64::INFINITY, 1.0)]), vec![]); + // -0.0 is 0.0: the three points lie on one line, and the hull is its two ends. + assert_eq!(convex_hull(vec![p(-0.0, 10.0), p(0.0, 0.0), p(0.0, 5.0)]), vec![p(0.0, 0.0), p(0.0, 10.0)]); + } + #[test] fn rect_is_4_corners_clockwise() { let p = rectangle(Rect::new(0.0, 0.0, 100.0, 50.0)); diff --git a/crates/mcp/src/tools/definitions.rs b/crates/mcp/src/tools/definitions.rs index ce9cac1e02..fcbc9cf708 100644 --- a/crates/mcp/src/tools/definitions.rs +++ b/crates/mcp/src/tools/definitions.rs @@ -219,6 +219,7 @@ pub fn tool_definitions() -> Vec { "tiltX": num("Pen tilt in degrees −90..90, positive leaning right (document axes); with tiltY, the tilt the Paintbrush records for Tilt and Bearing brushes. One without the other is 0"), "tiltY": num("Pen tilt in degrees −90..90, positive leaning down the page"), "rotation": num("Pen barrel rotation in degrees clockwise: the rotation the Paintbrush records for Rotation brushes"), + "wheel": num("Airbrush pen finger wheel 0..1 (clamped): the wheel the Paintbrush records for Stylus Wheel brushes"), "holdMs": num("Milliseconds the pointer then holds still, button down (0..60000): Twirl, Pucker and Bloat keep applying"), }), &["kind", "x", "y"]), }, diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 88f60fd6c8..fb27613512 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -223,6 +223,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ ("view.pixelPreview", "Pixel Preview", "Cmd+Alt+Y", "{}"), ("view.trimView", "Trim View", "", "{} toggle: hide everything outside the artboards"), ("view.cornerWidget", "Hide Corner Widget", "", "{} toggle the live corner widgets"), + ( + "view.shapeWidgets", + "Hide Shape Widgets", + "", + "{on?: bool} hide or show selected live shapes' corner, pie and side widgets for the Selection tool and the shape tools (the shape tools' Control bar button); without `on` it toggles; returns the new state. Direct Selection's corner widgets follow view.cornerWidget alone", + ), ( "view.snapToPixel", "Snap to Pixel", @@ -924,6 +930,18 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{colors?: n (an n-colour job: n rows, Scale Tints) | [colour] (new colours to assign, in order; with no art selected and no group they are the rows, and OK saves them as a new colour group, field `groupName`: the Color Guide's Edit or Apply Colors), library?: id or name; or \"document\" (Limit to Library; \"\" the first library), group?: colour group (Edit or Apply Color Group: OK rewrites the group with the new colours and recolours the selected art, if any)} open Recolor Artwork (dialog `recolor`; engine: recolor.reduce / recolor.apply)", ), + ( + "ui.recolorUndo", + "Undo Changes", + "", + "{} the open Recolor Artwork dialog goes back one of its own color edits (rows, Colors, Method, the Preserve options, Limit to Library, the harmony rule, Global Adjust, the Color Theme Picker's picks, the Prominent Colors weights): its fields and the preview return to their values before that edit; the document's undo history is unchanged, and OK still records one undo step → {changed, canUndo, canRedo}; an error when the dialog isn't open. Each opening starts with nothing to undo, and selecting another color group or Save Changes leaves nothing to undo or redo", + ), + ( + "ui.recolorRedo", + "Redo Changes", + "", + "{} the open Recolor Artwork dialog restores the color edit ui.recolorUndo went back from last; a new edit after ui.recolorUndo leaves nothing to redo → {changed, canUndo, canRedo}; an error when the dialog isn't open", + ), ( "ui.cropImage", "Crop Image", @@ -996,6 +1014,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{swatches?: [names]} open New Color Group, from those swatches or the selected artwork (dialog `newColorGroup`, engine: swatch.newGroup)", ), + ( + "ui.colorGroupOptions", + "Color Group Options…", + "", + "{group?} open Color Group Options for that color group, or without group for the color group selected alone in the Swatches panel (dialog `colorGroupOptions`, field `name`): OK renames the group (engine: swatch.renameGroup); a name that is empty or that another color group or a swatch has keeps the dialog open; when another document is active, or the color group at the group's place in the list no longer has the name and swatches it opened with, OK closes the dialog and renames nothing", + ), ( "ui.colorPicker", "Color Picker…", @@ -1078,7 +1102,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "tool.options", "Tool Options…", "", - "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool, diameter (pt), intensity and density (1–10), shared by the eight tools; OK runs tool.setOption {tool, values}), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", + "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", ), ( "ui.colorGuideOptions", @@ -1160,19 +1184,19 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.layerDelete", "Delete Selection", "", - "{ids?|id?, doc?, confirmed?: bool} Delete Selection as the Layers panel runs it (its trash button, rows dropped on the trash, its menu, Delete and Backspace), on the rows layer.delete takes (default: the highlighted rows, else the current layer). When a layer or sublayer among them holds art (an object other than a guide; hidden, locked and nested objects count) it asks first: dialog `confirm` with `message`; OK deletes those rows by id with layer.delete (one undo step), Cancel keeps them. OK runs ui.layerDelete again with the rows, `doc` (the document's uid) and `confirmed: true`: with another document active then, nothing is deleted. Other rows (an empty layer, groups and objects alone) and rows layer.delete refuses go to layer.delete at once → layer.delete's {deleted}, or null while the question is open", + "{ids?|id?, doc?, confirmed?: bool} Delete Selection as the Layers panel runs it (its trash button, rows dropped on the trash, its menu, Delete and Backspace), on the rows layer.delete takes (default: the highlighted rows, else the current layer; in isolation mode, with no row highlighted, a current layer outside the isolated art is an error and nothing is deleted). When a layer or sublayer among them holds art (an object other than a guide; hidden, locked and nested objects count) it asks first: dialog `confirm` with `message`; OK deletes those rows by id with layer.delete (one undo step), Cancel keeps them. OK runs ui.layerDelete again with the rows, `doc` (the document's uid) and `confirmed: true`: with another document active then, nothing is deleted. In isolation mode a row outside the isolated art is an error and nothing is deleted. Other rows (an empty layer, groups and objects alone) and rows layer.delete refuses go to layer.delete at once → layer.delete's {deleted}, or null while the question is open", ), ( "ui.rename", "Rename", "", - "{id?} open the Layers panel's name field on the row of layer, group or object id, as double-clicking the row's name does (the panel is shown and the layers around the row open): Enter renames it with layer.setProps (one undo step), Escape keeps the name. Without id: the highlighted row when a Layers panel row was clicked last, else the one selected object or group, else the one highlighted row, else the current layer. Several rows or objects, or a row the panel's search, filter or Show Layers Only hides, is an error and nothing opens → {id, name}", + "{id?} open the Layers panel's name field on the row of layer, group or object id, as double-clicking the row's name does (the panel is shown and the layers around the row open): Enter renames it with layer.setProps (one undo step), Escape keeps the name. Without id: the highlighted row when a Layers panel row was clicked last, else the one selected object or group, else the one highlighted row, else the current layer. Several rows or objects, a row the panel's search, filter or Show Layers Only hides, or in isolation mode an object outside the isolated art, is an error and nothing opens → {id, name}", ), ( "ui.newLayer", "New Layer Options…", "Cmd+Alt+L", - "{sublayer?: bool} open Layer Options for a new layer (or a sublayer of the current layer), named and coloured as it would be: dialog `layerOptions` with mode new|newSublayer; OK runs layer.new or layer.newSublayer with the fields", + "{sublayer?: bool} open Layer Options for a new layer (or a sublayer of the current layer), named and coloured as it would be: dialog `layerOptions` with mode new|newSublayer; OK runs layer.new or layer.newSublayer with the fields. In isolation mode, a layer that would be outside the isolated art is an error and nothing opens; OK checks again, and with isolation mode started since, it returns the same error and makes no layer", ), ( "ui.newArtboard", @@ -1417,7 +1441,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.widthPointEdit", "Width Point Edit…", "", - "{id, index?: existing width point, t?: 0..1 for a new point, adjustAdjoining?: bool (false)} open Width Point Edit on path `id` (dialog `widthPoint`: side1, side2 (pt), linked, adjustAdjoining; double-clicking the stroke opens it too, Shift on a width point enabling adjoining adjustment): OK runs stroke.widthPoint.set; discard: true (Delete) removes an existing point or discards a prospective point", + "{id, index?: existing width point, indices?: [i…] several existing width points, t?: 0..1 for a new point (give only one of index, indices and t), adjustAdjoining?: bool (false)} open Width Point Edit on path `id` (dialog `widthPoint`: side1, side2 (pt), linked, adjustAdjoining; for several points also totalWidth, and side1, side2 and totalWidth are null where the points differ; double-clicking the stroke opens it too, on one of several Shift-selected width points for all of them, Shift on a width point enabling adjoining adjustment): OK runs stroke.widthPoint.set, for several points one stroke.widthProfile.set (none when nothing changed); discard: true (Delete) removes the existing points or discards a prospective point", ), ( "ui.corners", @@ -1495,13 +1519,19 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.colorWheel", "Color Wheel Options", "", - "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, vision?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, and pick the box's channel, as Box Channel does: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, vision}", + "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, vision?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, and pick the box's channel, as Box Channel does: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, harmony, harmonyRule, vision}", ), ( "ui.savePdfDialog", "Save PDF Dialog", "", - "{path?, preset?, range?, useArtboards?, …document.exportPdf options} open the Save PDF dialog with these options (fields = the options, sections are objects; OK writes path, else asks); useArtboards: false: one page of the visible art's bounds, with no Artboards section", + "{path?, preset?, range?, useArtboards?, …document.exportPdf options} open the Save PDF dialog with these options (fields = the options, sections are objects; Custom… sets `flattener`, which setting flattenerPreset drops; OK writes path, else asks); useArtboards: false: one page of the visible art's bounds, with no Artboards section", + ), + ( + "ui.pdfSummary.save", + "Save Summary…", + "", + "{path} write the Summary of the open Save PDF dialog (or PDF preset editor) to path as UTF-8 text without a byte order mark, with LF line endings, line for line as the Summary section shows it: Options and each option that differs from the preset (or the line saying none does), a blank line, then Warnings and each warning (or None.). The Summary the section last drew for the same fields, document, saved PDF and flattener presets, loaded color profiles and available fonts is used without computing the settings again. The web downloads the file under path's file name. The Summary section's Save Summary… button writes the same text to a file picked in a save panel that suggests ` PDF Summary.txt` in the document's folder. The dialog stays open and the document does not change. No such dialog open, a path that is missing, empty or not a string, a path outside the automation write roots and a failed document.pdfSettings are errors that write nothing; a failed write is an error → {path, bytes}", ), ( "file.exportAs", @@ -1807,6 +1837,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{path?, useArtboards?, range?, …document.exportEps options} open EPS Options (dialog `epsOptions`: fields = these options over the ones used last; Custom… sets `flattener`, which a flattenerPreset given without it drops); OK checks them, remembers them and writes path (else asks). Export As… → EPS opens it too", ), + ( + "ui.hpglOptionsDialog", + "HP-GL Options Dialog", + "", + "{path?, useArtboards?, range?, hpglVersion?, curveTolerance?, origin?, pens?, sortPaths?, insideFirst?} open HP-GL Options (dialog `hpglOptions`: fields = these document.export options over the ones used last; pens null is One Pen per Color); OK checks them, remembers them and writes path (else asks). Export As… → HP-GL opens it too", + ), ( "file.saveForWeb", "Save for Web (Legacy)…", diff --git a/crates/pathops/src/addons/pathtools.rs b/crates/pathops/src/addons/pathtools.rs index ed01ec3ce8..d5fe994bed 100644 --- a/crates/pathops/src/addons/pathtools.rs +++ b/crates/pathops/src/addons/pathtools.rs @@ -41,6 +41,8 @@ pub use tangent_circle::{Circle, MAX_TANGENT_CIRCLE_SEGMENTS, MAX_TANGENT_CIRCLE pub use tangents::{Coincide, MAX_TANGENT_SEGMENTS, Outline, OutlineError, Tangent, TangentKind, common_tangents}; pub use trim::{Span, slice, span_at, spans, without_spans}; +pub use tangent_circle::{SegmentCircle, circles_of_radius, circles_through}; + use crate::fit::{end_tangent, start_tangent}; /// The auto-smooth rule's handle length as a share of the nearer neighbour's distance: the share diff --git a/crates/pathops/src/addons/pathtools/bridge.rs b/crates/pathops/src/addons/pathtools/bridge.rs index f0afa31dc8..2b2fd9512e 100644 --- a/crates/pathops/src/addons/pathtools/bridge.rs +++ b/crates/pathops/src/addons/pathtools/bridge.rs @@ -217,7 +217,9 @@ pub struct Bridged { pub enum ManyError { /// More than [`MAX_BRIDGED_CIRCLES`] circles. TooManyCircles, - /// More than [`MAX_BRIDGES`] pairs of circles within reach that the arcs can bridge. + /// More than [`MAX_BRIDGES`] pairs of circles to bridge: within reach, near enough for the + /// arcs and with a neck wide enough for the shape's precision. Also more than nine times as many + /// pairs within reach to check. TooManyBridges, /// No two circles are within reach of each other. NoneInReach, @@ -324,6 +326,9 @@ fn bridgeable(circles: &[Circle], arc: ArcRadius, reach: f64) -> Result MAX_BRIDGES { + return Err(ManyError::TooManyBridges); + } Ok((pairs, too_far, roots, precision)) } @@ -377,16 +382,15 @@ fn pairs_within(circles: &[Circle], reach: f64, arc: ArcRadius) -> Result 9 * MAX_BRIDGES { return Err(ManyError::TooManyBridges); } } + // Saturated cells can list a pair twice. pairs.sort_unstable_by_key(|&(pair, _)| pair); pairs.dedup_by_key(|&mut (pair, _)| pair); - if pairs.len() > MAX_BRIDGES { - return Err(ManyError::TooManyBridges); - } Ok((pairs, too_far)) } @@ -793,6 +797,20 @@ mod tests { assert_eq!(bridge_many(&[circle(f64::INFINITY, 0.0, 1.0), far[0]], ArcRadius::Share(1.0), 1.0), Err(ManyError::Bad)); } + #[test] + fn the_bridge_limit_counts_the_necks_left_after_thin_ones_are_dropped() { + // Two columns of 65 nearly coincident circles: 8,385 pairs within reach that the arcs can + // bridge, but the 4,225 between the columns are thinner than the precision allows. + let column = |x: f64| (0..65).map(move |k| circle(x, 0.001 * k as f64, 10.0)); + let circles: Vec = column(0.0).chain(column(34.6409)).collect(); + let (pairs, too_far) = pairs_within(&circles, 15.0, ArcRadius::Share(1.0)).unwrap(); + assert_eq!((pairs.len(), too_far), (8385, None)); + let (pairs, ..) = bridgeable(&circles, ArcRadius::Share(1.0), 15.0).unwrap(); + assert_eq!(pairs.len(), 4160); + assert!(pairs.iter().all(|&((i, j), _)| (i < 65) == (j < 65))); + assert!(bridges_any(&circles, ArcRadius::Share(1.0), 15.0)); + } + #[test] fn huge_circles_bridge_with_finite_anchors_or_are_refused() { // Squaring these lengths overflows f64. diff --git a/crates/pathops/src/addons/pathtools/tangent_circle.rs b/crates/pathops/src/addons/pathtools/tangent_circle.rs index b17a52cac6..2a7fed0045 100644 --- a/crates/pathops/src/addons/pathtools/tangent_circle.rs +++ b/crates/pathops/src/addons/pathtools/tangent_circle.rs @@ -10,13 +10,19 @@ //! from a point to an outline changes by at most the distance the point moves, so a cell whose //! center is too far from every condition holds no center and is dropped. The cells left are //! refined with Newton's method on the exact curves. +//! +//! The Tangent Circle tool's circles on two picked segments are [`circles_through`] and +//! [`circles_of_radius`]. use kurbo::{CubicBez, ParamCurve, Point, Vec2}; use vectorcraft_geom::PathData; +mod on_segments; #[cfg(test)] mod tests; +pub use on_segments::{SegmentCircle, circles_of_radius, circles_through}; + /// Most segments the shapes may hold together, counted by [`tangent_circle_segments`]. pub const MAX_TANGENT_CIRCLE_SEGMENTS: usize = 2_000; diff --git a/crates/pathops/src/addons/pathtools/tangent_circle/on_segments.rs b/crates/pathops/src/addons/pathtools/tangent_circle/on_segments.rs new file mode 100644 index 0000000000..615c7f1412 --- /dev/null +++ b/crates/pathops/src/addons/pathtools/tangent_circle/on_segments.rs @@ -0,0 +1,268 @@ +//! The circles the Tangent Circle tool draws on two picked segments: the circle tangent to the +//! first segment at a point that also touches the second ([`circles_through`]), or the circles of a +//! radius tangent to the first segment that also touch the second ([`circles_of_radius`]). "The +//! second" is a list of segments (the picked one and those next to it). A circle touches them when +//! the nearest of their points to its center is on the circle, so they lie outside it, and it never +//! crosses the first segment. +//! +//! The roots are found by sampling a distance function along one parameter: samples where it is 0, +//! bisection where it changes sign, and a golden-section search where it comes down to 0 between +//! samples without changing sign. + +use kurbo::{CubicBez, ParamCurve, ParamCurveDeriv, ParamCurveNearest, Point, Vec2}; + +use super::Circle; + +/// A circle on two picked segments: the circle, where it touches the first segment and where it +/// touches the second ones. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct SegmentCircle { + pub circle: Circle, + pub first: Point, + pub second: Point, +} + +/// Samples along the parameter the roots are looked for on. +const SAMPLES: usize = 512; +/// Bisection steps per root. +const BISECTIONS: usize = 64; +/// The largest radius [`circles_through`] looks at, as a multiple of the diagonal of the box around +/// the segments' control points. +const MAX_RADIUS: f64 = 1e4; +/// Below this share of the radius two points of a circle are one. +const SAME: f64 = 1e-7; +/// Below this share of the radius (or, while the radius is looked for, of the gap from the point to +/// the second segments) a circle's distance from the second segments counts as touching. +const CONTACT: f64 = 1e-9; +/// Below this (in units of the first segment's size) a length is rounding. +const ROUNDING: f64 = 1e-12; + +/// The diagonal of the box around the control points of `first` and `second`; none when it is 0 or +/// not finite. +fn scale(first: &CubicBez, second: &[CubicBez]) -> Option { + let pts = std::iter::once(first).chain(second).flat_map(|c| [c.p0, c.p1, c.p2, c.p3]); + let (mut lo, mut hi) = (Point::new(f64::INFINITY, f64::INFINITY), Point::new(f64::NEG_INFINITY, f64::NEG_INFINITY)); + for p in pts { + if !(p.x.is_finite() && p.y.is_finite()) { + return None; + } + lo = Point::new(lo.x.min(p.x), lo.y.min(p.y)); + hi = Point::new(hi.x.max(p.x), hi.y.max(p.y)); + } + let d = (hi - lo).hypot(); + (d.is_finite() && d > 0.0).then_some(d) +} + +/// The nearest point to `q` on `segs` and its distance. +fn nearest(q: Point, segs: &[CubicBez]) -> Option<(f64, Point)> { + segs.iter() + .map(|c| { + let n = c.nearest(q, 1e-9); + (n.distance_sq.sqrt(), c.eval(n.t)) + }) + .min_by(|a, b| a.0.total_cmp(&b.0)) +} + +/// The unit normal of `c` at `t` (its tangent turned a quarter turn). Where the derivative is 0 (a +/// handle lying on its anchor), the direction the curve leaves in: toward the far handle, or the +/// other end. None where the segment does not move by more than rounding in units of `scale`, its +/// size. +fn normal(c: &CubicBez, t: f64, scale: f64) -> Option { + let tiny = ROUNDING * scale; + let d = c.deriv().eval(t).to_vec2(); + let d = if d.hypot() > tiny { + d + } else if t < 0.5 { + c.p2 - c.p0 + } else { + c.p3 - c.p1 + }; + let d = if d.hypot() > tiny { d } else { c.p3 - c.p0 }; + let len = d.hypot(); + (len.is_finite() && len > tiny).then(|| Vec2::new(-d.y / len, d.x / len)) +} + +/// The parameters where `f` is 0, within `zero`, in order: every sample where it is (a stretch where +/// it stays 0 gives each of its samples), each place between two samples where it changes sign +/// (found by bisection), and, where `f` comes toward 0 between samples and goes back without a +/// sample on the other side, the place it comes nearest (a golden-section search): a touch when it +/// reaches 0 there, and the two places on either side, by bisection, when it passes 0. +fn roots(samples: &[f64], f: impl Fn(f64) -> Option, zero: f64) -> Vec { + let mut out = vec![]; + let values: Vec> = samples.iter().map(|s| f(*s)).collect(); + let is_zero = |v: f64| v.abs() <= zero; + for (s, v) in samples.iter().zip(&values) { + if v.is_some_and(is_zero) { + out.push(*s); + } + } + for (k, w) in values.windows(3).enumerate() { + let (Some(a), Some(b), Some(c)) = (w[0], w[1], w[2]) else { continue }; + let (Some(&lo), Some(&hi)) = (samples.get(k), samples.get(k + 2)) else { continue }; + let same_side = (a > 0.0) == (b > 0.0) && (b > 0.0) == (c > 0.0); + // A low point, or one of two equal low samples about a touch half way between them. + let low = b.abs() <= a.abs() && b.abs() <= c.abs() && (b.abs() < a.abs() || b.abs() < c.abs()); + if !same_side || is_zero(a) || is_zero(b) || is_zero(c) || !low { + continue; + } + out.extend(near_zero(lo, hi, b > 0.0, &f, zero)); + } + // At either end the lowest sample has no sample beyond it: the stretch to the next one. + for (end, next) in [(0, 1), (values.len().saturating_sub(1), values.len().saturating_sub(2))] { + let (Some(Some(a)), Some(Some(b))) = (values.get(end), values.get(next)) else { continue }; + let (Some(&s), Some(&t)) = (samples.get(end), samples.get(next)) else { continue }; + if (a > &0.0) == (b > &0.0) && !is_zero(*a) && !is_zero(*b) && a.abs() < b.abs() { + out.extend(near_zero(s.min(t), s.max(t), *a > 0.0, &f, zero)); + } + } + for (k, w) in values.windows(2).enumerate() { + let (Some(a), Some(b)) = (w[0], w[1]) else { continue }; + let (Some(&lo), Some(&hi)) = (samples.get(k), samples.get(k + 1)) else { continue }; + if (a > 0.0) == (b > 0.0) || is_zero(a) || is_zero(b) { + continue; + } + out.extend(bisect(lo, hi, &f)); + } + out.sort_by(f64::total_cmp); + out +} + +/// Where `f`, above 0 (`positive`) or below at the samples `lo` and `hi`, comes nearest 0 between +/// them: that place when it reaches 0 there, the two places on either side where it passes 0, or +/// none. +fn near_zero(lo: f64, hi: f64, positive: bool, f: &impl Fn(f64) -> Option, zero: f64) -> Vec { + // Toward 0 is down for a positive `f`, up for a negative one. + let toward = if positive { 1.0 } else { -1.0 }; + let Some(m) = smallest(lo, hi, |s| f(s).map(|v| v * toward)) else { return vec![] }; + let Some(fm) = f(m) else { return vec![] }; + if fm.abs() <= zero { + vec![m] + } else if fm * toward < 0.0 { + bisect(lo, m, f).into_iter().chain(bisect(m, hi, f)).collect() + } else { + vec![] + } +} + +/// Where `f` changes sign between `lo` and `hi`, by bisection; none when it does not. +fn bisect(mut lo: f64, mut hi: f64, f: impl Fn(f64) -> Option) -> Option { + let (a, b) = (f(lo)?, f(hi)?); + if (a > 0.0) == (b > 0.0) { + return None; + } + let positive_low = a > 0.0; + for _ in 0..BISECTIONS { + let mid = 0.5 * (lo + hi); + match f(mid) { + Some(v) if (v > 0.0) == positive_low => lo = mid, + Some(_) => hi = mid, + None => break, + } + } + Some(0.5 * (lo + hi)) +} + +/// Where `g` is smallest between `lo` and `hi`, by a golden-section search; none where `g` has no +/// value. +fn smallest(mut lo: f64, mut hi: f64, g: impl Fn(f64) -> Option) -> Option { + const INV_PHI: f64 = 0.618_033_988_749_894_9; + let (mut a, mut b) = (hi - INV_PHI * (hi - lo), lo + INV_PHI * (hi - lo)); + let (mut ga, mut gb) = (g(a)?, g(b)?); + for _ in 0..BISECTIONS { + if ga < gb { + hi = b; + (b, gb) = (a, ga); + a = hi - INV_PHI * (hi - lo); + ga = g(a)?; + } else { + lo = a; + (a, ga) = (b, gb); + b = lo + INV_PHI * (hi - lo); + gb = g(b)?; + } + } + Some(0.5 * (lo + hi)) +} + +/// Where the circle about `center` of radius `r` touches `second`: the nearest of their points, when +/// it is on the circle (within a millionth of the radius, plus rounding in units of `scale`). None +/// for a root where the distance only jumps past the radius, as it does where the first segment +/// turns back on itself and its normal flips. +fn touching(center: Point, r: f64, second: &[CubicBez], scale: f64) -> Option { + nearest(center, second).filter(|(d, _)| (d - r).abs() <= 1e-6 * r + ROUNDING * scale).map(|(_, p)| p) +} + +/// `found` without circles that cross `first`, that touch the two at one point, or that repeat an +/// earlier one (the same center, touching `first` at the same point). +fn keep(found: Vec, first: &CubicBez) -> Vec { + let own = scale(first, &[]).unwrap_or(0.0); + let mut out: Vec = vec![]; + for c in found { + let r = c.circle.radius; + let crosses = nearest(c.circle.center, std::slice::from_ref(first)).is_none_or(|(d, _)| d < r * (1.0 - 1e-6)); + let one_point = (c.first - c.second).hypot() <= SAME * r; + // The roots come in order along their parameter, so a repeat follows its first. Circles of + // one large radius at places tried close together along `first` are not repeats. + let repeat = + out.last().is_some_and(|o| (o.circle.center - c.circle.center).hypot() <= SAME * r * 10.0 && (o.first - c.first).hypot() <= SAME * own); + if !(crosses || one_point || repeat) && r.is_finite() && r > 0.0 { + out.push(c); + } + } + out +} + +/// The circles tangent to `first` at parameter `t` (passing through that point, their centers on +/// its normal there) that touch `second`. An empty list when `first` has no direction at `t`, when +/// the point is on `second`, or when no circle touches it; at most two in practice, one on each side. +pub fn circles_through(first: CubicBez, t: f64, second: &[CubicBez]) -> Vec { + if second.is_empty() || !t.is_finite() { + return vec![]; + } + let t = t.clamp(0.0, 1.0); + let (Some(scale), Some(own)) = (scale(&first, second), scale(&first, &[])) else { return vec![] }; + let Some(n) = normal(&first, t, own) else { return vec![] }; + let p = first.eval(t); + // On the second segments (a corner the two share), up to rounding in units of the first + // segment's size: no circle. + let on = ROUNDING * own; + let Some((gap, _)) = nearest(p, second).filter(|(d, _)| *d > on) else { return vec![] }; + // Radii spaced evenly in their logarithm, from half the gap from the point to the second + // segments (no smaller circle through the point reaches them) to far past the segments. + let (lo, hi) = (0.5 * gap * (1.0 - 1e-9), MAX_RADIUS * scale.max(gap)); + let samples: Vec = (0..=SAMPLES).map(|k| lo * (hi / lo).powf(k as f64 / SAMPLES as f64)).collect(); + let mut found = vec![]; + for side in [1.0, -1.0] { + let center = |r: f64| p + n * (side * r); + for r in roots(&samples, |r| nearest(center(r), second).map(|(d, _)| d - r), CONTACT * gap) { + if let Some(touch) = touching(center(r), r, second, own) { + found.push(SegmentCircle { circle: Circle { center: center(r), radius: r }, first: p, second: touch }); + } + } + } + keep(found, &first) +} + +/// The circles of `radius` tangent to `first` (their centers `radius` from it along its normal) +/// that touch `second`. An empty list when the radius is not above 0 or none is found. Where the +/// segments run twice the radius apart along a stretch, every circle along it touches both, and one +/// is listed for each of the 513 places along `first` that are tried there. +pub fn circles_of_radius(first: CubicBez, second: &[CubicBez], radius: f64) -> Vec { + if second.is_empty() || !radius.is_finite() || radius <= 0.0 { + return vec![]; + } + let (Some(_), Some(own)) = (scale(&first, second), scale(&first, &[])) else { return vec![] }; + let samples: Vec = (0..=SAMPLES).map(|k| k as f64 / SAMPLES as f64).collect(); + let mut found = vec![]; + for side in [1.0, -1.0] { + let center = |t: f64| normal(&first, t, own).map(|n| first.eval(t) + n * (side * radius)); + for t in roots(&samples, |t| center(t).and_then(|c| nearest(c, second)).map(|(d, _)| d - radius), CONTACT * radius) { + if let Some(c) = center(t) + && let Some(touch) = touching(c, radius, second, own) + { + found.push(SegmentCircle { circle: Circle { center: c, radius }, first: first.eval(t), second: touch }); + } + } + } + keep(found, &first) +} diff --git a/crates/pathops/src/addons/pathtools/tangent_circle/tests.rs b/crates/pathops/src/addons/pathtools/tangent_circle/tests.rs index 8b63d29873..c130fb5be3 100644 --- a/crates/pathops/src/addons/pathtools/tangent_circle/tests.rs +++ b/crates/pathops/src/addons/pathtools/tangent_circle/tests.rs @@ -1,4 +1,4 @@ -use kurbo::{Affine, Point, Rect}; +use kurbo::{Affine, CubicBez, Point, Rect}; use vectorcraft_geom::{PathData, SubPath, shapes}; use super::*; @@ -485,3 +485,210 @@ fn answers_about_a_tiny_shape_far_away_stay_apart() { assert!(a.y < b.y - 1e-3 || ((a.y - b.y).abs() <= 1e-3 && a.x < b.x), "{found:?}"); } } + +/// A straight segment from `a` to `b`, its handles at its thirds so that `t` runs evenly along it. +fn line(a: (f64, f64), b: (f64, f64)) -> CubicBez { + let (a, b) = (Point::new(a.0, a.1), Point::new(b.0, b.1)); + CubicBez::new(a, a.lerp(b, 1.0 / 3.0), a.lerp(b, 2.0 / 3.0), b) +} + +#[test] +fn a_line_with_its_handles_on_its_anchors_has_a_direction_at_its_ends() { + let (a, b) = (Point::new(0.0, 0.0), Point::new(100.0, 0.0)); + for t in [0.0, 1.0] { + let p = CubicBez::new(a, a, b, b).eval(t); + let found = circles_through(CubicBez::new(a, a, b, b), t, &[line((-50.0, 40.0), (150.0, 40.0))]); + assert_eq!(found.len(), 1, "{t}: {found:?}"); + assert!(near(found[0].circle.center, p.x, 20.0, 1e-6), "{t}: {found:?}"); + } +} + +fn near(p: Point, x: f64, y: f64, tol: f64) -> bool { + (p - Point::new(x, y)).hypot() <= tol +} + +#[test] +fn a_circle_through_a_point_of_one_line_touches_a_parallel_line() { + let found = circles_through(line((0.0, 0.0), (100.0, 0.0)), 0.5, &[line((0.0, 40.0), (100.0, 40.0))]); + // Only toward the other line: away from it, no circle reaches it. + assert_eq!(found.len(), 1, "{found:?}"); + let c = found[0]; + assert!(near(c.circle.center, 50.0, 20.0, 1e-6) && (c.circle.radius - 20.0).abs() < 1e-6, "{c:?}"); + assert!(near(c.first, 50.0, 0.0, 1e-9) && near(c.second, 50.0, 40.0, 1e-6), "{c:?}"); +} + +#[test] +fn a_crossing_line_gives_a_circle_on_each_side() { + let found = circles_through(line((0.0, 0.0), (100.0, 0.0)), 0.3, &[line((80.0, -100.0), (80.0, 100.0))]); + assert_eq!(found.len(), 2, "{found:?}"); + for y in [50.0, -50.0] { + assert!(found.iter().any(|c| near(c.circle.center, 30.0, y, 1e-6) && (c.circle.radius - 50.0).abs() < 1e-6), "{y}: {found:?}"); + } +} + +#[test] +fn a_circle_that_crosses_the_first_segment_is_left_out() { + // Through (50, 75) on a flat first segment, the circle touching y = -200 has radius 137.5. + let below = [line((-500.0, -200.0), (500.0, -200.0))]; + let flat = circles_through(line((0.0, 75.0), (100.0, 75.0)), 0.5, &below); + assert_eq!(flat.len(), 1, "{flat:?}"); + assert!((flat[0].circle.radius - 137.5).abs() < 1e-6, "{flat:?}"); + // On a hump from (0, 0) up to (50, 75) and back down to (100, 0), the same circle crosses the + // hump's sides (its center (50, -62.5) is 80 from (0, 0)), and none on the other side reaches. + let hump = CubicBez::new(Point::new(0.0, 0.0), Point::new(0.0, 100.0), Point::new(100.0, 100.0), Point::new(100.0, 0.0)); + assert!(near(hump.eval(0.5), 50.0, 75.0, 1e-9)); + let found = circles_through(hump, 0.5, &below); + assert!(found.is_empty(), "{found:?}"); +} + +#[test] +fn where_the_first_segment_turns_back_only_circles_that_touch_are_kept() { + // Out to (75, 0) and back: the normal flips at the turn, and the distance to the line jumps there. + let first = CubicBez::new(Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 0.0), Point::new(0.0, 0.0)); + let second = [line((-100.0, 40.0), (200.0, 40.0))]; + let found = circles_of_radius(first, &second, 30.0); + for c in &found { + assert!((c.circle.center.y - 10.0).abs() < 1e-6 || (c.circle.center.y - 70.0).abs() < 1e-6, "{c:?}"); + } + assert!(!found.iter().any(|c| (c.circle.center.x - 75.0).abs() < 1.0), "{found:?}"); +} + +#[test] +fn a_circle_through_a_point_touches_a_curved_segment() { + // The second segments are a Bézier circle of radius 20 about (50, 100): touched from outside, + // |center − (50, 100)| = r + 20 with the center at (50, r), so r = 40. + let ring = circle(50.0, 100.0, 20.0); + let segs: Vec = (0..4).map(|i| ring.subpaths[0].segment(i)).collect(); + let found = circles_through(line((0.0, 0.0), (100.0, 0.0)), 0.5, &segs); + assert_eq!(found.len(), 1, "{found:?}"); + let c = found[0]; + // Within the Bézier circle's own error (0.0273% of 20). + assert!((c.circle.radius - 40.0).abs() < 0.01 && near(c.circle.center, 50.0, 40.0, 0.01), "{c:?}"); + assert!(near(c.second, 50.0, 80.0, 0.01), "{c:?}"); +} + +#[test] +fn on_a_curved_first_segment_the_center_is_on_the_normal() { + // A quarter of a ring of radius 50 about (0, 0); the second segment a line far off to the right. + let ring = circle(0.0, 0.0, 50.0); + let mut checked = 0; + for i in 0..4 { + let first = ring.subpaths[0].segment(i); + for t in [0.0, 0.3, 0.7, 1.0] { + let found = circles_through(first, t, &[line((300.0, -500.0), (300.0, 500.0))]); + let tangent = kurbo::ParamCurveDeriv::deriv(&first).eval(t).to_vec2(); + for c in &found { + let to_center = c.circle.center - c.first; + assert!(to_center.dot(tangent).abs() <= 1e-9 * to_center.hypot() * tangent.hypot(), "{i} {t}: {c:?}"); + checked += 1; + } + } + } + assert!(checked >= 8, "{checked}"); +} + +#[test] +fn a_radius_fills_the_corner_between_two_lines() { + let first = line((0.0, 0.0), (100.0, 0.0)); + let found = circles_of_radius(first, &[line((100.0, 0.0), (100.0, 100.0))], 10.0); + // Outside the corner a circle tangent to the first line reaches the second only at the shared + // corner, where it touches both at one point: left out. + assert_eq!(found.len(), 1, "{found:?}"); + let c = found[0]; + assert!(near(c.circle.center, 90.0, 10.0, 1e-6) && c.circle.radius == 10.0, "{c:?}"); + assert!(near(c.first, 90.0, 0.0, 1e-6) && near(c.second, 100.0, 10.0, 1e-6), "{c:?}"); +} + +#[test] +fn lines_twice_the_radius_apart_give_circles_all_along() { + let found = circles_of_radius(line((0.0, 0.0), (100.0, 0.0)), &[line((0.0, 40.0), (100.0, 40.0))], 20.0); + assert!(found.len() > 100, "{}", found.len()); + assert!(found.iter().all(|c| (c.circle.center.y - 20.0).abs() < 1e-9 && c.circle.radius == 20.0), "{found:?}"); + let xs: Vec = found.iter().map(|c| c.circle.center.x).collect(); + assert!(xs.iter().any(|x| *x < 1.0) && xs.iter().any(|x| *x > 99.0), "from end to end: {xs:?}"); + // At a radius of 1,000,000 pt the places tried along the line, 0.2 pt apart, stay apart. + let found = circles_of_radius(line((0.0, 0.0), (100.0, 0.0)), &[line((0.0, 2e6), (100.0, 2e6))], 1e6); + let xs: Vec = found.iter().map(|c| c.circle.center.x).collect(); + let widest = xs.windows(2).map(|w| w[1] - w[0]).fold(0.0, f64::max); + assert!(xs.iter().any(|x| *x < 1.0) && xs.iter().any(|x| *x > 99.0) && widest < 1.0, "from end to end, none merged: {xs:?}"); +} + +#[test] +fn a_circle_that_touches_a_curve_between_the_places_tried_is_found() { + // A ring of radius 20 about (50.3, 60): a circle of radius 20 on the line y = 0 reaches it only + // at x = 50.3, between the places tried along the line, without the distance changing sign. + let ring = circle(50.3, 60.0, 20.0); + let segs: Vec = (0..4).map(|i| ring.subpaths[0].segment(i)).collect(); + let found = circles_of_radius(line((0.0, 0.0), (100.0, 0.0)), &segs, 20.0); + assert_eq!(found.len(), 1, "{found:?}"); + assert!(near(found[0].circle.center, 50.3, 20.0, 1e-3) && near(found[0].second, 50.3, 40.0, 1e-3), "{found:?}"); +} + +#[test] +fn a_touch_half_way_between_two_places_tried_is_found() { + // A point half way between the places tried at x = 50 and x = 50.1953125: the two samples + // either side are equally far from a touch. + let dot = line((50.097_656_25, 40.0), (50.097_656_25, 40.0)); + let found = circles_of_radius(line((0.0, 0.0), (100.0, 0.0)), &[dot], 20.0); + assert_eq!(found.len(), 1, "{found:?}"); + assert!(near(found[0].circle.center, 50.097_656_25, 20.0, 1e-6), "{found:?}"); +} + +#[test] +fn a_touch_between_the_end_and_the_next_place_tried_is_found() { + for x in [0.05, 99.95] { + let found = circles_of_radius(line((0.0, 0.0), (100.0, 0.0)), &[line((x, 40.0), (x, 40.0))], 20.0); + assert_eq!(found.len(), 1, "{x}: {found:?}"); + assert!(near(found[0].circle.center, x, 20.0, 1e-6), "{x}: {found:?}"); + } +} + +#[test] +fn two_circles_between_the_same_two_places_tried_are_both_found() { + // A point a hair less than twice the radius from the line: two circles, about 0.02 pt either + // side of x = 50.05, both between the places tried at 50 and 50.1953125. + let (x, y) = (50.05, 39.99999); + let found = circles_of_radius(line((0.0, 0.0), (100.0, 0.0)), &[line((x, y), (x, y))], 20.0); + assert_eq!(found.len(), 2, "{found:?}"); + let dx = (400.0 - (y - 20.0) * (y - 20.0)).sqrt(); + assert!(near(found[0].circle.center, x - dx, 20.0, 1e-6) && near(found[1].circle.center, x + dx, 20.0, 1e-6), "{found:?}"); +} + +#[test] +fn a_tiny_circle_between_long_lines_close_together_is_found() { + let found = circles_through(line((0.0, 0.0), (100.0, 0.0)), 0.5, &[line((0.0, 1e-4), (100.0, 1e-4))]); + assert_eq!(found.len(), 1, "{found:?}"); + assert!((found[0].circle.radius - 5e-5).abs() < 1e-12 && near(found[0].circle.center, 50.0, 5e-5, 1e-12), "{found:?}"); + // A short line near a very long one: the long one's size does not hide the gap. + let found = circles_through(line((0.0, 0.0), (100.0, 0.0)), 0.5, &[line((-5e9, 1e-3), (5e9, 1e-3))]); + assert_eq!(found.len(), 1, "{found:?}"); + assert!((found[0].circle.radius - 5e-4).abs() < 1e-9, "{found:?}"); + // Lines 1e-5 pt apart moved 1e9 pt to the right. + let found = circles_through(line((1e9, 0.0), (1e9 + 100.0, 0.0)), 0.5, &[line((1e9, 1e-5), (1e9 + 100.0, 1e-5))]); + assert_eq!(found.len(), 1, "{found:?}"); + assert!((found[0].circle.radius - 5e-6).abs() < 1e-9, "{found:?}"); +} + +#[test] +fn long_segments_far_apart_give_no_circle_of_a_small_radius() { + // Lines 1e10 pt long and 1450 pt apart: a circle of radius 500 on one stays 950 pt from the other. + let found = circles_of_radius(line((0.0, 0.0), (1e10, 0.0)), &[line((0.0, 1450.0), (1e10, 1450.0))], 500.0); + assert!(found.is_empty(), "{:?}", found.first()); + // A radius of 1,000,000 pt and lines 0.05 pt more than twice that apart: no touch. + let found = circles_of_radius(line((0.0, 0.0), (100.0, 0.0)), &[line((0.0, 2_000_000.05), (100.0, 2_000_000.05))], 1e6); + assert!(found.is_empty(), "{:?}", found.first()); +} + +#[test] +fn no_circle_when_the_radius_is_too_small_or_the_point_is_on_the_second() { + let (first, other) = (line((0.0, 0.0), (100.0, 0.0)), line((0.0, 40.0), (100.0, 40.0))); + assert!(circles_of_radius(first, &[other], 5.0).is_empty()); + for r in [0.0, -1.0, f64::NAN, f64::INFINITY] { + assert!(circles_of_radius(first, &[other], r).is_empty(), "{r}"); + } + assert!(circles_through(first, 1.0, &[line((100.0, 0.0), (100.0, 100.0))]).is_empty(), "the point is on the second"); + assert!(circles_through(first, 0.5, &[]).is_empty()); + assert!(circles_through(first, f64::NAN, &[other]).is_empty()); + let dot = line((5.0, 5.0), (5.0, 5.0)); + assert!(circles_through(dot, 0.5, &[other]).is_empty(), "no direction"); +} diff --git a/crates/render/src/changed.rs b/crates/render/src/changed.rs index 1c15247034..cea07dab35 100644 --- a/crates/render/src/changed.rs +++ b/crates/render/src/changed.rs @@ -360,8 +360,8 @@ fn same_but_anchors(a: &Node, b: &Node) -> bool { } /// Does `n` paint each pixel from the segments near it alone: no effects, every visible fill and -/// stroke a solid color, and no stroke with dashes, a width profile, pressure, tilt, bearing or -/// rotation, arrowheads, a brush or effects? +/// stroke a solid color, and no stroke with dashes, a width profile, pressure, tilt, bearing, +/// rotation or wheel, arrowheads, a brush or effects? fn local_paint(n: &Node) -> bool { use vectorcraft_doc::AppearanceItem; let solid = |p: &vectorcraft_color::Paint| matches!(p, vectorcraft_color::Paint::Solid { .. } | vectorcraft_color::Paint::None); @@ -379,6 +379,7 @@ fn local_paint(n: &Node) -> bool { && s.tilt.is_none() && s.bearing.is_none() && s.rotation.is_none() + && s.wheel.is_none() && s.start_arrow.is_none() && s.end_arrow.is_none() && s.brush.is_none() diff --git a/crates/render/src/fx/renderer.rs b/crates/render/src/fx/renderer.rs index d0ad5d65e9..78a6ea236b 100644 --- a/crates/render/src/fx/renderer.rs +++ b/crates/render/src/fx/renderer.rs @@ -493,7 +493,27 @@ impl Renderer { { return self.draw_staged(ctx, f, stage, &bp, *rule); } - let art = self.fx_art(f.symbols, a, cache); + let separations = f.opts.proof.as_ref().filter(|proof| proof.separations.is_some()); + let key = Arc::as_ptr(a) as usize; + let previous = (cache && separations.is_some()).then(|| self.fx_arts.get(&key, self.stamp).map(|entry| entry.1.clone())).flatten(); + let mut art = self.fx_art(f.symbols, a, cache); + if let Some(proof) = separations + && previous.as_ref().is_none_or(|previous| !Arc::ptr_eq(previous, &art)) + { + let made = crate::proof::generated_black(f.doc, proof, &art); + if !Arc::ptr_eq(&made, &art) { + if let Some((_, bounds)) = self.three_d_bounds.remove(&(Arc::as_ptr(&art) as usize)) { + self.three_d_bounds.insert(Arc::as_ptr(&made) as usize, (Arc::downgrade(&made), bounds)); + } + if cache + && let Some((node, _, found)) = + self.fx_arts.get(&key, self.stamp).filter(|entry| Arc::ptr_eq(&entry.0, a) && Arc::ptr_eq(&entry.1, &art)).cloned() + { + self.fx_arts.insert(key, (node, made.clone(), found), crate::lru::node_bytes(&made), self.stamp); + } + art = made; + } + } // Art the cache did not keep is made again in the next frame. let kept = cache && self.fx_arts.get(&(Arc::as_ptr(a) as usize), self.stamp).is_some_and(|e| Arc::ptr_eq(&e.1, &art)); let outer = self.made_again; diff --git a/crates/render/src/proof.rs b/crates/render/src/proof.rs index 284ad8ce5d..e809afb4ee 100644 --- a/crates/render/src/proof.rs +++ b/crates/render/src/proof.rs @@ -28,11 +28,11 @@ use std::sync::{Arc, Mutex, OnceLock, RwLock, Weak}; use vectorcraft_color::cms::{self, Cms, CmykLut, PROCESS_PLATES, ProofLut, lab}; pub use vectorcraft_color::cms::{Intent, ProofSetup, ProofTarget}; -use vectorcraft_color::{Color, Swatch, SwatchGroup}; +use vectorcraft_color::{Color, Paint, Swatch, SwatchGroup}; pub use vectorcraft_doc::inks::{Inks, Link, Plate, inks, map_document_colors, map_node_colors, plates, spot_color}; use vectorcraft_doc::inks::{StopPlates, map_node_inks, stop_inks}; use vectorcraft_doc::overprint::darken_overprints; -use vectorcraft_doc::{Document, ImageBlob, Node, NodeId, Shared}; +use vectorcraft_doc::{AppearanceItem, Document, ImageBlob, Node, NodeId, Shared}; use vello_cpu::Pixmap; use vello_cpu::color::PremulRgba8; @@ -80,6 +80,46 @@ fn plate_color(doc: &Document, c: &Cms, proof: &ProofSetup, visible: &[String], Color::Rgb { r, g, b } } +/// Map grayscale inks created after document preparation to the visible plates. +pub(crate) fn generated_black(doc: &Document, proof: &ProofSetup, art: &Arc) -> Arc { + let Some(visible) = proof.separations.as_deref() else { return art.clone() }; + let c = cms::active(); + let mut made = Node::clone(art); + if !visible.iter().any(|plate| plate == "Black") { + hide_generated_black(&mut made); + } + let mut changed = false; + map_node_inks(&mut made, &mut |color, link, plates| { + // Document colors are already display RGB; newly generated black retains its Gray ink. + if matches!(color, Color::Gray { .. }) { + changed = true; + plate_color(doc, &c, proof, visible, color, link, plates) + } else { + *color + } + }); + if changed { Arc::new(made) } else { art.clone() } +} + +fn hide_generated_black(node: &mut Node) { + for item in &mut node.appearance.items { + match item { + AppearanceItem::Fill(layer) if layer.overprint && matches!(layer.paint, Paint::Solid { color: Color::Gray { .. }, swatch: None, .. }) => { + layer.visible = false; + } + AppearanceItem::Stroke(layer) + if layer.overprint && matches!(layer.paint, Paint::Solid { color: Color::Gray { .. }, swatch: None, .. }) => + { + layer.visible = false; + } + _ => {} + } + } + for child in node.children_mut().into_iter().flatten() { + hide_generated_black(Arc::make_mut(child)); + } +} + /// Separations Preview's tables for placed images: what the visible plates show of display pixels /// and of a CMYK image's own inks ([`plate_rgb`]), for one proof setup, color settings and set of /// profiles. Each table is made when an image first needs it. diff --git a/crates/render/src/renderer/nodes.rs b/crates/render/src/renderer/nodes.rs index bd26c851cd..3e79641a51 100644 --- a/crates/render/src/renderer/nodes.rs +++ b/crates/render/src/renderer/nodes.rs @@ -499,7 +499,7 @@ impl Renderer { fn draw_content(&mut self, ctx: &mut RenderContext, f: &Frame, n: &Node, knockout: bool) { match &n.kind { NodeKind::Group { children, clip: false } if f.opts.trace_views && !f.opts.outline && Self::trace_view(f, n) != TraceView::Result => { - self.draw_trace_view(ctx, f, children, Self::trace_view(f, n), knockout) + self.draw_trace_view(ctx, f, children, (Self::trace_view(f, n), n.trace_split()), knockout) } NodeKind::Layer { children, clip: false, .. } | NodeKind::Group { children, clip: false } => { self.draw_children(ctx, f, children, knockout) @@ -641,9 +641,56 @@ impl Renderer { } /// An Image Trace object's `children` (the hidden source image, then the traced shapes) as - /// `view` shows them on screen. - fn draw_trace_view(&mut self, ctx: &mut RenderContext, f: &Frame, children: &[Arc], view: TraceView, knockout: bool) { + /// `view` shows them on screen, with `split`, the Split view's divider + /// ([`TraceView::split_of`]). + fn draw_trace_view(&mut self, ctx: &mut RenderContext, f: &Frame, children: &[Arc], (view, split): (TraceView, f64), knockout: bool) { let Some((source, shapes)) = children.split_first() else { return }; + if view == TraceView::Split { + // Each side is drawn once under a plain clip (no layer and no second render), in the + // image's own pixels so the divider turns with the image: the source image on the part + // of the image left of the divider, and the traced shapes everywhere else, art past any + // of the image's edges included. Without an image, with one of no size or that can't + // be inverted, or with the divider at the image's left edge, the traced shapes draw as + // they are. + let NodeKind::Image(im) = &source.kind else { return self.draw_children(ctx, f, shapes, knockout) }; + let (w, h) = (f64::from(im.width), f64::from(im.height)); + let at = w * split.clamp(0.0, 1.0); + let det = im.xf.determinant(); + if w <= 0.0 || h <= 0.0 || at <= 0.0 || !det.is_finite() || det.abs() < 1e-12 { + return self.draw_children(ctx, f, shapes, knockout); + } + // The result's side covers the image and the traced shapes' cached bounds, two screen + // pixels more so anti-aliased edges are not cut, in the image's pixels, less the + // source's side. + let inverse = im.xf.inverse(); + let (mut x0, mut x1, mut y0, mut y1) = (0.0_f64, w, 0.0_f64, h); + for c in shapes { + if let Some(b) = self.bounds_of(f.symbols, c).map(|b| b.inflate(f.px * 2.0, f.px * 2.0)) { + for q in [(b.x0, b.y0), (b.x1, b.y0), (b.x1, b.y1), (b.x0, b.y1)] { + let p = inverse * kurbo::Point::new(q.0, q.1); + if p.x.is_finite() && p.y.is_finite() { + (x0, x1, y0, y1) = (x0.min(p.x), x1.max(p.x), y0.min(p.y), y1.max(p.y)); + } + } + } + } + let part = |p: &mut BezPath, x0: f64, x1: f64, y0: f64, y1: f64| { + p.move_to(im.xf * kurbo::Point::new(x0, y0)); + p.line_to(im.xf * kurbo::Point::new(x1, y0)); + p.line_to(im.xf * kurbo::Point::new(x1, y1)); + p.line_to(im.xf * kurbo::Point::new(x0, y1)); + p.close_path(); + }; + let (mut left, mut right) = (BezPath::new(), BezPath::new()); + part(&mut left, 0.0, at, 0.0, h); + part(&mut right, x0, x1, y0, y1); + part(&mut right, 0.0, at, 0.0, h); + let comp = Composite { clip: Some((&left, FillRule::NonZero)), blends: true, ..Default::default() }; + self.group(ctx, f, comp, &mut |r, c, fr| r.draw_forced_arc(c, fr, source)); + let comp = Composite { clip: Some((&right, FillRule::EvenOdd)), blends: true, ..Default::default() }; + self.group(ctx, f, comp, &mut |r, c, fr| r.draw_children(c, fr, shapes, knockout)); + return; + } if view.shows_source() && matches!(source.kind, NodeKind::Image(_)) { self.draw_forced_arc(ctx, f, source); } diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index 2a0e6c9a93..d3c9b708d5 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -841,6 +841,79 @@ fn trace_source_applies_the_hidden_image_mask() { assert_eq!(img.pixel(70, 50), [255, 255, 255, 255]); } +/// The Split view draws the source image left of its divider and the traced shapes right of it, +/// along the image's own width (also when the image is turned), with traced art past any of the +/// image's edges drawn whatever the divider, in the same frames a renderer that keeps its caches +/// draws, and in a zoomed and scrolled view and a turned view; exports draw the tracing result. +#[test] +fn split_view_draws_the_source_on_one_side_of_the_divider_and_the_result_on_the_other() { + use vectorcraft_doc::{ImageBlob, ImageObject}; + let mut png = vec![]; + image::RgbaImage::from_pixel(1, 1, image::Rgba([255, 0, 0, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let red = |p: [u8; 4]| p[0] > 200 && p[1] < 60 && p[2] < 60; + let blue = |p: [u8; 4]| p[2] > 200 && p[0] < 60; + // A red 80 × 80 source image at 10, 10, turned a half turn about its center when `turned`, with + // a blue traced square over all of it. + for turned in [false, true] { + let mut d = Document::new(100.0, 100.0); + d.images.insert("red".into(), ImageBlob::new("image/png", png.clone())); + let turn = if turned { Affine::rotate_about(std::f64::consts::PI, kurbo::Point::new(50.0, 50.0)) } else { Affine::IDENTITY }; + let xf = turn * Affine::translate((10.0, 10.0)) * Affine::scale(80.0); + let im = ImageObject { key: "red".into(), width: 1, height: 1, xf, link: None, placement: Default::default(), pixels: None }; + let mut source = Node::new(d.alloc_id(), NodeKind::Image(Box::new(im))); + source.visible = false; + let shape = rect_node(&mut d, Rect::new(10.0, 10.0, 90.0, 90.0), Paint::solid(Color::rgb(0.0, 0.0, 1.0)), Paint::None, 0.0); + // Traced art past the image's right edge on the page (a stroke along it, say). + let past = rect_node(&mut d, Rect::new(92.0, 46.0, 98.0, 54.0), Paint::solid(Color::rgb(0.0, 1.0, 0.0)), Paint::None, 0.0); + // And above the image's top edge, near its left edge. + let above = rect_node(&mut d, Rect::new(14.0, 2.0, 26.0, 8.0), Paint::solid(Color::rgb(0.0, 1.0, 0.0)), Paint::None, 0.0); + let mut g = Node::group(d.alloc_id(), vec![Arc::new(source), Arc::new(shape), Arc::new(past), Arc::new(above)]); + let id = g.id; + g.extras_mut().trace = Some(Box::new(serde_json::json!({ "view": "split", "split": 0.25 }))); + d.insert(Some(d.layers[0].id), 0, g).unwrap(); + let screen = RenderOptions { trace_views: true, background: Some([255; 4]), ..Default::default() }; + let export = RenderOptions { background: Some([255; 4]), ..Default::default() }; + let mut kept = Renderer::new(); + for split in [0.25, 0.0, 1.0, 0.25] { + if let Some(n) = d.node_mut(id) { + n.extras_mut().trace = Some(Box::new(serde_json::json!({ "view": "split", "split": split }))); + } + // The divider in page space: 30 across from the image's left edge, or from its right + // edge on the page once the image is turned. + let at = if turned { 90.0 - 80.0 * split } else { 10.0 + 80.0 * split }; + // The view: as is, zoomed in twice and scrolled, and turned a half turn about the page's + // middle; `px` finds the pixel showing page point (x, y). + let views: [(Affine, u32); 3] = [ + (Affine::IDENTITY, 100), + (Affine::translate((5.0, 7.0)) * Affine::scale(2.0), 210), + (Affine::rotate_about(std::f64::consts::PI, kurbo::Point::new(50.0, 50.0)), 100), + ]; + for (view, size) in views { + let px = |r: &Rendered, x: f64, y: f64| { + let q = view * kurbo::Point::new(x, y); + r.pixel(q.x.floor() as u32, q.y.floor() as u32) + }; + for r in [kept.render(&d, size, size, view, &screen), Renderer::new().render(&d, size, size, view, &screen)] { + for x in [12.5, 30.5, 48.5, 52.5, 70.5, 88.5] { + let p = px(&r, x, 50.5); + let source = if turned { x > at } else { x < at }; + assert!(if source { red(p) } else { blue(p) }, "turned {turned}, split {split}, view {view:?}, x = {x}: {p:?}"); + } + assert_eq!(px(&r, 5.5, 50.5), [255; 4], "nothing outside the image"); + // The art past the image's edges shows on either side of the divider. + let green = |p: [u8; 4]| p[1] > 200 && p[0] < 60 && p[2] < 60; + for (x, y) in [(95.5, 50.5), (20.5, 5.5)] { + let p = px(&r, x, y); + assert!(green(p), "turned {turned}, split {split}, view {view:?}, ({x}, {y}): {p:?}"); + } + } + } + let r = Renderer::new().render(&d, 100, 100, Affine::IDENTITY, &export); + assert!([12u32, 50, 88].iter().all(|x| blue(r.pixel(*x, 50))), "exports draw the result"); + } + } +} + #[test] fn artboards_white_on_pasteboard() { let d = Document::new(50.0, 50.0); diff --git a/crates/svg/src/export.rs b/crates/svg/src/export.rs index ded9a037fe..84b2efa32b 100644 --- a/crates/svg/src/export.rs +++ b/crates/svg/src/export.rs @@ -78,6 +78,18 @@ fn update_editing_hash(svg: &mut String) { } } +/// Format physical dimensions (inches, mm, cm) with enough precision and significant digits +/// that small nonzero sizes do not round to zero or distort relative aspect ratio. +fn physical_num(v: f64) -> String { + if !v.is_finite() || v <= 0.0 { + return "0".into(); + } + let leading_zeros = (-v.log10().floor() as i32).max(0); + let decimals = (leading_zeros + 3).clamp(3, 14) as u8; + let s = fmt_num(v, decimals); + if s == "0" && v > 0.0 { format!("{v:.16}").trim_end_matches('0').trim_end_matches('.').to_string() } else { s } +} + /// `doc` as SVG with `opts`, the native file `native` embedded for Preserve Editing, its generated /// ids starting with `id_prefix`. fn write(doc: &Document, opts: &ExportOptions, native: Option<&[u8]>, id_prefix: &str) -> Output { @@ -183,10 +195,17 @@ fn write(doc: &Document, opts: &ExportOptions, native: Option<&[u8]>, id_prefix: root = root.attr("version", "1.2").attr("baseProfile", "tiny"); } if !opts.responsive { - // Unitless width/height stay in this one branch so #7105 (physical unit suffixes) can rebase here. - root = root.attr("width", &ww).attr("height", &hh); + if let Some(suffix) = doc.units.svg_suffix() { + let w_val = physical_num(doc.units.from_pt(rect.width())); + let h_val = physical_num(doc.units.from_pt(rect.height())); + root = root.attr("width", format_args!("{w_val}{suffix}")).attr("height", format_args!("{h_val}{suffix}")); + } else { + root = root.attr("width", &ww).attr("height", &hh); + } } - root.attr("viewBox", format_args!("0 0 {ww} {hh}")).open(); + let vb_w = if rect.width() > 0.0 && ww == "0" { physical_num(rect.width()) } else { ww.clone() }; + let vb_h = if rect.height() > 0.0 && hh == "0" { physical_num(rect.height()) } else { hh.clone() }; + root.attr("viewBox", format_args!("0 0 {vb_w} {vb_h}")).open(); let mut out = svg.as_str().to_string(); out.push_str(nl); let css = opts.styling == Styling::InternalCss && !w.classes.is_empty(); diff --git a/crates/svg/tests/it/import_units.rs b/crates/svg/tests/it/import_units.rs index 1ce01c7f07..0140741aeb 100644 --- a/crates/svg/tests/it/import_units.rs +++ b/crates/svg/tests/it/import_units.rs @@ -3,7 +3,7 @@ use vectorcraft_doc::{Document, Node, NodeKind, Unit}; use vectorcraft_geom::Rect; -use vectorcraft_svg::import; +use vectorcraft_svg::{ExportOptions, export, import}; fn art(d: &Document) -> Vec<&Node> { let mut v = Vec::new(); @@ -130,3 +130,65 @@ fn absolute_lengths_in_a_pixel_document_keep_their_size() { assert!(close_rect(n.geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 72.0, 720.0 / 25.4)), "{:?}", n.geometric_bounds()); assert!(close(n.appearance.stroke_width(), 2.0)); } + +#[test] +fn export_physical_units_writes_unit_suffixes() { + // Millimeters (#864 / G11: avoid 75% scale in external tools like LightBurn, LaserGRBL, Inkscape) + let mut d = Document::new(50.0 * 72.0 / 25.4, 30.0 * 72.0 / 25.4); + d.units = Unit::Millimeters; + let s = export(&d, &ExportOptions::default()); + assert!(s.contains("width=\"50mm\" height=\"30mm\""), "{s}"); + assert!(s.contains("viewBox=\"0 0 141.732 85.039\""), "{s}"); + + // Inches + let mut d = Document::new(8.5 * 72.0, 11.0 * 72.0); + d.units = Unit::Inches; + let s = export(&d, &ExportOptions::default()); + assert!(s.contains("width=\"8.5in\" height=\"11in\""), "{s}"); + assert!(s.contains("viewBox=\"0 0 612 792\""), "{s}"); + + // Centimeters + let mut d = Document::new(5.0 * 72.0 / 2.54, 3.0 * 72.0 / 2.54); + d.units = Unit::Centimeters; + let s = export(&d, &ExportOptions::default()); + assert!(s.contains("width=\"5cm\" height=\"3cm\""), "{s}"); + + // Picas + let mut d = Document::new(10.0 * 12.0, 20.0 * 12.0); + d.units = Unit::Picas; + let s = export(&d, &ExportOptions::default()); + assert!(s.contains("width=\"10pc\" height=\"20pc\""), "{s}"); + + // Points and pixels remain unitless + let mut d = Document::new(100.0, 200.0); + d.units = Unit::Points; + let s = export(&d, &ExportOptions::default()); + assert!(s.contains("width=\"100\" height=\"200\""), "{s}"); + + d.units = Unit::Pixels; + let s = export(&d, &ExportOptions::default()); + assert!(s.contains("width=\"100\" height=\"200\""), "{s}"); + + // Responsive export omits width and height even with physical units + d.units = Unit::Millimeters; + let s = export(&d, &ExportOptions { responsive: true, ..Default::default() }); + assert!(!s.contains("width="), "{s}"); + assert!(!s.contains("height="), "{s}"); + + // Non-zero small dimensions do not round to zero + let mut d = Document::new(0.001 * 72.0 / 25.4, 0.002 * 72.0 / 25.4); + d.units = Unit::Millimeters; + let s = export(&d, &ExportOptions::default()); + assert!(s.contains("width=\"0.001mm\" height=\"0.002mm\""), "{s}"); + + // Extreme small dimension below 8 decimal places preserves non-zero width and viewBox + let mut d = Document::new(1e-9 * 72.0 / 25.4, 1e-9 * 72.0 / 25.4); + d.units = Unit::Millimeters; + let s = export(&d, &ExportOptions::default()); + assert!(!s.contains("width=\"0mm\""), "{s}"); + assert!(!s.contains("viewBox=\"0 0 0 0\""), "{s}"); + + // Re-importing preserved physical units + let back = import(&s).unwrap(); + assert_eq!(back.units, Unit::Millimeters); +} diff --git a/crates/text/src/fontdb.rs b/crates/text/src/fontdb.rs index 83c55a71ca..b7efa856c8 100644 --- a/crates/text/src/fontdb.rs +++ b/crates/text/src/fontdb.rs @@ -56,7 +56,7 @@ use face::Instances; #[cfg(test)] pub(crate) use face::MAX_LIVE_INSTANCES; pub(crate) use face::PathAlignHeights; -pub use face::{FALLBACK_FAMILY, FontFace, IcfMargins}; +pub use face::{FALLBACK_FAMILY, FontFace, IcfMargins, OutlineFormat}; pub(crate) use glyph_pen::FlipPen; pub use gsub::{GlyphCategory, GlyphCategoryKind, GlyphOrigin, JoiningPosition, Substitution, SubstitutionKind}; #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/text/src/fontdb/face.rs b/crates/text/src/fontdb/face.rs index f02ebea3fc..5c21fbb4f1 100644 --- a/crates/text/src/fontdb/face.rs +++ b/crates/text/src/fontdb/face.rs @@ -753,4 +753,54 @@ impl FontFace { use skrifa::raw::TableProvider; self.skrifa().is_some_and(|f| f.glyf().is_ok()) } + /// The kind of outlines the face's glyphs are drawn from ([`outline_format_of`]). + pub fn outline_format(&self) -> Option { + self.skrifa().and_then(|f| outline_format_of(&f)) + } +} + +/// The kind of outlines a face's glyphs are drawn from. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum OutlineFormat { + /// Quadratic outlines in a `glyf` table. + TrueType, + /// PostScript outlines in a `CFF ` or `CFF2` table. + Cff, +} + +/// The kind of outlines `font`'s glyphs are drawn from: TrueType when it has a `glyf` table, else +/// CFF when it has a `CFF ` or `CFF2` table. None for a font with neither (outlines in `VARC` +/// alone, color bitmaps only). +pub(crate) fn outline_format_of(font: &skrifa::FontRef<'_>) -> Option { + let has = |tag: &[u8; 4]| font.table_data(skrifa::Tag::new(tag)).is_some(); + if has(b"glyf") { + Some(OutlineFormat::TrueType) + } else if has(b"CFF ") || has(b"CFF2") { + Some(OutlineFormat::Cff) + } else { + None + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The outline format comes from the tables the font holds. + #[test] + fn outline_format_follows_the_outline_tables() { + let format = |tables: &[(&[u8; 4], &[u8])]| { + let font = crate::fontdb::sfnt_of(tables).unwrap_or_default(); + outline_format_of(&skrifa::FontRef::new(&font).unwrap()) + }; + let table = [0_u8; 4]; + assert_eq!(format(&[(b"glyf", &table), (b"loca", &table)]), Some(OutlineFormat::TrueType)); + assert_eq!(format(&[(b"CFF ", &table)]), Some(OutlineFormat::Cff)); + assert_eq!(format(&[(b"CFF2", &table)]), Some(OutlineFormat::Cff)); + assert_eq!(format(&[(b"VARC", &table)]), None); + assert_eq!(format(&[(b"sbix", &table)]), None); + // The built-in faces are TrueType. + let face = crate::FontDb::global().resolve("Source Sans 3", "Regular").map(|(f, _)| f).unwrap(); + assert_eq!(face.outline_format(), Some(OutlineFormat::TrueType)); + } } diff --git a/crates/text/src/layout.rs b/crates/text/src/layout.rs index 04e594ed16..fee74054c1 100644 --- a/crates/text/src/layout.rs +++ b/crates/text/src/layout.rs @@ -36,6 +36,7 @@ mod vertical; mod warichu; pub(crate) use bidi::{is_rtl, para_bidi, starts_bidi}; +pub(crate) use breaking::is_hanging_punctuation; use breaking::tab_advance; #[cfg(test)] use breaking::{break_line, candidates}; diff --git a/crates/text/src/layout/breaking.rs b/crates/text/src/layout/breaking.rs index 874813e9b1..bfc984f83e 100644 --- a/crates/text/src/layout/breaking.rs +++ b/crates/text/src/layout/breaking.rs @@ -1,11 +1,76 @@ use super::region::Region; use super::vertical::stands_upright; use super::{ - Affine, BezPath, Breakpoint, Burasagari, EPS, FirstBaseline, FontDb, HyphenationOptions, Kinsoku, KinsokuShoriType, LeadingModel, SGlyph, - hyphen_glyph, is_cjk, no_line_end, no_line_start, points_for, soft_line_start, + Affine, BezPath, Breakpoint, Burasagari, EPS, FirstBaseline, FontDb, HyphenationOptions, Kinsoku, KinsokuShoriType, LeadingModel, ParaStyle, + SGlyph, hyphen_glyph, is_cjk, no_line_end, no_line_start, points_for, soft_line_start, }; use crate::justify::is_format_control; +/// The kinsoku rules a paragraph is composed with: a built-in Kinsoku Set (None, Hard or Soft), or +/// a custom set (Type › Kinsoku Shori Settings…). +#[derive(Clone, Copy, Debug)] +pub(crate) enum KinsokuRules<'a> { + BuiltIn(Kinsoku), + Custom(&'a vectorcraft_doc::KinsokuSet), +} + +impl<'a> KinsokuRules<'a> { + /// The rules of paragraph `para`: its custom set when it has one, else its Kinsoku Set. + pub(crate) fn of(para: &'a ParaStyle) -> Self { + match ¶.kinsoku_set { + Some(set) => Self::Custom(set), + None => Self::BuiltIn(para.kinsoku), + } + } + + /// Kinsoku None: no character is kept off a line's ends, and Bunri-Kinshi has no effect. + pub(crate) fn is_none(self) -> bool { + matches!(self, Self::BuiltIn(Kinsoku::None)) + } + + /// May `c` not start a line? Hard: every character of [`no_line_start`]; Soft: those + /// [`soft_line_start`] doesn't let start one; a custom set: its Cannot Start Line characters. + pub(crate) fn cannot_start(self, c: char) -> bool { + match self { + Self::BuiltIn(Kinsoku::None) => false, + Self::BuiltIn(Kinsoku::Hard) => no_line_start(c), + Self::BuiltIn(Kinsoku::Soft) => no_line_start(c) && !soft_line_start(c), + Self::Custom(set) => set.cannot_start(c), + } + } + + /// May `c` not end a line? Hard and Soft: an opening bracket ([`no_line_end`]); a custom set: + /// its Cannot End Line characters. + pub(crate) fn cannot_end(self, c: char) -> bool { + match self { + Self::BuiltIn(Kinsoku::None) => false, + Self::BuiltIn(Kinsoku::Hard | Kinsoku::Soft) => no_line_end(c), + Self::Custom(set) => set.cannot_end(c), + } + } + + /// May `c` hang outside a line's end with Burasagari? An East Asian comma or full stop (、。,. + /// and the half-width 、。), or a custom set's Hanging Punctuation characters. + pub(crate) fn hangs(self, c: char) -> bool { + match self { + Self::BuiltIn(_) => is_hanging_punctuation(c), + Self::Custom(set) => set.hangs(c), + } + } +} + +impl From for KinsokuRules<'_> { + fn from(k: Kinsoku) -> Self { + Self::BuiltIn(k) + } +} + +/// The punctuation Burasagari hangs with the built-in Kinsoku Sets: the East Asian comma and full +/// stop, full width and half width. +pub(crate) fn is_hanging_punctuation(c: char) -> bool { + matches!(c, '、' | '。' | ',' | '.' | '、' | '。') +} + /// Vertical metrics of a line: (ascent, descent, leading, cap height, x height). #[derive(Clone, Copy, Debug, PartialEq)] pub(super) struct Metrics { @@ -351,12 +416,13 @@ pub(super) fn leader_outline(db: &FontDb, g: &SGlyph, leader: &str, origin: f64, /// Width of the word starting at glyph `i`: its advances up to the first place a line may break /// (spaces left out, the hyphen of a soft hyphen in), the least room a line needs not to break /// inside it. As in [`break_line`], kinsoku keeps a character that may not end a line with the one -/// after it, a No Break run (its spaces inside it included) is one word up to a forced line break, +/// after it, spaces between them included, a No Break run (its spaces inside it included) is one word up to a forced line break, /// and a cluster is never split. A soft hyphen just before a forced line break adds no hyphen. A list marker at `i` (glyphs of length 0) counts whole, with the word after it. A word /// that ends where a line may end is measured as the line is set: without the spaces at its end, /// and with its last glyph as narrow as `line_end` sets it; one that ends at a soft hyphen or past -/// the measured glyphs is not. -pub(super) fn word_width(g: &[SGlyph], i: usize, line_end: &[f64], kinsoku: Kinsoku) -> f64 { +/// the measured glyphs is not. With `burasagari`, the word may end after hanging punctuation. +pub(super) fn word_width<'k>(g: &[SGlyph], i: usize, line_end: &[f64], kinsoku: impl Into>, burasagari: Burasagari) -> f64 { + let kinsoku = kinsoku.into(); /// Glyphs measured at most: a word wrapped over many lines is measured again from each line's /// start, and one this long is broken inside whatever cell it meets. const MAX_GLYPHS: usize = 1024; @@ -375,7 +441,15 @@ pub(super) fn word_width(g: &[SGlyph], i: usize, line_end: &[f64], kinsoku: Kins return set(w, trailing, ink); } if gl.is_space() && (end == start || !splits_no_break(g, end)) { - return set(w, trailing, ink); + // A line breaks after one of these spaces only where kinsoku allows it, as in + // [`break_line`]; where it allows none (after 「, or before 」), the word goes on past them. + let run = end + g[end..].iter().take(start + MAX_GLYPHS - end).take_while(|h| h.is_space()).count(); + if end == start || (end..run).any(|k| g[k].break_after() && g[k].len > 0 && kinsoku_allows(g, k, kinsoku) && !splits_no_break(g, k + 1)) { + return set(w, trailing, ink); + } + let spaces: f64 = g[end..run].iter().map(|h| h.adv).sum(); + (w, trailing, end) = (w + spaces, trailing + spaces, run); + continue; } let forced_next = g.get(end + 1).is_some_and(|n| n.ch == '\u{2028}'); if gl.is_soft_hyphen() && !forced_next && kinsoku_allows(g, end, kinsoku) && !splits_no_break(g, end + 1) { @@ -389,7 +463,10 @@ pub(super) fn word_width(g: &[SGlyph], i: usize, line_end: &[f64], kinsoku: Kins (trailing, ink) = (0.0, end); } let cluster_ends = g.get(end).is_none_or(|next| next.byte != gl.byte); - if gl.break_after() && cluster_ends && kinsoku_allows(g, end - 1, kinsoku) && !splits_no_break(g, end) { + // Hanging punctuation of one glyph may end the line with Burasagari, as in [`break_line`]. + let alone = cluster_ends && end.checked_sub(2).and_then(|k| g.get(k)).is_none_or(|p| p.byte != gl.byte); + let hang_break = burasagari != Burasagari::None && alone && hangs(gl, kinsoku); + if (gl.break_after() || hang_break) && cluster_ends && kinsoku_allows(g, end - 1, kinsoku) && !splits_no_break(g, end) { return set(w, trailing, ink); } } @@ -442,7 +519,7 @@ fn drawn_last(g: &[SGlyph], i: usize, j: usize, end: usize) -> bool { /// end in the visual order of the line's levels ([`drawn_last`]) and the line before the mark fits /// as drawn. #[allow(clippy::too_many_arguments)] -pub(super) fn break_line( +pub(super) fn break_line<'k>( text: &str, g: &[SGlyph], i: usize, @@ -451,13 +528,14 @@ pub(super) fn break_line( x_start: f64, hyphenate: Option<(&HyphenationOptions, f64)>, burasagari: Burasagari, - kinsoku: Kinsoku, + kinsoku: impl Into>, kinsoku_type: KinsokuShoriType, hanging: bool, vertical: bool, line_end: &[f64], fits: Option<&dyn Fn(usize, bool) -> bool>, ) -> (usize, bool) { + let kinsoku = kinsoku.into(); let settle = |tabbed: bool, checks: usize, chosen: (usize, bool), breaks: &[(usize, bool)]| { craft_font_catalog::settle_line_break(tabbed, checks, i, chosen, breaks, fits) }; @@ -551,13 +629,14 @@ pub(super) fn break_line( let measured = if tabbed && fits.is_some() { (ink + cluster_ink).max(stops_reached) } else { x + cluster_width }; overflowed |= tabbed && fits.is_some() && j > first && !gl.is_space() && x + cluster_width - end_credit > width + EPS; if j > first && !gl.is_space() && measured - end_credit > width + EPS { - // It ends the line with the spaces after it, when the mark is all the characters kept - // together (the line's last character is the mark, which is what hangs). Once the line - // holds a tab and is measured as drawn, the mark hangs only where it is drawn at the - // line's right end (its cluster is last in the line's visual order, [`drawn_last`]) and - // the line before it fits as drawn with no line-end trim on its last glyph; otherwise the - // line ends at a legal break that fits as drawn. - let alone = g[j..cluster_end].iter().all(|h| h.byte == gl.byte); + // It ends the line with the spaces after it, when it hangs alone: not with the rest of a + // No Break run or an inseparable sequence it starts, and only as one glyph, the one the + // line's geometry hangs. Once the line holds a tab and is measured as drawn, the mark + // hangs only where it is drawn at the line's right end (its cluster is last in the + // line's visual order, [`drawn_last`]) and the line before it fits as drawn with no + // line-end trim on its last glyph; otherwise the line ends at a legal break that fits as + // drawn. + let alone = cluster_end == j + 1; let hangs_as_drawn = || match fits.filter(|_| tabbed) { None => true, Some(fits) => { @@ -568,7 +647,7 @@ pub(super) fn break_line( drawn_last(g, i, j, cluster_end) && line_end_credit(g, line_end, body) == 0.0 && fits(j, false) } }; - if burasagari != Burasagari::None && hangs(gl) && alone && kinsoku_allows(g, cluster_end - 1, kinsoku) && hangs_as_drawn() { + if burasagari != Burasagari::None && alone && hangs(gl, kinsoku) && kinsoku_allows(g, cluster_end - 1, kinsoku) && hangs_as_drawn() { let mut end = cluster_end; while g.get(end).is_some_and(SGlyph::is_space) { end += 1; @@ -586,7 +665,10 @@ pub(super) fn break_line( ink += cluster_ink; back += cluster_back; let last = &g[cluster_end - 1]; - if last.break_after() && last.len > 0 && kinsoku_allows(g, cluster_end - 1, kinsoku) && !splits_no_break(g, cluster_end) { + // Hanging punctuation that would hang alone where it overflows may end the line where it + // fits too: a custom set's may be a character no other rule breaks after. + let hang_break = burasagari != Burasagari::None && cluster_end == j + 1 && hangs(last, kinsoku); + if (last.break_after() || hang_break) && last.len > 0 && kinsoku_allows(g, cluster_end - 1, kinsoku) && !splits_no_break(g, cluster_end) { // Once the line holds a tab, whether a break fits as drawn is settled when the line ends. let hyphenated = last.is_soft_hyphen(); if !hyphenated || (tabbed && fits.is_some()) || x + hyphen_glyph(last).adv <= width + EPS { @@ -661,11 +743,12 @@ pub(super) fn break_line( } /// Can glyph `g` hang outside the line (burasagari)? An East Asian comma or full stop, full width -/// (、。,.) or half width (、。); not a closing bracket, nor Latin punctuation (Latin text keeps -/// its line breaks and composer). Never an inline graphic (U+FFFC), nor a character of a -/// tate-chu-yoko or warichu block. -pub(super) fn hangs(g: &SGlyph) -> bool { - g.inline.is_none() && matches!(g.ch, '、' | '。' | ',' | '.' | '、' | '。') && g.tcy.is_none() && g.wari.is_none() +/// (、。,.) or half width (、。), or with a custom set a character of its Hanging Punctuation +/// ([`KinsokuRules::hangs`]); with the built-in sets not a closing bracket, nor Latin punctuation +/// (Latin text keeps its line breaks and composer). Never an inline graphic (U+FFFC), nor a +/// character of a tate-chu-yoko or warichu block. +pub(super) fn hangs(g: &SGlyph, kinsoku: KinsokuRules<'_>) -> bool { + g.inline.is_none() && kinsoku.hangs(g.ch) && g.tcy.is_none() && g.wari.is_none() } /// Optical Margin Alignment: the share of glyph `g`'s advance that hangs outside the margin when @@ -755,7 +838,7 @@ fn line_end_credit(g: &[SGlyph], line_end: &[f64], end: usize) -> f64 { /// May [`break_line`] end a line after glyph `end - 1` (and the spaces after it)? At the paragraph's /// end or a forced line break, and where it records a break without a hyphen. -fn may_end_after(g: &[SGlyph], end: usize, kinsoku: Kinsoku) -> bool { +fn may_end_after(g: &[SGlyph], end: usize, kinsoku: KinsokuRules<'_>) -> bool { let mut e = end; while g.get(e).is_some_and(SGlyph::is_space) { e += 1; @@ -775,20 +858,25 @@ fn splits_no_break(g: &[SGlyph], end: usize) -> bool { /// Does kinsoku allow a line break after glyph `j`? Not after an opening bracket, nor before a /// closing one, a comma, a full stop, a small kana… (the character is pushed to the next line -/// with the one before it). -fn kinsoku_allows(g: &[SGlyph], j: usize, kinsoku: Kinsoku) -> bool { - g.get(j).is_some_and(|gl| kinsoku_between(gl.ch, g.get(j + 1).map(|n| n.ch), kinsoku)) +/// with the one before it). A line that breaks after spaces is drawn without them, so the +/// character before them is the one that ends it: up to [`KINSOKU_SPACES_BACK`] spaces are looked +/// past, and after a longer run of spaces the space itself counts. +fn kinsoku_allows(g: &[SGlyph], j: usize, kinsoku: KinsokuRules<'_>) -> bool { + let Some(gl) = g.get(j) else { return false }; + let before = if gl.is_space() { g[..j].iter().rev().take(KINSOKU_SPACES_BACK).find(|h| !h.is_space()).map_or(gl.ch, |h| h.ch) } else { gl.ch }; + kinsoku_between(before, g.get(j + 1).map(|n| n.ch), kinsoku) } +/// The most spaces [`kinsoku_allows`] looks past for the character that ends a line, so a long run +/// of spaces is not read again at each of its breaks. +const KINSOKU_SPACES_BACK: usize = 64; + /// Kinsoku for a break between `before` and `after` (none: the end of the paragraph): Hard keeps /// every character of the set off the line start and end, Soft lets 々, ー and small kana start a -/// line, None allows the break. -fn kinsoku_between(before: char, after: Option, kinsoku: Kinsoku) -> bool { - match kinsoku { - Kinsoku::None => true, - Kinsoku::Hard => !no_line_end(before) && after.is_none_or(|c| !no_line_start(c)), - Kinsoku::Soft => !no_line_end(before) && after.is_none_or(|c| !no_line_start(c) || soft_line_start(c)), - } +/// line, a custom set keeps its own characters off them ([`KinsokuRules`]), and None allows the +/// break. +fn kinsoku_between(before: char, after: Option, kinsoku: KinsokuRules<'_>) -> bool { + !kinsoku.cannot_end(before) && after.is_none_or(|c| !kinsoku.cannot_start(c)) } /// The share of an em by which a push-in ([`push_in`]) may close each gap next to a CJK character @@ -823,13 +911,13 @@ fn push_in( x: f64, width: f64, pushed_out: Option, - kinsoku: Kinsoku, + kinsoku: KinsokuRules<'_>, kinsoku_type: KinsokuShoriType, hanging: bool, vertical: bool, line_end: &[f64], ) -> Option { - if kinsoku == Kinsoku::None || kinsoku_type == KinsokuShoriType::PushOutOnly { + if kinsoku.is_none() || kinsoku_type == KinsokuShoriType::PushOutOnly { return None; } let before = g.get(j.checked_sub(1)?)?; @@ -933,13 +1021,30 @@ pub(super) fn squeeze_em(g: &SGlyph, vertical: bool) -> f64 { #[cfg(test)] #[test] fn kinsoku_keeps_closing_marks_off_line_starts_and_opening_ones_off_line_ends() { + let hard = KinsokuRules::BuiltIn(Kinsoku::Hard); for (a, b) in [('字', '。'), ('弧', '」'), ('」', '、'), ('ャ', 'ー'), ('カ', 'ッ'), ('「', 'か'), ('(', '雅')] { - assert!(!kinsoku_between(a, Some(b), Kinsoku::Hard), "{a}{b}"); + assert!(!kinsoku_between(a, Some(b), hard), "{a}{b}"); } for (a, b) in [('。', '雅'), ('」', 'は'), ('字', '「'), ('の', '演')] { - assert!(kinsoku_between(a, Some(b), Kinsoku::Hard), "{a}{b}"); + assert!(kinsoku_between(a, Some(b), hard), "{a}{b}"); } - assert!(kinsoku_between('。', None, Kinsoku::Hard)); + assert!(kinsoku_between('。', None, hard)); +} + +/// A custom set keeps its own characters off a line's ends, and nothing else: here 字 may not +/// start a line and 弧 may not end one, while 。 and 「 may. +#[cfg(test)] +#[test] +fn a_custom_kinsoku_set_keeps_its_own_characters_off_line_ends() { + let mut set = vectorcraft_doc::KinsokuSet { name: "Custom".into(), cannot_start: vec!['字'], cannot_end: vec!['弧'], ..Default::default() }; + set.normalize(); + let custom = KinsokuRules::Custom(&set); + assert!(!kinsoku_between('の', Some('字'), custom)); + assert!(!kinsoku_between('弧', Some('の'), custom)); + for (a, b) in [('字', '。'), ('「', 'か'), ('字', 'の')] { + assert!(kinsoku_between(a, Some(b), custom), "{a}{b}"); + } + assert!(!custom.is_none()); } /// Soft kinsoku lets 々, ー and small kana (JLREQ cl-09's 々, cl-10, cl-11) start a line and keeps @@ -947,13 +1052,14 @@ fn kinsoku_keeps_closing_marks_off_line_starts_and_opening_ones_off_line_ends() #[cfg(test)] #[test] fn soft_kinsoku_lets_small_kana_and_the_prolonged_sound_mark_start_a_line() { + let [none, hard, soft] = [Kinsoku::None, Kinsoku::Hard, Kinsoku::Soft].map(KinsokuRules::BuiltIn); for (a, b) in [('ャ', 'ー'), ('カ', 'ッ'), ('時', '々'), ('ト', 'ㇰ'), ('か', 'ゃ')] { - assert!(!kinsoku_between(a, Some(b), Kinsoku::Hard), "{a}{b}"); - assert!(kinsoku_between(a, Some(b), Kinsoku::Soft), "{a}{b}"); + assert!(!kinsoku_between(a, Some(b), hard), "{a}{b}"); + assert!(kinsoku_between(a, Some(b), soft), "{a}{b}"); } for (a, b) in [('字', '。'), ('弧', '」'), ('「', 'か'), ('カ', 'ッ'), ('カ', 'ー'), ('字', 'ゝ')] { - assert!(!kinsoku_between(a, Some(b), Kinsoku::Soft), "{a}{b}"); - assert!(kinsoku_between(a, Some(b), Kinsoku::None), "{a}{b}"); + assert!(!kinsoku_between(a, Some(b), soft), "{a}{b}"); + assert!(kinsoku_between(a, Some(b), none), "{a}{b}"); } } @@ -1001,7 +1107,13 @@ fn word_hyphen_breaks(text: &str, g: &[SGlyph], ws: usize, we: usize, opts: &Hyp /// paragraph's Hyphenation options) when it is given. No break comes before a space: a line that /// may end after a dash, a Thai word or a space ends after the spaces that follow it, as in /// [`break_line`]. -pub(super) fn candidates(text: &str, g: &[SGlyph], hyphenate: Option<&HyphenationOptions>, kinsoku: Kinsoku) -> Vec { +pub(super) fn candidates<'k>( + text: &str, + g: &[SGlyph], + hyphenate: Option<&HyphenationOptions>, + kinsoku: impl Into>, +) -> Vec { + let kinsoku = kinsoku.into(); let mut v = vec![]; let mut ws = 0; for (j, gl) in g.iter().enumerate() { diff --git a/crates/text/src/layout/flow.rs b/crates/text/src/layout/flow.rs index 36881e20d8..856ed12229 100644 --- a/crates/text/src/layout/flow.rs +++ b/crates/text/src/layout/flow.rs @@ -1,25 +1,32 @@ use super::bidi::{is_rtl, para_bidi_with, visual_order}; use super::breaking::{ - Metrics, PUSH_IN_SQUEEZE, Pen, break_line, candidates, drawn_after_tab, drawn_width, hangs, leader_outline, optical_hangs, optical_hangs_rtl, - optical_punct, optical_share, roman_share, squeeze_em, tab_advance, word_width, + KinsokuRules, Metrics, PUSH_IN_SQUEEZE, Pen, break_line, candidates, drawn_after_tab, drawn_width, hangs, leader_outline, optical_hangs, + optical_hangs_rtl, optical_punct, optical_share, roman_share, squeeze_em, tab_advance, word_width, }; use super::region::Region; use super::vertical::{ EM_CENTER, MojikumiRules, align_shift, compress_punctuation, dot_quarter, glyph_em, halve_punctuation, punct_half, space_japanese_and_latin, }; use super::{ - Affine, BidiInfo, Burasagari, CharStyle, Ctx, EPS, Flex, Justify, Kinsoku, KinsokuShoriType, LeadingModel, LineFit, LineInfo, ListMarker, - ParaStyle, Params, Point, Punct, Range, SGlyph, SingleWordJustify, TextObject, apply_desired, cap_x_heights, compose, fit_line, hyphen_glyph, - is_cjk, is_word_space, kashida, mark_word_ends, no_line_end, no_line_start, style_metrics, + Affine, BidiInfo, Burasagari, CharStyle, Ctx, EPS, Flex, Justify, KinsokuShoriType, LeadingModel, LineFit, LineInfo, ListMarker, ParaStyle, + Params, Point, Punct, Range, SGlyph, SingleWordJustify, TextObject, apply_desired, cap_x_heights, compose, fit_line, hyphen_glyph, is_cjk, + is_word_space, kashida, mark_word_ends, style_metrics, }; use crate::justify::is_format_control; -use crate::shape::{keep_inseparable_pairs, keep_korean_words, repeat_base, repeated_char, shape_range}; +use crate::shape::{keep_inseparable_pairs, keep_inseparable_sequences, keep_korean_words, repeat_base, repeated_char, shape_range}; use std::cell::Cell; /// Does paragraph `para` push characters in (Kinsoku Shori Type Push In First or Push Out First, /// with kinsoku on)? fn pushes_in(para: &ParaStyle) -> bool { - para.kinsoku != Kinsoku::None && para.kinsoku_type != KinsokuShoriType::PushOutOnly + !KinsokuRules::of(para).is_none() && para.kinsoku_type != KinsokuShoriType::PushOutOnly +} + +/// May paragraph `para` push one of glyphs `sg` in onto a line: does it push characters in, and +/// hold a character its kinsoku rules keep off a line's start or end? +pub(super) fn may_push_in(para: &ParaStyle, sg: &[SGlyph]) -> bool { + let kinsoku = KinsokuRules::of(para); + pushes_in(para) && sg.iter().any(|g| kinsoku.cannot_start(g.ch) || kinsoku.cannot_end(g.ch)) } /// Paragraphs longer than this (glyphs) are always broken line by line. @@ -55,9 +62,10 @@ fn compose_para( let composer = cx.opts.composer.unwrap_or(para.composer); // A paragraph whose commas or full stops may hang is composed line by line (as the Japanese // single-line composer does). - let may_hang = para.burasagari != Burasagari::None && sg.iter().any(hangs); + let kinsoku = KinsokuRules::of(para); + let may_hang = para.burasagari != Burasagari::None && sg.iter().any(|g| hangs(g, kinsoku)); // So is a paragraph that may push characters kinsoku keeps off a line's ends in onto a line. - let may_push_in = pushes_in(para) && sg.iter().any(|g| no_line_start(g.ch) || no_line_end(g.ch)); + let may_push_in = may_push_in(para, sg); // A tab's width depends on where it falls in its line, which the composer's fixed glyph widths // can't follow: such a paragraph is broken line by line ([`break_line`] measures its tabs). // The tab of a list marker is on the first line, with the marker, and has a fixed width. @@ -100,7 +108,7 @@ fn compose_para( // Only the first line's first word is known here. Later lines are placed as the composed // lines need: each fits its width, so its first word does too. It is measured as the line // loop measures it, with Mojikumi's narrower start and end. - let word = if first { word_width(sg, 0, line_end, para.kinsoku) - start_credit(0) } else { 0.0 }; + let word = if first { word_width(sg, 0, line_end, kinsoku, para.burasagari) - start_credit(0) } else { 0.0 }; let Some((b, x0, x1, _)) = sim.place(m, ind_l, para.right_indent, word) else { break }; let w = x1 - x0 - ind_l - para.right_indent; widths.push(w); @@ -119,7 +127,7 @@ fn compose_para( let width = |k: usize| widths.get(k).copied().unwrap_or(last); // Lines from `uniform_from` on are interchangeable (same width). let uniform_from = widths.iter().rposition(|&w| (w - last).abs() > EPS).map_or(0, |k| k + 1); - let cands = candidates(cx.text, sg, para.hyphenate.then_some(¶.hyphenation), para.kinsoku); + let cands = candidates(cx.text, sg, para.hyphenate.then_some(¶.hyphenation), kinsoku); let justify_last = para.justify == Justify::JustifyAll; let hyphen_limit = usize::try_from(para.hyphenation.hyphen_limit).unwrap_or(usize::MAX); let params = |tolerance| Params { justify_last, ragged, tolerance, uniform_from, hyphen_limit }; @@ -277,8 +285,12 @@ fn prepare_paragraph<'a, 'text>( keep_korean_words(&mut sg); } // Bunri-Kinshi keeps inseparable pairs on one line, while kinsoku is on. - if para.bunri_kinshi && para.kinsoku != Kinsoku::None { - keep_inseparable_pairs(text, &mut sg); + // A custom set keeps its own inseparable sequences instead. + match KinsokuRules::of(para) { + _ if !para.bunri_kinshi => {} + KinsokuRules::Custom(set) => keep_inseparable_sequences(text, &mut sg, &set.inseparable), + rules if !rules.is_none() => keep_inseparable_pairs(text, &mut sg), + _ => {} } // Japanese composition (the paragraph's Mojikumi set): every punctuation mark set half width, // or consecutive punctuation sharing one half-em space… @@ -442,7 +454,8 @@ fn place_flow_line(cx: &mut Ctx<'_>, pen: &mut Pen<'_>, context: &mut PlacementC glyph.lead += half; } // The line's first word, as narrow as the line sets it at both ends. - let word = word_width(sg, *i, line_end, para.kinsoku); + let kinsoku = KinsokuRules::of(para); + let word = word_width(sg, *i, line_end, kinsoku, para.burasagari); // A composed line in a frame whose lines are not all as wide is placed at its own tallest // metrics, as the composer placed it (`shaped::Shaped`): its room is the room across its height. let composed_line = composed.as_ref().and_then(|lines| lines.get(*para_line)).is_some_and(|&(end, _)| end > *i); @@ -502,7 +515,7 @@ fn place_flow_line(cx: &mut Ctx<'_>, pen: &mut Pen<'_>, context: &mut PlacementC // A right-to-left paragraph draws a burasagari mark inside its line // ([`prepare_line_geometry`]): the line ends where it fits with the mark. if *rtl { Burasagari::None } else { para.burasagari }, - para.kinsoku, + kinsoku, ty, *hanging, cx.vertical, @@ -782,7 +795,7 @@ fn prepare_line_geometry(cx: &Ctx<'_>, t: &TextObject, paragraph: &ParagraphData let hang = (paragraph.regions.is_some() && !paragraph.rtl && hyphen.is_none() && trimmed > index + 1) .then(|| sg.get(trimmed - 1)) .flatten() - .filter(|g| hangs(g)) + .filter(|g| hangs(g, KinsokuRules::of(para))) .map(|g| g.adv - end_trim) .filter(|_| match para.burasagari { Burasagari::None => false, diff --git a/crates/text/src/layout/shaped.rs b/crates/text/src/layout/shaped.rs index 61c28b1465..86caea418f 100644 --- a/crates/text/src/layout/shaped.rs +++ b/crates/text/src/layout/shaped.rs @@ -15,7 +15,7 @@ use std::cell::Cell; use std::collections::HashMap; use std::rc::Rc; -use super::breaking::{Metrics, Pen, word_width}; +use super::breaking::{KinsokuRules, Metrics, Pen, word_width}; use super::flow::line_indents; use super::{ParaStyle, SGlyph}; use crate::composer::{Exhausted, Measure}; @@ -278,7 +278,7 @@ fn past_end<'r>(p: &Para<'_>, start: &Start<'r>) -> Option> { /// frame's end ([`past_end`]) when no frame cell has room for it. fn place<'r>(p: &Para<'_>, start: &Start<'r>, m: Metrics) -> Result>, Exhausted> { let (ind_l, ind_r) = line_indents(p.para, start.first, p.mirror); - let word = word_width(p.sg, start.pos, p.line_end, p.para.kinsoku) - (p.start_credit)(start.pos); + let word = word_width(p.sg, start.pos, p.line_end, KinsokuRules::of(p.para), p.para.burasagari) - (p.start_credit)(start.pos); let mut pen = start.pen.clone(); loop { match pen.place(m, ind_l, ind_r, word) { diff --git a/crates/text/src/layout/wrapping_tests.rs b/crates/text/src/layout/wrapping_tests.rs index c7d8ff8a4b..96ccc3e5c7 100644 --- a/crates/text/src/layout/wrapping_tests.rs +++ b/crates/text/src/layout/wrapping_tests.rs @@ -300,12 +300,12 @@ fn word_width_measures_across_a_soft_hyphen_inside_a_no_break_run() { for g in &mut glyphs { g.sx = 0.001; } - let plain = breaking::word_width(&glyphs, 0, &[], Kinsoku::None); + let plain = breaking::word_width(&glyphs, 0, &[], Kinsoku::None, Burasagari::None); assert!(plain < 30.0, "without the mark the word ends at the soft hyphen: {plain}"); for g in &mut glyphs { g.no_break = true; } - let marked = breaking::word_width(&glyphs, 0, &[], Kinsoku::None); + let marked = breaking::word_width(&glyphs, 0, &[], Kinsoku::None, Burasagari::None); assert!((marked - 30.0).abs() < 1e-9, "the marked run is measured whole: {marked}"); } @@ -317,7 +317,7 @@ fn word_width_stops_at_a_forced_line_break() { for g in &mut glyphs { g.no_break = true; } - let marked = breaking::word_width(&glyphs, 0, &[], Kinsoku::None); + let marked = breaking::word_width(&glyphs, 0, &[], Kinsoku::None, Burasagari::None); assert!((marked - 10.0).abs() < 1e-9, "the marked run ends at the forced line break: {marked}"); let mut glyphs = synthetic_glyphs(&[(0, 1, 10.0, 'A'), (1, 2, 0.0, '\u{00ad}'), (3, 3, 5.0, '\u{2028}'), (6, 1, 10.0, 'B')]); @@ -325,12 +325,12 @@ fn word_width_stops_at_a_forced_line_break() { for g in &mut glyphs { g.sx = 0.001; } - let plain = breaking::word_width(&glyphs, 0, &[], Kinsoku::None); + let plain = breaking::word_width(&glyphs, 0, &[], Kinsoku::None, Burasagari::None); assert!((plain - 10.0).abs() < 1e-9, "no hyphen before the forced line break: {plain}"); for g in &mut glyphs { g.no_break = true; } - let marked = breaking::word_width(&glyphs, 0, &[], Kinsoku::None); + let marked = breaking::word_width(&glyphs, 0, &[], Kinsoku::None, Burasagari::None); assert!((marked - 10.0).abs() < 1e-9, "the marked run ends at the forced line break: {marked}"); } @@ -1342,8 +1342,8 @@ fn korean_words_break_at_spaces_unless_line_break_anywhere() { let cands = candidates(text, &off, None, Kinsoku::Hard); assert_eq!(compose(&off, &|_| 50.0, &|_| 0.0, &|_| 0.0, &cands, &[], ¶ms), Some(vec![(4, false), (7, false)])); // The first word is measured whole, as the line loop measures it. - assert_eq!(breaking::word_width(&off, 0, &[], Kinsoku::Hard), 30.0); - assert_eq!(breaking::word_width(&korean(text, true), 0, &[], Kinsoku::Hard), 10.0); + assert_eq!(breaking::word_width(&off, 0, &[], Kinsoku::Hard, Burasagari::None), 30.0); + assert_eq!(breaking::word_width(&korean(text, true), 0, &[], Kinsoku::Hard, Burasagari::None), 10.0); // A word wider than the line still breaks, at the syllable that overflows. assert_eq!(greedy(&korean("가나다라마바", false), 25.0), 2); // A soft return still ends the line. @@ -1449,8 +1449,8 @@ fn bunri_kinshi_keeps_jlreq_pairs_in_both_composers() { }; assert_eq!(greedy(&pairs(text, false), 35.0), 3, "off: the line ends between the dashes"); assert_eq!(greedy(&pairs(text, true), 35.0), 2, "on: both dashes go to the next line"); - assert_eq!(breaking::word_width(&pairs("——あ", true), 0, &[], Kinsoku::Hard), 20.0); - assert_eq!(breaking::word_width(&pairs("——あ", false), 0, &[], Kinsoku::Hard), 10.0); + assert_eq!(breaking::word_width(&pairs("——あ", true), 0, &[], Kinsoku::Hard, Burasagari::None), 20.0); + assert_eq!(breaking::word_width(&pairs("——あ", false), 0, &[], Kinsoku::Hard, Burasagari::None), 10.0); let params = Params { justify_last: false, ragged: true, tolerance: f64::INFINITY, uniform_from: 0, hyphen_limit: 0 }; let on = pairs("あい——う", true); let cands = candidates("あい——う", &on, None, Kinsoku::Hard); @@ -1500,6 +1500,241 @@ fn bunri_kinshi_progresses_with_an_overlong_pair_and_no_break() { assert_eq!(line(text, &pairs(text, true), 0, 46.5, Kinsoku::Hard, PushInFirst), 3); } +/// A custom Kinsoku Shori set (Type › Kinsoku Shori Settings…) with these categories. +fn custom_set(cannot_start: &str, cannot_end: &str, hanging: &str, inseparable: &[&str]) -> vectorcraft_doc::KinsokuSet { + let mut set = vectorcraft_doc::KinsokuSet { + name: "Custom".into(), + cannot_start: cannot_start.chars().collect(), + cannot_end: cannot_end.chars().collect(), + hanging: hanging.chars().collect(), + inseparable: inseparable.iter().map(|s| s.to_string()).collect(), + }; + set.normalize(); + set +} + +/// New Set from Hard or Soft starts with their characters: a custom set made from either breaks +/// every line where it does, in both composers, with every Kinsoku Shori Type and with and without +/// Burasagari, and keeps the same inseparable pairs with Bunri-Kinshi. One made from None is empty. +#[test] +fn a_set_made_from_hard_or_soft_breaks_lines_as_they_do() { + use KinsokuShoriType::{PushInFirst, PushOutFirst, PushOutOnly}; + let texts = ["一二三四五六七八九十一二三四五」六", "あカッー々ャ「か」、。(雅)", "あい——う〳〵え……カッー", "一二三四(五六)ab\u{201c}c\u{201d}。"]; + for base in [Kinsoku::Hard, Kinsoku::Soft] { + let set = crate::shape::kinsoku_set_from(base, "From"); + let custom = breaking::KinsokuRules::Custom(&set); + for text in texts { + let mut built_in = full_width(text); + crate::shape::keep_inseparable_pairs(text, &mut built_in); + let mut own = full_width(text); + crate::shape::keep_inseparable_sequences(text, &mut own, &set.inseparable); + let kept = |g: &[SGlyph]| g.iter().map(|g| g.keeps_next).collect::>(); + assert_eq!(kept(&built_in), kept(&own), "{base:?} {text}"); + let ends = |c: Vec| c.iter().map(|b| b.end).collect::>(); + assert_eq!(ends(candidates(text, &built_in, None, base)), ends(candidates(text, &own, None, custom)), "{base:?} {text}"); + for ty in [PushInFirst, PushOutFirst, PushOutOnly] { + for burasagari in [Burasagari::None, Burasagari::Standard] { + for width in (15..=160).step_by(5).map(f64::from) { + let at = |g: &[SGlyph], k: breaking::KinsokuRules<'_>| { + break_line(text, g, 0, width, &[], 0.0, None, burasagari, k, ty, false, false, &[], None).0 + }; + assert_eq!(at(&built_in, base.into()), at(&own, custom), "{base:?} {ty:?} {burasagari:?} {width} {text}"); + } + } + } + } + } + let empty = crate::shape::kinsoku_set_from(Kinsoku::None, "Empty"); + assert!(empty.cannot_start.is_empty() && empty.cannot_end.is_empty() && empty.hanging.is_empty() && empty.inseparable.is_empty()); +} + +/// A custom set keeps its own Cannot Start Line characters off a line's start and its Cannot End +/// Line characters off its end, and lets every other character start or end one: here 四 never +/// starts a line and 三 never ends one, while 」, which Hard keeps off a line's start, may start +/// one with an empty set. +#[test] +fn a_custom_set_keeps_its_own_characters_off_line_ends() { + use KinsokuShoriType::PushOutOnly; + let end = |text: &str, width: f64, k: breaking::KinsokuRules<'_>| { + break_line(text, &full_width(text), 0, width, &[], 0.0, None, Burasagari::None, k, PushOutOnly, false, false, &[], None).0 + }; + let text = "一二三四五六"; + let start = custom_set("四", "", "", &[]); + let finish = custom_set("", "三", "", &[]); + let empty = custom_set("", "", "", &[]); + assert_eq!(end(text, 35.0, Kinsoku::Hard.into()), 3); + assert_eq!(end(text, 35.0, breaking::KinsokuRules::Custom(&start)), 2, "四 does not start the next line"); + assert_eq!(end(text, 35.0, breaking::KinsokuRules::Custom(&finish)), 2, "三 does not end the line"); + let bracket = "一二三」四"; + assert_eq!(end(bracket, 35.0, Kinsoku::Hard.into()), 2, "Hard keeps 」 off the next line's start"); + assert_eq!(end(bracket, 35.0, breaking::KinsokuRules::Custom(&empty)), 3, "the empty set lets 」 start it"); + // A space after 三 is not drawn at the end of the line, so a break after it would still end + // the line with 三. + let spaced = "一二三 四"; + assert_eq!(end(spaced, 35.0, breaking::KinsokuRules::Custom(&finish)), 2, "三 does not end the line before a space"); + assert_eq!(end(spaced, 35.0, breaking::KinsokuRules::Custom(&empty)), 4); + let ends = candidates(text, &full_width(text), None, breaking::KinsokuRules::Custom(&start)).iter().map(|b| b.end).collect::>(); + assert_eq!(ends, [1, 2, 4, 5]); +} + +/// The least room a word needs ([`breaking::word_width`]) runs past spaces where kinsoku allows no +/// break after them, to the first break [`break_line`] may take: after 「 or a custom set's 三 with +/// spaces after it, and before a 」 that follows a space. Where the break after the space is +/// allowed, the word still ends before the space. +#[test] +fn word_width_runs_past_spaces_kinsoku_does_not_break_after() { + use KinsokuShoriType::PushOutOnly; + let finish = custom_set("", "三", "", &[]); + let empty = custom_set("", "", "", &[]); + for (text, k, word) in [ + ("「 四五", breaking::KinsokuRules::from(Kinsoku::Hard), 30.0), + ("「 四五", Kinsoku::Hard.into(), 40.0), + ("a 」二", Kinsoku::Hard.into(), 30.0), + ("三 四五", breaking::KinsokuRules::Custom(&finish), 30.0), + ("三 四五", breaking::KinsokuRules::Custom(&empty), 10.0), + ("一 二三", Kinsoku::Hard.into(), 10.0), + ] { + let g = full_width(text); + assert_eq!(breaking::word_width(&g, 0, &[], k, Burasagari::None), word, "{text}"); + // In a measure that wide, break_line's first line is that word, drawn without the spaces + // at its end. + let mut end = break_line(text, &g, 0, word, &[], 0.0, None, Burasagari::None, k, PushOutOnly, false, false, &[], None).0; + while end > 0 && g[end - 1].is_space() { + end -= 1; + } + assert_eq!(g[..end].iter().map(|h| h.adv).sum::(), word, "{text}"); + } + // A No Break run of spaces after 「 longer than the glyphs a word is measured over stops the + // measure there. + let long: String = std::iter::once('「').chain(std::iter::repeat_n(' ', 2000)).chain(['四']).collect(); + let mut g = full_width(&long); + for h in g.iter_mut().skip(1) { + h.no_break = true; + } + assert_eq!(breaking::word_width(&g, 0, &[], Kinsoku::Hard, Burasagari::None), 10240.0); +} + +/// Soft and a set made from it choose the same composer: small kana and the prolonged sound mark, +/// which Soft lets start a line, do not send a paragraph that pushes in to the single-line +/// composer with either, while Hard, which keeps them off a line's start, does. +#[test] +fn soft_and_a_set_made_from_it_push_in_the_same_characters() { + use KinsokuShoriType::{PushInFirst, PushOutOnly}; + let glyphs = full_width("あゃいーう"); + let para = |kinsoku: Kinsoku, own: bool, kinsoku_type: KinsokuShoriType| ParaStyle { + kinsoku, + kinsoku_set: own.then(|| Arc::new(crate::shape::kinsoku_set_from(kinsoku, "From"))), + kinsoku_type, + ..ParaStyle::default() + }; + assert!(!flow::may_push_in(¶(Kinsoku::Soft, false, PushInFirst), &glyphs), "built-in Soft"); + assert!(!flow::may_push_in(¶(Kinsoku::Soft, true, PushInFirst), &glyphs), "a set made from Soft"); + assert!(flow::may_push_in(¶(Kinsoku::Hard, false, PushInFirst), &glyphs), "built-in Hard"); + assert!(flow::may_push_in(¶(Kinsoku::Hard, true, PushInFirst), &glyphs), "a set made from Hard"); + assert!(!flow::may_push_in(¶(Kinsoku::Hard, false, PushOutOnly), &glyphs), "Push Out Only"); + let bracket = full_width("あい」う"); + assert!(flow::may_push_in(¶(Kinsoku::Soft, false, PushInFirst), &bracket), "Soft keeps 」 off a line's start"); +} + +/// With Burasagari, a custom set hangs its own Hanging Punctuation and not the comma and full stop +/// the built-in sets hang: 、 hangs outside a full line with Hard and with a set that lists it; with +/// a set that lists only ! it starts the next line, while ! hangs. +#[test] +fn a_custom_set_hangs_its_own_hanging_punctuation() { + use KinsokuShoriType::PushOutOnly; + let end = |text: &str, k: breaking::KinsokuRules<'_>| { + break_line(text, &full_width(text), 0, 30.0, &[], 0.0, None, Burasagari::Standard, k, PushOutOnly, false, false, &[], None).0 + }; + let comma = custom_set("", "", "、", &[]); + let bang = custom_set("", "", "!", &[]); + assert_eq!(end("一二三、四", Kinsoku::Hard.into()), 4); + assert_eq!(end("一二三、四", breaking::KinsokuRules::Custom(&comma)), 4, "、 hangs"); + assert_eq!(end("一二三、四", breaking::KinsokuRules::Custom(&bang)), 3, "、 does not hang"); + assert_eq!(end("一二三!四", breaking::KinsokuRules::Custom(&bang)), 4, "! hangs"); + // In a wider line where ! fits, the line still ends after it. + let text = "一二三!四"; + let wide = |b: Burasagari| { + break_line(text, &full_width(text), 0, 40.0, &[], 0.0, None, b, breaking::KinsokuRules::Custom(&bang), PushOutOnly, false, false, &[], None).0 + }; + assert_eq!(wide(Burasagari::Standard), 4, "! fits and ends the line"); + assert_eq!(wide(Burasagari::None), 3, "without Burasagari ! does not hang, and no line ends after it"); + // The first word, which places a line in a frame of uneven width, ends after ! as the line may. + let word = |b: Burasagari| breaking::word_width(&full_width("AB!CD"), 0, &[], breaking::KinsokuRules::Custom(&bang), b); + assert_eq!(word(Burasagari::Standard), 30.0); + assert_eq!(word(Burasagari::None), 50.0); + // A hanging character that starts an inseparable sequence kept with Bunri-Kinshi does not hang + // the rest of the sequence with it: the sequence goes to the next line. + let joined = custom_set("", "", "!", &["!あ"]); + let text = "一二三!あい"; + let mut g = full_width(text); + crate::shape::keep_inseparable_sequences(text, &mut g, &joined.inseparable); + let rules = breaking::KinsokuRules::Custom(&joined); + assert_eq!(break_line(text, &g, 0, 30.0, &[], 0.0, None, Burasagari::Standard, rules, PushOutOnly, false, false, &[], None).0, 3); + // A hanging character drawn with two glyphs does not hang: the line's geometry hangs only one + // glyph, so the other would stay past the measure. 三 goes to the next line with it. + let text = "一二三、四"; + let mut g = full_width(text); + g[3].adv = 5.0; + g.insert(3, g[3].clone()); + assert_eq!(break_line(text, &g, 0, 30.0, &[], 0.0, None, Burasagari::Standard, Kinsoku::Hard, PushOutOnly, false, false, &[], None).0, 2); + let g = full_width("、!"); + assert!(breaking::hangs(&g[1], breaking::KinsokuRules::Custom(&bang)) && !breaking::hangs(&g[0], breaking::KinsokuRules::Custom(&bang))); +} + +/// Bunri-Kinshi with a custom set: a line never breaks inside one of its inseparable sequences, +/// which may be longer than a pair and may overlap, and the built-in pairs are kept only when the +/// set lists them. +#[test] +fn a_custom_set_keeps_its_inseparable_sequences_on_one_line() { + let marked = |text: &str, sequences: &[&str]| { + let mut g = full_width(text); + crate::shape::keep_inseparable_sequences(text, &mut g, &sequences.iter().map(|s| s.to_string()).collect::>()); + g.iter().map(|g| g.keeps_next).collect::>() + }; + assert_eq!(marked("かあいうえ", &["あいう"]), [false, true, true, false, false]); + assert_eq!(marked("あいうえお", &["あい", "いう"]), [true, true, false, false, false], "overlapping sequences chain"); + assert_eq!(marked("あ——い", &["あい"]), [false; 4], "the built-in pairs are not kept by a set without them"); + assert_eq!(marked("", &["あい"]), Vec::::new()); + assert_eq!(marked("あいうえお", &["あい", "あいうえ"]), [true, true, true, false, false], "the longer of two sequences that start alike"); + assert_eq!(marked("あいう", &["あい", "あいか"]), [true, false, false], "the shorter where only it is found"); + // A set at the category limit whose sequences all start with one character. + let many: Vec = (0..2047u32).filter_map(|k| char::from_u32(0x4E00 + k)).map(|c| ['あ', c].iter().collect()).collect(); + let many: Vec<&str> = many.iter().map(String::as_str).chain(["あい"]).collect(); + assert_eq!(marked("あいあ一う", &many), [true, false, true, false, false]); + let text = "かあいうえ"; + let set = custom_set("", "", "", &["あいう"]); + let mut g = full_width(text); + crate::shape::keep_inseparable_sequences(text, &mut g, &set.inseparable); + let ends = candidates(text, &g, None, breaking::KinsokuRules::Custom(&set)).iter().map(|b| b.end).collect::>(); + assert_eq!(ends, [1, 4]); +} + +/// Bunri-Kinshi with a custom set compares at most 15 texts with the set's sequences for each +/// character of a paragraph, however many sequences start with one character: 2048 sequences of +/// 2 characters cost one lookup at each place, 256 of 16 characters cost 15, and a sequence longer +/// than a set holds is not looked for. +#[test] +fn inseparable_sequences_cost_a_bounded_number_of_lookups() { + let lookups = |text: &str, sequences: &[String]| { + let mut g = full_width(text); + crate::shape::SEQUENCE_LOOKUPS.with(|n| n.set(0)); + crate::shape::keep_inseparable_sequences(text, &mut g, sequences); + (crate::shape::SEQUENCE_LOOKUPS.with(std::cell::Cell::get), g.iter().filter(|g| g.keeps_next).count()) + }; + // A place n characters from the paragraph's end looks up min(n, 16) - 1 texts. + let cost = |chars: usize, longest: usize| (1..=chars).map(|n| n.min(longest) - 1).sum::(); + let text = "あ".repeat(1000); + let pairs: Vec = (0..2048u32).filter_map(|k| char::from_u32(0x4E00 + k)).map(|c| ['あ', c].iter().collect()).collect(); + assert_eq!(lookups(&text, &pairs), (999, 0)); + let long: Vec = (0..256u32).filter_map(|k| char::from_u32(0x4E00 + k)).map(|c| format!("{}{c}", "あ".repeat(15))).collect(); + assert_eq!(lookups(&text, &long), (cost(1000, 16), 0)); + assert!(cost(1000, 16) <= 1000 * 15); + let mut found = long.clone(); + found.push("あ".repeat(16)); + assert_eq!(lookups(&"あ".repeat(16), &found), (cost(16, 16), 15)); + assert_eq!(lookups(&"あ".repeat(17), &["あ".repeat(17)]), (cost(17, 16), 0), "17 characters are never found"); +} + /// Justification adds no gap between two glyphs of one warichu block, whichever of them is drawn /// first: right to left, the block's first glyph (the one that starts it) is drawn after the /// others. Between glyphs of two blocks, the gap stays. diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 6d99928b73..7b70b9c5a2 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -43,9 +43,10 @@ pub use features::{ }; pub use fontdb::{ CompositeCoverage, FALLBACK_FAMILY, FontClass, FontDb, FontFace, FontLikeness, FontMatch, FontTraits, GENERIC_FAMILIES, GlyphAlternate, - GlyphCategory, GlyphCategoryKind, GlyphOrigin, IcfMargins, JoiningPosition, LentCompositeFonts, PlatformFontFiles, RECENTLY_ADDED_WITHIN, - RecentlyAdded, StylisticSet, Substitution, SubstitutionKind, WantedFont, WantedFonts, app_font_dir, is_font_file, is_generic_family, is_suitcase, - set_app_font_dir, set_platform_font_files, set_user_font_dirs, set_user_font_dirs_confined, style_weight, system_font_dirs, user_font_dirs, + GlyphCategory, GlyphCategoryKind, GlyphOrigin, IcfMargins, JoiningPosition, LentCompositeFonts, OutlineFormat, PlatformFontFiles, + RECENTLY_ADDED_WITHIN, RecentlyAdded, StylisticSet, Substitution, SubstitutionKind, WantedFont, WantedFonts, app_font_dir, is_font_file, + is_generic_family, is_suitcase, set_app_font_dir, set_platform_font_files, set_user_font_dirs, set_user_font_dirs_confined, style_weight, + system_font_dirs, user_font_dirs, }; pub use hyphen::{hyphenation_exceptions, set_hyphenation_exceptions}; pub use layout::{envelope_ink, layout_inputs, register_envelope_ink}; @@ -55,7 +56,7 @@ pub use svg_glyph::{SvgGlyphReader, set_svg_glyph_reader}; pub use kept::{KeptLayoutsFrame, LayoutStamp, keep_layout, take_kept_layout}; use kurbo::{Affine, BezPath, Point, Rect, Shape, Vec2}; pub use layout::{decorations, drawn, fit_first_line, fit_source_lines, layout, layout_with, scaled}; -pub use shape::{aki_space, inseparable, line_start_space, repeat_base, spacing_scale}; +pub use shape::{aki_space, inseparable, kinsoku_set_from, line_start_space, repeat_base, spacing_scale}; pub use vectorcraft_doc::TextObject; pub use vectorcraft_doc::{AreaFit, FirstBaseline, TextFlow, VerticalAlign}; diff --git a/crates/text/src/shape.rs b/crates/text/src/shape.rs index 795e2c375b..9dfff9a0d6 100644 --- a/crates/text/src/shape.rs +++ b/crates/text/src/shape.rs @@ -438,6 +438,89 @@ pub(crate) fn keep_inseparable_pairs(text: &str, sg: &mut [SGlyph]) { } } +#[cfg(test)] +thread_local! { + /// How many texts [`keep_inseparable_sequences`] has compared with a set's sequences on this + /// thread. + pub(crate) static SEQUENCE_LOOKUPS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Bunri-Kinshi with a custom Kinsoku Shori set: as [`keep_inseparable_pairs`], for the set's +/// inseparable `sequences` (each [`vectorcraft_doc::text::KINSOKU_SEQUENCE`] characters): a line +/// never breaks between two characters of one occurrence of a sequence in the paragraph's text. +/// Occurrences may overlap. The text is read once; at each place that starts a sequence, only the +/// text of each sequence length (at most [`vectorcraft_doc::text::KINSOKU_SEQUENCE`]'s end) is +/// looked up, however many sequences share a first character: at most 15 lookups for each +/// character of the paragraph. A sequence longer than a set can hold is never found. +pub(crate) fn keep_inseparable_sequences(text: &str, sg: &mut [SGlyph], sequences: &[String]) { + let (Some(first), Some(last)) = (sg.iter().map(|g| g.byte).min(), sg.iter().map(|g| g.byte + g.len).max()) else { return }; + let Some(longest) = sequences.iter().map(|s| s.chars().count()).max() else { return }; + let longest = longest.min(*vectorcraft_doc::text::KINSOKU_SEQUENCE.end()); + let known: std::collections::HashSet<&str> = sequences.iter().map(String::as_str).collect(); + let starts: std::collections::HashSet = sequences.iter().filter_map(|s| s.chars().next()).collect(); + let Some(para) = text.get(first..last) else { return }; + // The bytes (of `text`) where a character inside an occurrence starts, after its first. + let mut inside = std::collections::HashSet::new(); + for (at, c) in para.char_indices() { + if !starts.contains(&c) { + continue; + } + let rest = ¶[at..]; + // Every sequence found here is the start of the longest one found here, so that one marks + // the characters of them all. + let mut found = None; + for end in rest.char_indices().take(longest).map(|(k, ch)| k + ch.len_utf8()).skip(1) { + #[cfg(test)] + SEQUENCE_LOOKUPS.with(|n| n.set(n.get() + 1)); + if known.contains(&rest[..end]) { + found = Some(end); + } + } + if let Some(end) = found { + inside.extend(rest[..end].char_indices().skip(1).map(|(k, _)| first + at + k)); + } + } + if inside.is_empty() { + return; + } + for k in 1..sg.len() { + let (a, b) = (&sg[k - 1], &sg[k]); + if a.byte == b.byte || a.inline.is_some() || b.inline.is_some() || a.byte + a.len != b.byte { + continue; + } + if inside.contains(&b.byte) { + sg[k - 1].keeps_next = true; + } + } +} + +/// The characters, hanging punctuation and inseparable sequences of a built-in Kinsoku Set +/// (`base`), as a custom set named `name` holds them: New Set's starting point. A set made from +/// Hard or Soft breaks lines as that set does; one made from None is empty. +pub fn kinsoku_set_from(base: vectorcraft_doc::Kinsoku, name: &str) -> vectorcraft_doc::KinsokuSet { + use vectorcraft_doc::Kinsoku; + let mut set = vectorcraft_doc::KinsokuSet { name: name.to_string(), ..Default::default() }; + if base == Kinsoku::None { + return set; + } + // Every character the built-in sets name is in the Basic Multilingual Plane. + for c in (0..=0xFFFF_u32).filter_map(char::from_u32) { + if no_line_start(c) && !(base == Kinsoku::Soft && soft_line_start(c)) { + set.cannot_start.push(c); + } + if no_line_end(c) { + set.cannot_end.push(c); + } + if crate::layout::is_hanging_punctuation(c) { + set.hanging.push(c); + } + } + let pairs = [('\u{2014}', '\u{2014}'), ('\u{2026}', '\u{2026}'), ('\u{2025}', '\u{2025}'), ('\u{3033}', '\u{3035}'), ('\u{3034}', '\u{3035}')]; + set.inseparable = pairs.iter().filter(|&&(a, b)| inseparable(a, b)).map(|&(a, b)| [a, b].iter().collect()).collect(); + set.normalize(); + set +} + /// Is `a` followed by `b` an inseparable pair that Bunri-Kinshi keeps on one line? VectorCraft's /// set is the pairs W3C JLREQ lists for its class cl-08 (https://www.w3.org/TR/jlreq/#cl-08): two /// em dashes, two horizontal ellipses, two two-dot leaders, and the upper half of a vertical kana diff --git a/crates/three-d/src/lib.rs b/crates/three-d/src/lib.rs index c6b00ed851..c99a437efd 100644 --- a/crates/three-d/src/lib.rs +++ b/crates/three-d/src/lib.rs @@ -12,8 +12,9 @@ pub mod fold; 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, extrude_side_size, inflate, inflate_each, inflate_together, plane, plane_face_map, plane_mesh_face, + Bevel, BevelShape, DepthPlane, Extrude, FaceMap, Facet, Inflate, MapCell, MeshFace, PlanarFace, SolidSurface, SurfaceKind, TOO_COMPLEX_SOLID, + View, extrude, extrude_face_map, extrude_mesh_face, extrude_side_size, extrude_surfaces, inflate, inflate_each, inflate_together, plane, + plane_face_map, plane_mesh_face, }; pub use visibility::{VisibleFace, visible_faces}; mod shading; @@ -22,7 +23,7 @@ mod lights; pub use lights::{Light, Lights, MAX_LIGHTS}; mod caps; mod mesh; -pub use mesh::{Mesh, MeshedSolid, extrude_mesh, extrude_meshed, inflate_meshed, inflate_meshes, plane_mesh, revolve_mesh}; +pub use mesh::{Mesh, MeshedSolid, extrude_mesh, extrude_meshed, inflate_meshed, inflate_meshes, plane_mesh, revolve_mesh, revolve_mesh_surface}; mod shadow; pub use shadow::{ MAX_SHADOW_FACES, Shadow, ShadowCaster, ShadowPlane, ShadowPosition, SolidFaces, TOO_COMPLEX_SHADOW, extrude_shadowed, inflate_shadowed, @@ -478,6 +479,15 @@ fn surface_span(sweep: f64, edge: Edge) -> f64 { } } +/// Where the four corners of the quad that the profile's edge from `a` to `b` sweeps in one step +/// about `axis` lie on the side surface ([`SurfaceCell`]), in the quad's order (`a`, `b`, then `b` +/// and `a` one step on): y is `along`, the surface y of each end of the edge, and x is the step's +/// surface angle at each end, `angle`, times the corner's own distance from the axis. +fn surface_corners(a: Point, b: Point, axis: f64, [va, vb]: [f64; 2], [t0, t1]: [f64; 2]) -> [Point; 4] { + let (ra, rb) = ((a.x - axis).abs(), (b.x - axis).abs()); + [Point::new(t0 * ra, va), Point::new(t0 * rb, vb), Point::new(t1 * rb, vb), Point::new(t1 * ra, va)] +} + /// The surface y ([`SurfaceCell`]) of each end of each piece of a contour's profile `profile` /// about `axis`: the length along the profile from its middle, counted from just after the /// pieces that lie on the axis (which sweep no surface and add no length) on a closed contour. @@ -980,7 +990,22 @@ fn revolve_face_limit(o: Revolve) -> usize { /// each turned out of the region `rule` fills. fn revolve_faces(path: &PathData, rule: FillRule, bounds: Rect, options: Revolve, mesh: Option<&mut Vec>) -> Result, String> { let draw = mesh.is_none(); - revolve_sweep(path, rule, bounds, options, draw, mesh).map(|(faces, _)| faces) + revolve_sweep(path, rule, bounds, options, draw, mesh, None).map(|(faces, _)| faces) +} + +/// The faces of Revolve's surface before projection, kept in `faces` as [`revolve_faces`] keeps +/// them, and in `surface` where the corners of each face of the side lie on the side surface +/// ([`SurfaceCell`]), as the drawn faces place them. Only a sweep with [`Revolve::map_surface`] lays +/// out its side; only the longest contour of a compound profile has one. +pub(crate) fn revolve_surface_faces( + path: &PathData, + rule: FillRule, + bounds: Rect, + options: Revolve, + faces: &mut Vec, + surface: &mut SurfaceQuads, +) -> Result<(), String> { + revolve_sweep(path, rule, bounds, options, false, Some(faces), Some(surface)).map(|_| ()) } #[cfg(test)] @@ -1037,11 +1062,19 @@ fn cap_outward(profile: &[Point], index: usize, center_y: f64) -> Option<(Point, /// Keep for a mesh the faces of one contour's profile `s`, which runs round the region it sweeps as /// `turn` says (its holes' walls turned the other way): a quad for each edge at each step, then for /// each end in `caps` (0 the first, 1 the last) the disk, or for a sweep of less than a full turn -/// the sector with its center on the axis. `keep` keeps one face with its outward normal; its -/// error, or an edge with invalid coordinates, stops the faces. -fn keep_profile(at: &Sweeping, s: &Swept, turn: f64, caps: &[usize], mut keep: impl FnMut(Vec, V3) -> Result<(), String>) -> Result<(), String> { +/// the sector with its center on the axis. `keep` keeps one face with its outward normal and, for a +/// quad of the side when `surface` lays it out, where each of its corners lies on the side surface +/// ([`SurfaceCell`]); its error, or an edge with invalid coordinates, stops the faces. +fn keep_profile( + at: &Sweeping, + s: &Swept, + turn: f64, + caps: &[usize], + surface: Option>, + mut keep: impl FnMut(Vec, V3, Option<[Point; 4]>) -> Result<(), String>, +) -> Result<(), String> { let (o, steps) = (at.o, at.steps); - for (pair, hole) in s.points.windows(2).zip(&s.holes) { + for (i, (pair, hole)) in s.points.windows(2).zip(&s.holes).enumerate() { let [a, b] = pair else { continue }; let turn = if *hole { -turn } else { turn }; if ![a.x, a.y, b.x, b.y].iter().all(|v| v.is_finite() && v.abs() <= 1e8) { @@ -1053,7 +1086,9 @@ fn keep_profile(at: &Sweeping, s: &Swept, turn: f64, caps: &[usize], mut keep: i // swept to the middle of the step. let (dr, dy) = ((b.x - a.x) * turn, (b.y - a.y) * turn); let (sin, cos) = (at.sweep * (j as f64 + 0.5) / steps as f64).sin_cos(); - keep(vec![v0, v1, v2, v3], o.rotate(V3(dy * cos, -dr, dy * sin)))?; + // The corners on the side surface, as the drawn faces place them. + let uv = surface.map(|(along, angle)| surface_corners(*a, *b, at.axis, along.get(i).copied().unwrap_or_default(), angle(j))); + keep(vec![v0, v1, v2, v3], o.rotate(V3(dy * cos, -dr, dy * sin)), uv)?; } } for &index in caps { @@ -1064,11 +1099,19 @@ fn keep_profile(at: &Sweeping, s: &Swept, turn: f64, caps: &[usize], mut keep: i } else { cap.insert(0, o.rotate(V3(0.0, end.y - at.center_y, 0.0))); } - keep(cap, o.rotate(V3(0.0, outward, 0.0)))?; + keep(cap, o.rotate(V3(0.0, outward, 0.0)), None)?; } Ok(()) } +/// How a contour's side lies on the side surface ([`SurfaceCell`]): the surface y of each end of +/// each piece of its profile ([`along_profile`]) and the surface angle at each end of a step. +type SurfaceLayout<'a> = (&'a [[f64; 2]], &'a dyn Fn(usize) -> [f64; 2]); + +/// Where the corners of the faces of Revolve's mesh lie on its side surface: the index of a face +/// among the faces kept, and the surface point of each of its four corners, in order. +pub(crate) type SurfaceQuads = Vec<(usize, [Point; 4])>; + /// Twice the signed area of the polygon `ring`. fn ring_area(ring: &[Point]) -> f64 { ring.iter().zip(ring.iter().cycle().skip(1)).take(ring.len()).map(|(p, q)| p.x * q.y - q.x * p.y).sum() @@ -1325,7 +1368,9 @@ fn lose_mesh(draw: bool, mesh: &mut Option<&mut Vec>, lost: &mut O /// [`revolve`]'s faces when `draw`, and with `mesh` the surface's faces before projection kept /// there from the same sweep, each turned out of the region `rule` fills. While faces are drawn, an /// error keeping faces for the mesh stops only the mesh: the error comes back beside the faces -/// drawn, and `mesh` keeps no more faces. Without `draw` that error is the result. +/// drawn, and `mesh` keeps no more faces. Without `draw` that error is the result. With `surface`, +/// the faces kept of the side of the contour that carries the graphics are listed there with their +/// corners on the side surface ([`revolve_surface_faces`]). fn revolve_sweep( path: &PathData, rule: FillRule, @@ -1333,6 +1378,7 @@ fn revolve_sweep( options: Revolve, draw: bool, mut mesh: Option<&mut Vec>, + mut surface: Option<&mut SurfaceQuads>, ) -> Result<(Vec, Option), String> { #[cfg(test)] REVOLVED.with(|n| n.set(n.get() + 1)); @@ -1536,7 +1582,15 @@ fn revolve_sweep( let turn = prepare(&mut kept); cuts.add(&kept, sp.closed, true); let caps: Vec = rings.iter().enumerate().filter_map(|(i, r)| r.as_ref().map(|_| i)).collect(); - let kept = keep_profile(&at, &kept, turn, &caps, |face, normal| keep(m, face, normal)); + let along = (surface.is_some() && surface_contour == Some(contour)).then(|| along_profile(&kept.points, axis, sp.closed)); + let layout = along.as_deref().map(|along| (along, &surface_angle as &dyn Fn(usize) -> [f64; 2])); + let kept = keep_profile(&at, &kept, turn, &caps, layout, |face, normal, uv| { + keep(m, face, normal)?; + if let (Some(uv), Some(s)) = (uv, surface.as_deref_mut()) { + s.push((m.len() - 1, uv)); + } + Ok(()) + }); if let Err(e) = kept { lose_mesh(draw, &mut mesh, &mut lost, e)?; } @@ -1551,7 +1605,7 @@ fn revolve_sweep( for (i, ((pair, [ta, tb]), hole)) in profile.windows(2).zip(drawn.tangents.iter().copied()).zip(drawn.holes.iter().copied()).enumerate() { let [a, b] = pair else { continue }; let turn = if hole { -turn } else { turn }; - let [va, vb] = along.get(i).copied().unwrap_or_default(); + let ends = along.get(i).copied().unwrap_or_default(); if ![a.x, a.y, b.x, b.y].iter().all(|v| v.is_finite() && v.abs() <= 1e8) { return Err("Revolve profile contains invalid coordinates".into()); } @@ -1561,10 +1615,7 @@ fn revolve_sweep( let last = (i + 2 == profile.len()).then(|| rings.last().and_then(Option::as_ref).and_then(|r| r.arcs.get(j))).flatten(); // Where the corners lie on the unrolled side surface, and whether the face shows // its outside: the edge's outward normal swept to the middle of the step. - // x is the angle times the corner's own distance from the axis. - let [t0, t1] = surface_angle(j); - let (ra, rb) = ((a.x - axis).abs(), (b.x - axis).abs()); - let corners = [Point::new(t0 * ra, va), Point::new(t0 * rb, vb), Point::new(t1 * rb, vb), Point::new(t1 * ra, va)]; + let corners = surface_corners(*a, *b, axis, ends, surface_angle(j)); let on_surface = surface_contour == Some(contour); let outward = { let (dr, dy) = ((b.x - a.x) * turn, (b.y - a.y) * turn); diff --git a/crates/three-d/src/mesh.rs b/crates/three-d/src/mesh.rs index 14284cb1bf..5262bb6131 100644 --- a/crates/three-d/src/mesh.rs +++ b/crates/three-d/src/mesh.rs @@ -8,7 +8,7 @@ //! turned plane) are cut into triangles: each hole is joined to its outline by a bridge, then the //! outline is cut by ear clipping. -use vectorcraft_geom::{FillRule, PathData, Rect}; +use vectorcraft_geom::{FillRule, PathData, Point, Rect}; use crate::solid::{Face3, Keep, extrude_faces, inflate_faces, plane_faces}; use crate::{Extrude, Facet, Inflate, Revolve, V3, View}; @@ -127,6 +127,21 @@ pub fn revolve_mesh(path: &PathData, rule: FillRule, bounds: Rect, options: Revo mesh(&faces) } +/// [`revolve_mesh`], with where each corner of each triangle of the side lies on the side surface +/// unrolled ([`crate::SurfaceCell`]), as the effect places a graphic mapped onto the side: one +/// entry for each triangle, in order, `None` for a triangle of an end cap, of a cut side or of a +/// contour other than the one that carries the graphics. Only a sweep with +/// [`Revolve::map_surface`] lays out its side; without it every entry is `None`. +pub fn revolve_mesh_surface(path: &PathData, rule: FillRule, bounds: Rect, options: Revolve) -> Result { + let (mut faces, mut surface) = (vec![], vec![]); + crate::revolve_surface_faces(path, rule, bounds, options, &mut faces, &mut surface)?; + mesh_on(&faces, Some(&surface)) +} + +/// A mesh with, for each of its triangles, the surface point of each corner, or `None` +/// ([`revolve_mesh_surface`]). +pub type SurfaceMesh = (Mesh, Vec>); + /// The area-weighted normal of `contours` (Newell's method). pub(crate) fn newell(contours: &[Vec]) -> V3 { let mut n = V3::default(); @@ -147,9 +162,28 @@ fn up(v: V3) -> [f64; 3] { /// `faces` (view space) as one mesh, each cut into triangles turned to its normal, which is written /// at unit length whatever length it is given (a face given no normal takes its corners' own). fn mesh(faces: &[Face3]) -> Result { + mesh_on(faces, None).map(|(mesh, _)| mesh) +} + +/// [`mesh`], with for each triangle where its corners lie on a surface: `surface` lists faces by +/// their index in `faces` (in increasing order) with a surface point for each corner of the face's +/// one contour, and a triangle of such a face takes its corners' points. `None` for a triangle of +/// any other face. Without `surface` the list is empty. +fn mesh_on(faces: &[Face3], surface: Option<&[(usize, [Point; 4])]>) -> Result { + let track = surface.is_some(); + let surface = surface.unwrap_or_default(); let mut out = Mesh::default(); + let mut on = vec![]; let mut work = 0usize; - for (contours, normal) in faces { + let mut cells = surface.iter().peekable(); + for (k, (contours, normal)) in faces.iter().enumerate() { + while cells.next_if(|(i, _)| *i < k).is_some() {} + let cell = cells.next_if(|(i, _)| *i == k).map(|(_, uv)| uv); + // The surface point of a corner of a triangle: the point of the face's corner it is. + let point = |v: V3| { + let corners = contours.first()?; + corners.iter().zip(cell?).find(|(c, _)| c.0 == v.0 && c.1 == v.1 && c.2 == v.2).map(|(_, p)| *p) + }; let geometric = newell(contours); let given = normal.unit(); let n = if given.dot(given) > 0.5 { given } else { geometric.unit() }; @@ -157,20 +191,36 @@ fn mesh(faces: &[Face3]) -> Result { continue; } let [nx, ny, nz] = up(n); - for [a, b, c] in triangulate(contours, geometric, &mut work)? { + // A face on the surface is cut along its diagonal from corner 0 to corner 2, as the canvas + // cuts it to place the graphics: the surface's layout of a quad whose ends lie at different + // distances from the axis is not one affine map, so the other diagonal would move them. + let quad = match contours.as_slice() { + [only] if cell.is_some() => <[V3; 4]>::try_from(only.as_slice()).ok(), + _ => None, + }; + let triangles = match quad { + Some([v0, v1, v2, v3]) => vec![[v0, v1, v2], [v0, v2, v3]], + None => triangulate(contours, geometric, &mut work)?, + }; + for [a, b, c] in triangles { let (pa, pb, pc) = (up(a), up(b), up(c)); let cross = V3(pb[0] - pa[0], pb[1] - pa[1], pb[2] - pa[2]).cross(V3(pc[0] - pa[0], pc[1] - pa[1], pc[2] - pa[2])); if cross.dot(cross) < 1e-24 { continue; } - let (pb, pc) = if cross.dot(V3(nx, ny, nz)) < 0.0 { (pc, pb) } else { (pb, pc) }; + let turned = cross.dot(V3(nx, ny, nz)) < 0.0; + let (pb, pc) = if turned { (pc, pb) } else { (pb, pc) }; + let (b, c) = if turned { (c, b) } else { (b, c) }; let base = u32::try_from(out.positions.len()).map_err(|_| "The 3D object is too complex to export".to_string())?; out.positions.extend([pa, pb, pc]); out.normals.extend([[nx, ny, nz]; 3]); out.triangles.push([base, base + 1, base + 2]); + if track { + on.push(point(a).zip(point(b)).zip(point(c)).map(|((a, b), c)| [a, b, c])); + } } } - Ok(out) + Ok((out, on)) } /// A corner of a face: its position on the plane the face is cut in, and in 3D. diff --git a/crates/three-d/src/mesh/tests.rs b/crates/three-d/src/mesh/tests.rs index 8b2ec0ae75..baf5266c76 100644 --- a/crates/three-d/src/mesh/tests.rs +++ b/crates/three-d/src/mesh/tests.rs @@ -255,6 +255,116 @@ fn a_partial_revolve_caps_its_ends_with_sectors_and_closes_its_cut_sides() { assert!(!closed(&hollow)); } +/// A vertical line 40 pt from the axis, from y 10 to 90: an open cylinder of radius 40 about the +/// axis at x 0, its middle height 50. +fn tube() -> (PathData, Rect) { + let mut b = BezPath::new(); + b.move_to((40.0, 10.0)); + b.line_to((40.0, 90.0)); + (PathData::from_bezpath(&b), Rect::new(0.0, 10.0, 40.0, 90.0)) +} + +#[test] +fn a_revolved_sides_corners_lie_where_the_canvas_places_the_unrolled_side() { + let (p, r) = tube(); + let o = Revolve { map_surface: true, ..Revolve::default() }; + let (m, on) = revolve_mesh_surface(&p, FillRule::NonZero, r, o).unwrap(); + assert_eq!(on.len(), m.triangles.len()); + assert_eq!(m.triangles.len(), revolve_mesh(&p, FillRule::NonZero, r, o).unwrap().triangles.len()); + let step = 40.0 * std::f64::consts::TAU / 64.0; + let (mut side, mut caps) = (0, 0); + for (t, points) in m.triangles.iter().zip(&on) { + let c = corners(&m, *t); + let Some(points) = points else { + // The end caps: flat at the top and bottom of the tube. + assert!(c.iter().all(|q| (q[1].abs() - 40.0).abs() < 1e-9), "{c:?}"); + caps += 1; + continue; + }; + side += 1; + for (q, uv) in c.iter().zip(points) { + // y runs down the profile from its middle (the mesh is y up), and x around the axis is + // the angle from the front (90°, toward the viewer), increasing to the viewer's right, + // times the radius. + assert!((uv.y + q[1]).abs() < 1e-9, "{q:?} {uv:?}"); + let turned = std::f64::consts::FRAC_PI_2 - q[2].atan2(q[0]); + let around = (turned + std::f64::consts::PI).rem_euclid(std::f64::consts::TAU) - std::f64::consts::PI; + let seam = (uv.x.abs() - 40.0 * std::f64::consts::PI).abs() < step + 1e-6; + assert!((uv.x - 40.0 * around).abs() < 1e-6 || seam, "{q:?} {uv:?}"); + } + // No triangle reaches across the cut at the back: each spans one step around the axis. + let (lo, hi) = points.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), p| (lo.min(p.x), hi.max(p.x))); + assert!(hi - lo < step + 1e-6, "{points:?}"); + } + assert_eq!((side, caps > 0), (2 * 64, true)); + // The cut is at the back: the side runs half a turn each way from the front. + let xs = on.iter().flatten().flatten().map(|p| p.x); + let (lo, hi) = xs.fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), x| (lo.min(x), hi.max(x))); + assert!((lo + 40.0 * std::f64::consts::PI).abs() < 1e-6 && (hi - 40.0 * std::f64::consts::PI).abs() < 1e-6, "{lo} {hi}"); +} + +#[test] +fn a_revolved_sides_layout_matches_its_drawn_faces_at_every_turn() { + let (p, r) = tube(); + for o in [ + Revolve { map_surface: true, angle: 90.0, ..Revolve::default() }, + Revolve { map_surface: true, angle: 250.0, offset: 15.0, edge: Edge::Right, rotation_x: -20.0, rotation_y: 35.0, ..Revolve::default() }, + ] { + let (m, on) = revolve_mesh_surface(&p, FillRule::NonZero, r, o).unwrap(); + // The drawn faces' surface points, which the canvas places the graphics by. + let drawn: Vec = crate::revolve(&p, r, o).unwrap().iter().filter_map(|f| f.surface.as_ref()).flat_map(|c| c.uv.clone()).collect(); + let near = |q: Point| drawn.iter().any(|d| d.distance(q) < 1e-6); + let points: Vec = on.iter().flatten().flatten().copied().collect(); + assert!(!points.is_empty() && points.iter().all(|q| near(*q)), "{o:?}"); + assert!(drawn.iter().all(|d| points.iter().any(|q| q.distance(*d) < 1e-6)), "{o:?}"); + // The end sectors and the two cut sides carry no surface points. + assert!(on.iter().any(Option::is_none) && on.len() == m.triangles.len()); + } + // Without the layout, no triangle carries one. + let (_, on) = revolve_mesh_surface(&p, FillRule::NonZero, r, Revolve::default()).unwrap(); + assert!(on.iter().all(Option::is_none)); +} + +#[test] +fn a_tapered_sides_triangles_are_the_drawn_faces_triangles() { + // A cone's side: each face's ends lie at different distances from the axis, so its layout on + // the surface is not one affine map, and each triangle must take the corners the canvas cuts + // the face into. + let mut b = BezPath::new(); + b.move_to((10.0, 10.0)); + b.line_to((40.0, 90.0)); + let p = PathData::from_bezpath(&b); + let r = Rect::new(0.0, 10.0, 40.0, 90.0); + let o = Revolve { map_surface: true, ..Revolve::default() }; + let key = |t: &[Point]| { + let mut k: Vec<(i64, i64)> = t.iter().map(|q| ((q.x * 1e6).round() as i64, (q.y * 1e6).round() as i64)).collect(); + k.sort_unstable(); + k + }; + let drawn: Vec<_> = crate::revolve(&p, r, o).unwrap().iter().filter_map(|f| f.surface.as_ref()).map(|c| key(&c.uv)).collect(); + assert!(drawn.iter().all(|k| k.len() == 3), "the canvas draws the smooth side in triangles"); + let (_, on) = revolve_mesh_surface(&p, FillRule::NonZero, r, o).unwrap(); + let side: Vec<_> = on.iter().flatten().collect(); + assert_eq!(side.len(), drawn.len()); + assert!(side.iter().all(|t| drawn.contains(&key(t.as_slice())))); +} + +#[test] +fn only_the_longest_contour_of_a_revolved_profile_lies_on_the_side_surface() { + let mut b = BezPath::new(); + b.move_to((40.0, 10.0)); + b.line_to((40.0, 90.0)); + b.move_to((20.0, 30.0)); + b.line_to((20.0, 50.0)); + let p = PathData::from_bezpath(&b); + let r = Rect::new(0.0, 10.0, 40.0, 90.0); + let (m, on) = revolve_mesh_surface(&p, FillRule::NonZero, r, Revolve { map_surface: true, cap_ends: false, ..Revolve::default() }).unwrap(); + for (t, points) in m.triangles.iter().zip(&on) { + let radius = corners(&m, *t).iter().map(|q| q[0].hypot(q[2])).fold(0.0f64, f64::max); + assert_eq!(points.is_some(), radius > 30.0, "{radius}"); + } +} + #[test] fn a_revolved_surface_has_unit_normals_facing_out_whatever_its_length_and_direction() { // A wall 100 pt tall and one 0.5 pt tall, each drawn up and down the page. diff --git a/crates/three-d/src/shadow.rs b/crates/three-d/src/shadow.rs index 00ae75d169..38d2be50c7 100644 --- a/crates/three-d/src/shadow.rs +++ b/crates/three-d/src/shadow.rs @@ -369,7 +369,7 @@ pub fn inflate_shadowed( /// [`crate::revolve`] gives one. pub fn revolve_shadowed(path: &PathData, bounds: Rect, options: Revolve) -> Result<(Vec, SolidFaces), String> { let mut kept = vec![]; - let (faces, lost) = crate::revolve_sweep(path, options.fill_rule, bounds, options, true, Some(&mut kept))?; + let (faces, lost) = crate::revolve_sweep(path, options.fill_rule, bounds, options, true, Some(&mut kept), None)?; let projection = Some(crate::revolve_projection(bounds, options.sanitized())); Ok((faces, SolidFaces { faces: lost.map_or(Ok(kept), Err), projection })) } diff --git a/crates/three-d/src/solid.rs b/crates/three-d/src/solid.rs index 5029a79910..0ea03dcbf9 100644 --- a/crates/three-d/src/solid.rs +++ b/crates/three-d/src/solid.rs @@ -28,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, extrude_side_size, plane}; +pub use build::{extrude, extrude_side_size, extrude_surfaces, 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; @@ -219,6 +219,9 @@ 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, + /// Lay out the solid's numbered surfaces ([`extrude_surfaces`]): each facet of a wall or a + /// bevel band then carries its [`MapCell`]. A solid with a twist or a taper has none. + pub map_surfaces: 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, @@ -226,10 +229,44 @@ pub struct Extrude { impl Default for Extrude { fn default() -> Self { - Self { depth: 50.0, twist: 0.0, taper: 1.0, cap: true, bevel: None, hidden: false, map_surface: false } + Self { depth: 50.0, twist: 0.0, taper: 1.0, cap: true, bevel: None, hidden: false, map_surfaces: false, map_surface: false } } } +/// Where a facet lies on one of its solid's numbered surfaces, laid out flat: the surface's index, +/// the facet's corners on the page, and the point of the flat surface at each corner, in points +/// (x along the surface from its left edge as it is seen from outside the solid, y from the edge +/// nearer the front of the solid). +#[derive(Clone, Debug, PartialEq)] +pub struct MapCell { + pub surface: usize, + pub page: Vec, + pub uv: Vec, +} + +/// What a numbered surface of a solid is. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SurfaceKind { + /// The front or back cap, or a plane's only face. + End(PlanarFace), + /// A side wall: the part of the side between two corners of the outline. + Wall, + /// The bevel between the front cap and a side wall. + Bevel, + /// Revolve's swept side. + Side, +} + +/// One numbered surface of a solid: its kind and its size laid out flat, in points. An end also +/// has the center of its bounds in the art's plane. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct SolidSurface { + pub kind: SurfaceKind, + pub width: f64, + pub height: f64, + pub center: Option, +} + /// Inflate's options. #[derive(Clone, Copy, Debug, PartialEq)] pub struct Inflate { @@ -311,6 +348,10 @@ pub struct Facet { /// 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. pub plane: Option, + /// Where the facet lies on one of its solid's numbered surfaces. `None` unless the solid was + /// built with its surfaces laid out ([`Extrude::map_surfaces`], [`Revolve::map_surface`]), + /// and for the ends, whose art is placed through a [`FaceMap`]. + pub cell: Option>, /// The contours in view space, before projection, for tests that measure depths. #[cfg(test)] view: Vec>, @@ -383,7 +424,11 @@ impl Facet { /// Revolve's face `face` as a facet: its polygon, curved outline, depth, plane, normal and lighting. /// A face that joins the profile's ends round the axis is a side; a cap is an end. pub(crate) fn of_face(face: crate::Face) -> Self { + // The side is the surface's only numbered surface. A face that shows its inside carries + // no cell. + let cell = face.surface.filter(|c| c.outward && !face.cap).map(|c| Box::new(MapCell { surface: 0, page: c.page, uv: c.uv })); Facet { + cell, contours: vec![face.points], depth: face.depth, brightness: face.brightness, diff --git a/crates/three-d/src/solid/build.rs b/crates/three-d/src/solid/build.rs index 29d5debcc3..e5b311ed0c 100644 --- a/crates/three-d/src/solid/build.rs +++ b/crates/three-d/src/solid/build.rs @@ -7,8 +7,8 @@ use super::rings::{ }; 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, + Bevel, DepthPlane, Extrude, Facet, FillRule, MAX_FACES, MAX_SOLID_FACES, MapCell, ParamCurve, PathData, PlanarFace, Point, Rect, Revolve, + SolidSurface, SurfaceKind, V3, View, eye_distance, perspective_scale, }; use crate::shadow::Projection; @@ -102,6 +102,16 @@ pub(super) struct Builder<'a> { /// The faces kept for the mesh passed [`MAX_SOLID_FACES`] while the facets were built too: the /// mesh is too complex, and `mesh` keeps no more faces. pub(super) lost: bool, + /// The cells the facets of the next band carry ([`Builder::curved_band`]). + pub(super) cells: Option, +} + +/// The cells of one band's facets: for each edge of the ring, its numbered surface and where the +/// edge starts and ends along it (`None` for an edge of no length), and where the band's two rings +/// lie across the surface. +pub(super) struct BandCells { + edges: Vec>, + across: (f64, f64), } /// Where a face goes in the order the facets are drawn, back to front. @@ -123,7 +133,16 @@ pub(super) enum Order { impl<'a> Builder<'a> { /// A builder for one solid seen by `camera`, keeping what `keep` asks for. pub(super) fn new(camera: &'a Camera, closed: bool, hidden: bool, keep: Keep) -> Self { - Self { camera, closed, hidden, facets: vec![], mesh: (keep != Keep::Facets).then(Vec::new), draw: keep != Keep::Faces, lost: false } + Self { + camera, + closed, + hidden, + facets: vec![], + mesh: (keep != Keep::Facets).then(Vec::new), + draw: keep != Keep::Faces, + lost: false, + cells: None, + } } /// Add a face of view-space contours with outward normal `n` (view space), drawn in `order`. @@ -214,6 +233,7 @@ impl<'a> Builder<'a> { end: None, surface: None, plane, + cell: None, #[cfg(test)] view, }); @@ -300,6 +320,12 @@ impl<'a> Builder<'a> { && let Some(f) = self.facets.last_mut() { f.side = true; + // An edge drawn in one piece carries its place on its numbered surface. + let cell = self.cells.as_ref().filter(|_| pieces == 1).and_then(|c| Some((c.edges.get(i).copied().flatten()?, c.across))); + if let (Some(((surface, u0, u1), (v0, v1))), Some(page)) = (cell, f.contours.first()) { + let uv = vec![Point::new(u0, v0), Point::new(u1, v0), Point::new(u1, v1), Point::new(u0, v1)]; + f.cell = Some(Box::new(MapCell { surface, page: page.clone(), uv })); + } if let Some(s) = side.as_ref() && let (Some([x0, x1]), Some(page)) = (s.x.get(i).copied(), f.contours.first()) { @@ -534,6 +560,16 @@ struct Step { face: f64, } +/// How far the walls are inset (negative: outset). With the bevel inside, the cap is inset by its +/// width and the wall is the outline; outside, the cap is the outline and the wall is outset by +/// the width. +fn wall_inset(o: &Extrude) -> f64 { + match o.bevel.filter(|b| b.width > 0.0 || b.height > 0.0) { + Some(b) if !b.inside => -b.width, + _ => 0.0, + } +} + /// The outline's steps from the front cap's edge to the back cap's edge. fn steps(o: &Extrude) -> Vec { let d = o.depth.max(1e-6); @@ -563,12 +599,7 @@ fn steps(o: &Extrude) -> Vec { } pts }; - // With the bevel inside, the cap is inset by its width and the wall is the outline; outside, - // the cap is the outline and the wall is outset by the width. - let wall = match bevel { - Some(b) if !b.inside => -b.width, - _ => 0.0, - }; + let wall = wall_inset(o); // A twist turns a bevel's steps too: each step between two samples is cut into steps that // turn no further than 6°, as the walls' slices do at most. let refine = |pts: Vec<(f64, f64)>| -> Vec<(f64, f64)> { @@ -694,6 +725,8 @@ pub(crate) fn extrude_faces(path: &PathData, rule: FillRule, bounds: Rect, optio }) .collect(); let mut budget = Budget::default(); + // The numbered surfaces of the sides, for a solid whose walls stay flat. + let layout = (o.map_surfaces && o.twist == 0.0 && o.taper == 1.0).then(|| (sides(&traced, wall_inset(&o)), band_spans(&steps, o.depth))); // With graphics on the side, the longest contour's pieces carry where they lie on it unrolled. let unrolled = o .map_surface @@ -708,6 +741,17 @@ pub(crate) fn extrude_faces(path: &PathData, rule: FillRule, bounds: Rect, optio 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 }; + b.cells = layout.as_ref().and_then(|(sides, spans)| { + let (bevel, v0, v1) = spans.get(k).copied().flatten()?; + // Without a wall span the walls are not numbered, and the bevels follow the caps. + let walls = has_walls(spans); + if !bevel && !walls { + return None; + } + let base = caps + if bevel && walls { sides.lengths.len() } else { 0 }; + let edges = sides.edges.get(r)?.iter().map(|e| e.map(|(section, u0, u1)| (base + section, u0, u1))).collect(); + Some(BandCells { edges, across: (v0, v1) }) + }); // A band between two front bevel steps borders the front, one reaching a back bevel // step the back; the rest are walls. let face = if s1.face < 0.0 { @@ -725,6 +769,7 @@ pub(crate) fn extrude_faces(path: &PathData, rule: FillRule, bounds: Rect, optio b.curved_band(a, c, pieces, |i| outward(ring, i, face), curves, side)?; } } + b.cells = None; if o.cap { // A cap turned toward the viewer covers the walls it overlaps, even those nearer than its // center: twisted walls, and the walls of a fill inside the solid of its stroke. @@ -743,6 +788,152 @@ pub(crate) fn extrude_faces(path: &PathData, rule: FillRule, bounds: Rect, optio Ok(b.finish()) } +/// The turn of the outline, in degrees, past which the side wall on one side of a point is another +/// numbered surface than the wall on its other side. +const CORNER: f64 = 20.0; + +/// How the sides of a solid's rings divide into numbered surfaces: for each ring, each edge's +/// surface (counted through the rings in order) and where the edge starts and ends along it, and +/// each surface's length. A surface runs from one corner of its ring to the next, and a ring with +/// no corner is one surface from its first point. The edges of one curve of the outline are never +/// parted. An edge of no length belongs to no surface. An edge starts farther along its surface +/// than it ends: the surface is measured from its left edge as it is seen from outside the solid. +/// Lengths are measured on the ring moved to the walls' inset `wall`, so a wall set out by a bevel +/// is laid out at its own length, and a bevel band at the length of the wall below it. +struct Sides { + edges: Vec>>, + lengths: Vec, +} + +fn sides(rings: &[Ring], wall: f64) -> Sides { + let mut out = Sides { edges: vec![], lengths: vec![] }; + for ring in rings { + let n = ring.points.len(); + let point = |i: usize| ring.points.get(i % n.max(1)).copied().unwrap_or_default(); + let at_wall = inset(&ring.points, wall); + let wall_point = |i: usize| at_wall.get(i % n.max(1)).copied().unwrap_or_default(); + // An edge of the outline with no length (a corner cut square) stays off every surface. + let length = |i: usize| if point(i).distance(point(i + 1)) > 1e-9 { wall_point(i).distance(wall_point(i + 1)) } else { 0.0 }; + let direction = |i: usize| { + let d = point(i + 1) - point(i); + let l = d.hypot(); + (l > 1e-9).then(|| d / l) + }; + let curve = |i: usize| ring.spans.get(i % n.max(1)).copied().flatten().map(|s| s.curve); + // Point `i` is a corner when the edge that leaves it turns from the last edge with a + // length before it, and the two do not follow one curve. + let corner = |i: usize| { + let Some(leaving) = direction(i) else { return false }; + let Some(before) = (1..n).map(|k| i + n - k).find(|e| direction(*e).is_some()) else { return false }; + let one_curve = matches!((curve(before), curve(i)), (Some(a), Some(b)) if a == b); + !one_curve && direction(before).is_some_and(|d| d.dot(leaving) < CORNER.to_radians().cos()) + }; + let start = (0..n).find(|i| corner(*i)).unwrap_or(0); + let mut edges = vec![None; n]; + let mut along = 0.0; + out.lengths.push(0.0); + for k in 0..n { + let i = (start + k) % n; + if k > 0 && corner(i) { + out.lengths.push(0.0); + along = 0.0; + } + let l = length(i); + if let Some(slot) = edges.get_mut(i).filter(|_| l > 1e-9) { + *slot = Some((out.lengths.len() - 1, along, along + l)); + } + along += l; + if let Some(total) = out.lengths.last_mut() { + *total = along; + } + } + // A ring runs from right to left as its side is seen from outside the solid, so each edge + // is placed from its surface's far end. + for (surface, from, to) in edges.iter_mut().flatten() { + let length = out.lengths.get(*surface).copied().unwrap_or(0.0); + (*from, *to) = (length - *from, length - *to); + } + out.edges.push(edges); + } + out +} + +/// Where the band between each two neighboring steps lies across its numbered surface: whether it +/// is part of the front bevel (else of the wall), and the distances of its two rings from the +/// surface's edge nearer the front. `None` for a band of a back bevel. +fn band_spans(steps: &[Step], depth: f64) -> Vec> { + let (mut bevel_at, mut wall_at) = (0.0, 0.0); + steps + .windows(2) + .map(|pair| { + let [s0, s1] = pair else { return None }; + if s1.face < 0.0 { + return None; + } + let across = (s1.inset - s0.inset).hypot((s1.t - s0.t) * depth); + let bevel = s0.face > 0.0 && s1.face > 0.0; + let at = if bevel { &mut bevel_at } else { &mut wall_at }; + let from = *at; + *at += across; + Some((bevel, from, *at)) + }) + .collect() +} + +/// Whether the bands of `spans` ([`band_spans`]) hold a wall with some width across it: a bevel as +/// deep as the solid leaves none. +fn has_walls(spans: &[Option<(bool, f64, f64)>]) -> bool { + spans.iter().flatten().any(|(bevel, from, to)| !bevel && to > from) +} + +/// The numbered surfaces of the solid [`extrude`] builds from `path`, in order: the front and back +/// caps of a solid with caps, then each side wall, ring by ring from each ring's first corner, then +/// the bevel above each wall in the same order. A plane (no depth) has its front only, and a solid +/// with a twist or a taper has only its caps. A solid whose bevel is as deep as the solid has no +/// walls. The facets of a solid built with +/// [`Extrude::map_surfaces`] carry these indexes ([`MapCell`]). +pub fn extrude_surfaces(path: &PathData, rule: FillRule, bounds: Rect, options: Extrude) -> Result, String> { + check_bounds(bounds)?; + let o = options.sanitized(); + let end = + |face: PlanarFace, b: Rect| SolidSurface { kind: SurfaceKind::End(face), width: b.width(), height: b.height(), center: Some(b.center()) }; + if o.depth <= 0.0 { + return Ok(path.bounds().map(|b| end(PlanarFace::Front, b)).into_iter().collect()); + } + 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)?; + 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)?.iter().map(|r| square_corners(r, side)).collect(); + // A solid past the face limit is refused, as [`extrude_faces`] refuses it. + let edges = traced.iter().map(|r| r.points.len()).fold(0usize, usize::saturating_add); + if edges.saturating_mul(bands).saturating_add(caps) > MAX_SOLID_FACES { + return Err(TOO_COMPLEX_SURFACE.into()); + } + let mut out = vec![]; + if o.cap { + for (step, face) in [(steps.first(), PlanarFace::Front), (steps.last(), PlanarFace::Back)] { + let Some(step) = step else { continue }; + let mut points = traced.iter().flat_map(|r| inset(&r.points, step.inset)); + let Some(first) = points.next() else { continue }; + out.push(end(face, points.fold(Rect::from_points(first, first), |b, p| b.union_pt(p)))); + } + } + if o.twist != 0.0 || o.taper != 1.0 { + return Ok(out); + } + let sides = sides(&traced, wall_inset(&o)); + let spans = band_spans(&steps, o.depth); + let across = |bevel: bool| spans.iter().flatten().filter(|s| s.0 == bevel).map(|s| s.2).fold(0.0, f64::max); + let walls = has_walls(&spans).then_some((SurfaceKind::Wall, false)); + let kinds = walls.into_iter().chain(spans.iter().flatten().any(|s| s.0).then_some((SurfaceKind::Bevel, true))); + for (kind, bevel) in kinds { + out.extend(sides.lengths.iter().map(|l| SolidSurface { kind, width: *l, height: across(bevel), center: None })); + } + Ok(out) +} + /// 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. diff --git a/crates/three-d/src/solid/tests.rs b/crates/three-d/src/solid/tests.rs index b32faf1097..78d2fcdcbe 100644 --- a/crates/three-d/src/solid/tests.rs +++ b/crates/three-d/src/solid/tests.rs @@ -438,6 +438,7 @@ 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_surfaces: false, map_surface: true, }; let f = extrude(&p, FillRule::EvenOdd, b, wild, View { rotation_x: f64::NAN, perspective: 900.0, ..front() }).unwrap(); diff --git a/crates/three-d/src/solid/tests_side.rs b/crates/three-d/src/solid/tests_side.rs index f2d7ec722a..47c519ca05 100644 --- a/crates/three-d/src/solid/tests_side.rs +++ b/crates/three-d/src/solid/tests_side.rs @@ -1,6 +1,6 @@ use vectorcraft_geom::{BezPath, FillRule, PathData, Point, Rect}; -use super::super::{Bevel, Extrude, View, extrude, extrude_side_size}; +use super::super::{Bevel, Extrude, View, extrude, extrude_side_size, extrude_surfaces}; use super::{across_steps, along_ring, longest}; fn square(r: Rect, hole: Option) -> PathData { @@ -94,3 +94,30 @@ fn the_side_measures_around_the_outline_and_across_the_bevels() { 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)); } + +#[test] +fn the_surfaces_of_a_solid_past_the_face_limit_are_refused_as_its_side_is() { + // A star of `n` thin spikes: a bevel outside cuts each sharp tip square, adding a corner there. + let star = |n: usize| { + let mut b = BezPath::new(); + for i in 0..2 * n { + let a = i as f64 * std::f64::consts::PI / n as f64; + let r = if i % 2 == 0 { 1000.0 } else { 100.0 }; + if i == 0 { b.move_to((r * a.cos(), r * a.sin())) } else { b.line_to((r * a.cos(), r * a.sin())) } + } + b.close_path(); + PathData::from_bezpath(&b) + }; + let bounds = Rect::new(-1000.0, -1000.0, 1000.0, 1000.0); + let o = Extrude { depth: 40.0, bevel: Some(Bevel { width: 1.0, height: 1.0, ..Bevel::default() }), ..Extrude::default() }; + let fits = |n: usize| extrude_side_size(&star(n), FillRule::NonZero, bounds, o).is_some(); + // The fewest spikes past the limits, as the side's size counts them. + let (mut lo, mut hi) = (3usize, 100_000usize); + assert!(fits(lo) && !fits(hi)); + while hi - lo > 1 { + let mid = (lo + hi) / 2; + if fits(mid) { lo = mid } else { hi = mid } + } + assert!(extrude_surfaces(&star(lo), FillRule::NonZero, bounds, o).is_ok()); + assert!(extrude_surfaces(&star(hi), FillRule::NonZero, bounds, o).is_err(), "{hi} spikes"); +} diff --git a/crates/three-d/src/tests.rs b/crates/three-d/src/tests.rs index ace8566816..069013c808 100644 --- a/crates/three-d/src/tests.rs +++ b/crates/three-d/src/tests.rs @@ -327,6 +327,16 @@ fn only_the_longest_contour_of_a_compound_profile_carries_the_side_surface() { let (w, h) = revolve_surface_size(&PathData::from_bezpath(&bp), b, Revolve::default()).unwrap(); assert!((w - 10.0 * std::f64::consts::PI).abs() < 1e-9 && (h - 80.0).abs() < 1e-3, "{w} {h}"); } +#[test] +fn a_side_quad_lies_on_the_surface_at_its_corners_distances_from_the_axis() { + // An edge from 30 to 50 pt right of an axis at 10, at surface y -5 and 15, over a step from + // 0.25 to 0.5 radians: x is each angle times each corner's own distance from the axis. + let corners = surface_corners(Point::new(30.0, 0.0), Point::new(50.0, 20.0), 10.0, [-5.0, 15.0], [0.25, 0.5]); + assert_eq!(corners, [Point::new(5.0, -5.0), Point::new(10.0, 15.0), Point::new(20.0, 15.0), Point::new(10.0, -5.0)]); + // Left of the axis the distances are the same. + let left = surface_corners(Point::new(-10.0, 0.0), Point::new(-30.0, 20.0), 10.0, [-5.0, 15.0], [0.25, 0.5]); + assert_eq!(left, corners); +} /// The square ring of [`a_ring_profile_is_measured_from_its_outer_side_at_mid_height`] with an /// anchor in the middle of its inner side. fn split_square() -> [Point; 6] { diff --git a/crates/tools/src/addons.rs b/crates/tools/src/addons.rs index ca8645ffc8..c0223aedb9 100644 --- a/crates/tools/src/addons.rs +++ b/crates/tools/src/addons.rs @@ -17,6 +17,7 @@ pub mod polygonal_lasso; pub mod shared_edge; pub mod slide_anchor; pub mod smart_pen; +pub mod tangent_circle; pub mod trim; use crate::{Tool, ToolInfo}; @@ -31,6 +32,7 @@ pub const PATH_TOOLS: &[ToolInfo] = &[ ToolInfo { id: corner_tool::ID, label: "Corner Tool", shortcut: None, icon: "dc-rounded-rect" }, ToolInfo { id: slide_anchor::ID, label: "Slide Anchor Along Path", shortcut: None, icon: "dc-anchor" }, ToolInfo { id: shared_edge::ID, label: "Shared Edge Merge Tool", shortcut: None, icon: "dc-join" }, + ToolInfo { id: tangent_circle::ID, label: "Tangent Circle Tool", shortcut: None, icon: "circle" }, ]; /// Smart Pen's tool, a flyout group of its own. @@ -66,6 +68,7 @@ pub fn create(id: &str) -> Option> { shared_edge::ID => Box::new(shared_edge::SharedEdgeTool::default()), slide_anchor::ID => Box::new(slide_anchor::SlideAnchorTool::default()), smart_pen::ID => Box::new(smart_pen::SmartPenTool::default()), + tangent_circle::ID => Box::new(tangent_circle::TangentCircleTool::default()), trim::ID => Box::new(trim::TrimTool::default()), enclosing_lasso::ID => Box::new(enclosing_lasso::EnclosingLassoTool::default()), contour::ID => Box::new(contour::ContourTool::default()), diff --git a/crates/tools/src/addons/tangent_circle.rs b/crates/tools/src/addons/tangent_circle.rs new file mode 100644 index 0000000000..a8d24d8853 --- /dev/null +++ b/crates/tools/src/addons/tangent_circle.rs @@ -0,0 +1,720 @@ +//! Tangent Circle tool (Path Precision Tools): click a path segment, then another, selected or +//! not, to draw the circle that is tangent to the first segment where it was clicked and touches the +//! second ([`circles_through`]). With Shift held over the second segment the circle has the tool's +//! `radius` instead, anywhere along the first segment ([`circles_of_radius`]). A drag from the +//! second segment sets the radius to the drag's length, the circle again anywhere along the first +//! segment: Shift steps it by a round number of points about 4 screen pixels long, and Cmd/Ctrl +//! pressed during the drag moves it by a tenth of the pointer's movement (held at the press, +//! Cmd/Ctrl lends the selection tool as it does for every tool). The segments on either side of the +//! second one count with it (the first one excepted), and of the circles found the one touching +//! them nearest the pointer (in a drag, nearest the press) is drawn. While the pointer is over the +//! second segment the circle shows with its center and radii; where there is none, or none that its +//! three points can draw, a note says so. The circle is a new ellipse with the current paint, drawn +//! with `shape.circleThroughPoints` in one undo step, so Align New Objects to Pixel Grid leaves it +//! in place; the first segment stays picked until the circle is drawn, also when drawing fails or the +//! press on the second segment is dropped. Escape, an edit or Undo outside the tool, or another +//! document forgets the first segment. + +use kurbo::{CubicBez, Shape}; +use serde_json::{Value, json}; +use vectorcraft_doc::NodeId; +use vectorcraft_geom::{BezPath, ParamCurve, Point}; +use vectorcraft_pathops::addons::pathtools::{SegmentCircle, circles_of_radius, circles_through}; + +use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; + +/// The tool's id. +pub const ID: &str = "tangentCircle"; +/// The radius Shift asks for to start with (pt). +pub const RADIUS: f64 = 36.0; +/// The radius the `radius` option takes (pt). +pub const RADIUS_RANGE: (f64, f64) = (0.01, 1e6); +/// How far (screen pixels) the pointer moves from the second click before a drag sets the radius. +const DRAG_PX: f64 = 3.0; +/// About how long (screen pixels) one step of a Shift drag is. +const STEP_PX: f64 = 4.0; +/// How much of the pointer's movement a Cmd/Ctrl drag gives the radius. +const SLOW: f64 = 0.1; +/// The note shown over a second segment that gives no circle. +pub const NO_CIRCLE: &str = "No tangent circle here"; +const BLUE: [u8; 3] = [0x4f, 0x9d, 0xff]; +const RED: [u8; 3] = [0xe0, 0x3c, 0x3c]; +const GREY: [u8; 3] = [0x80, 0x80, 0x80]; + +/// A segment under the pointer: where on it, and the segment itself. +#[derive(Clone, Debug, PartialEq)] +struct Pick { + id: NodeId, + subpath: usize, + segment: usize, + t: f64, + p: Point, + curve: CubicBez, +} + +/// A press on the second segment, kept while the button is down. +#[derive(Clone, Debug, PartialEq)] +struct Press { + /// The segments a circle may touch. + second: Vec, + /// Where the press was. + at: Point, + /// Whether Shift was held when the click's circle was last looked for. + shift: bool, + /// How far the pointer was from the press last time, and the radius the drag set (none until + /// the pointer moves far enough). + reach: f64, + radius: Option, +} + +pub struct TangentCircleTool { + radius: f64, + first: Option, + hover: Option, + press: Option, + /// Whether the press in progress picked the first segment. + picking: bool, + /// The circle the second segment gives, and whether one was looked for. + found: Option, + looked: bool, + pointer: Point, + /// The circles the last second segment gave (its path, subpath and segment, and the radius + /// asked for), so that moving along it only picks among them. + cache: Option<(CacheKey, Vec)>, +} + +type CacheKey = (NodeId, usize, usize, Option); + +impl Default for TangentCircleTool { + fn default() -> Self { + Self { radius: RADIUS, first: None, hover: None, press: None, picking: false, found: None, looked: false, pointer: Point::ZERO, cache: None } + } +} + +/// The path segment under `p`, of any editable path. +fn pick_at(cx: &ToolContext, p: Point) -> Option { + let (id, subpath, segment, t) = crate::draw2::hit_segment(cx, p, cx.pick_tol())?; + let sp = cx.doc.node(id)?.path_data()?.subpaths.get(subpath)?; + if segment >= sp.segment_count() { + return None; + } + let curve = sp.segment(segment); + Some(Pick { id, subpath, segment, t, p: curve.eval(t), curve }) +} + +/// The segments a circle may touch when `second` is picked: it and the segments on either side of +/// it, without `first`. None when `second` is the first segment again. +fn second_set(cx: &ToolContext, first: &Pick, second: &Pick) -> Vec { + if (first.id, first.subpath, first.segment) == (second.id, second.subpath, second.segment) { + return vec![]; + } + let Some(sp) = cx.doc.node(second.id).and_then(|n| n.path_data()).and_then(|p| p.subpaths.get(second.subpath)) else { return vec![] }; + let n = sp.segment_count(); + let i = second.segment; + let mut indices = vec![i]; + if i > 0 || sp.closed { + indices.push((i + n - 1) % n); + } + if i + 1 < n || sp.closed { + indices.push((i + 1) % n); + } + indices.sort_unstable(); + indices.dedup(); + let is_first = |k: usize| first.id == second.id && first.subpath == second.subpath && first.segment == k; + indices.into_iter().filter(|k| *k < n && !is_first(*k)).map(|k| sp.segment(k)).collect() +} + +/// Of `circles`, the one touching the second segments nearest `at`, leaving out those [`draw`] cannot +/// draw within `tol`. +fn nearest_to(circles: Vec, at: Point, tol: f64) -> Option { + circles.into_iter().filter(|c| draw(c, tol).is_some()).min_by(|a, b| (a.second - at).hypot().total_cmp(&(b.second - at).hypot())) +} + +/// How far (screen pixels) the circle three points give back may be from the circle found. +const DRAW_PX: f64 = 0.05; +/// What the tool is told once its circle is drawn: then it forgets the first segment. +const DRAWN: &str = "tangentCircle.drawn"; + +/// The circles on `first` and `second`: tangent at the first pick, or of `radius`. +fn circles(first: &Pick, second: &[CubicBez], radius: Option) -> Vec { + match radius { + Some(r) => circles_of_radius(first.curve, second, r), + None => circles_through(first.curve, first.t, second), + } +} + +/// The step a Shift drag rounds the radius to: 1, 2 or 5 times a power of 10, at least `least`. +fn round_step(least: f64) -> f64 { + if !(least.is_finite() && least > 0.0) { + return 1.0; + } + let e = 10f64.powf(least.log10().floor()); + [1.0, 2.0, 5.0, 10.0].into_iter().map(|m| m * e).find(|s| *s >= least).unwrap_or(10.0 * e) +} + +/// Draw circle `c`: through three points spread around it, with `shape.circleThroughPoints`, which +/// leaves it where it is with Align New Objects to Pixel Grid on, so that it stays tangent. None +/// when the three points do not give the circle back to within `tol` (a circle too small for its +/// distance from the origin, or too large, in floating point). +fn draw(c: &SegmentCircle, tol: f64) -> Option { + let (at, r) = (c.circle.center, c.circle.radius); + let points: Vec = [90.0f64, 210.0, 330.0] + .iter() + .map(|deg| { + let (s, k) = deg.to_radians().sin_cos(); + Point::new(at.x + r * k, at.y + r * s) + }) + .collect(); + let (back, rb) = vectorcraft_geom::shapes::circle_through(points[0], points[1], points[2])?; + if !(back.distance(at) <= tol && (rb - r).abs() <= tol) { + return None; + } + let points: Vec<[f64; 2]> = points.iter().map(|p| [p.x, p.y]).collect(); + Some(Action::Exec("shape.circleThroughPoints".into(), json!({ "points": points }))) +} + +fn segment_path(c: &CubicBez) -> BezPath { + let mut bp = BezPath::new(); + bp.move_to(c.p0); + bp.curve_to(c.p1, c.p2, c.p3); + bp +} + +impl TangentCircleTool { + /// The radius a drag gives, with Shift in round steps. + fn shown_radius(cx: &ToolContext, r: f64, shift: bool) -> f64 { + if !shift { + return r; + } + let step = round_step(cx.tol(STEP_PX)); + // Less than half a step rounds to 0: no circle, as without Shift. + (r / step).round() * step + } + + /// The circles `pick` gives as the second segment, with Shift's `radius`: worked out again only + /// when the segment or the radius changes. + fn circles_on(&mut self, cx: &ToolContext, pick: &Pick, radius: Option) -> Vec { + let key = (pick.id, pick.subpath, pick.segment, radius.map(f64::to_bits)); + if let Some((k, found)) = &self.cache + && *k == key + { + return found.clone(); + } + let Some(first) = &self.first else { return vec![] }; + let found = circles(first, &second_set(cx, first, pick), radius); + self.cache = Some((key, found.clone())); + found + } + + /// Look for the circle the pointer at `p` would give over `hover`, before any press. + fn look(&mut self, cx: &ToolContext, p: Point, mods: Mods) { + self.found = None; + self.looked = false; + let Some(hover) = self.hover.clone().filter(|_| self.first.is_some()) else { return }; + let found = self.circles_on(cx, &hover, mods.shift.then_some(self.radius)); + self.found = nearest_to(found, p, cx.tol(DRAW_PX)); + self.looked = true; + } + + /// The pointer at `ev` during a press on the second segment: once it is far enough from the + /// press, the radius follows it (Cmd/Ctrl: a tenth of its movement; Shift: round steps). + fn drag_to(&mut self, cx: &ToolContext, ev: &PointerEvent) { + let radius = self.radius; + let (Some(first), Some(press)) = (&self.first, &mut self.press) else { return }; + let reach = ev.pos.distance(press.at); + let gear = if ev.mods.cmd { SLOW } else { 1.0 }; + let r = match press.radius { + None if reach <= cx.tol(DRAG_PX) => { + // Shift pressed or let go before the drag starts: the click's circle, with or + // without the tool's radius. + if ev.mods.shift != press.shift { + press.shift = ev.mods.shift; + let found = circles(first, &press.second, press.shift.then_some(radius)); + self.found = nearest_to(found, press.at, cx.tol(DRAW_PX)); + } + return; + } + None => reach * gear, + Some(r) => (r + (reach - press.reach) * gear).max(0.0), + }; + press.reach = reach; + press.radius = Some(r); + let shown = Self::shown_radius(cx, r, ev.mods.shift); + // Dragged back to the press: a radius of 0, and no circle. + self.found = if shown > 0.0 { nearest_to(circles(first, &press.second, Some(shown)), press.at, cx.tol(DRAW_PX)) } else { None }; + } + + fn forget(&mut self) { + self.first = None; + self.press = None; + self.picking = false; + self.found = None; + self.looked = false; + self.cache = None; + } +} + +impl Tool for TangentCircleTool { + fn id(&self) -> &'static str { + ID + } + + fn busy(&self) -> bool { + self.press.is_some() + } + + fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { + self.pointer = ev.pos; + match ev.kind { + PointerKind::Move => { + self.hover = pick_at(cx, ev.pos); + self.look(cx, ev.pos, ev.mods); + vec![] + } + PointerKind::Down => { + let Some(pick) = pick_at(cx, ev.pos) else { return vec![] }; + let Some(first) = self.first.clone() else { + self.first = Some(pick); + self.picking = true; + self.hover = None; + self.found = None; + self.looked = false; + return vec![]; + }; + let second = second_set(cx, &first, &pick); + let found = self.circles_on(cx, &pick, ev.mods.shift.then_some(self.radius)); + self.found = nearest_to(found, ev.pos, cx.tol(DRAW_PX)); + self.looked = true; + self.hover = None; + self.press = Some(Press { second, at: ev.pos, shift: ev.mods.shift, reach: 0.0, radius: None }); + vec![] + } + PointerKind::Drag => { + self.drag_to(cx, ev); + vec![] + } + PointerKind::Up => { + // The release's own position and keys set the radius of a drag. + self.drag_to(cx, ev); + self.picking = false; + if self.press.take().is_none() { + return vec![]; + } + // No circle, or one the three points cannot draw: the first segment stays picked, + // for another try. It also stays when the command fails: only a drawn circle tells + // the tool (`notify`) to forget it. + let Some(action) = self.found.take().and_then(|c| draw(&c, cx.tol(DRAW_PX))) else { return vec![] }; + self.looked = false; + vec![action, Action::Notify(DRAWN.into())] + } + // The canvas sends a double-click after the second click's `Up`, which drew the circle. + PointerKind::DoubleClick | PointerKind::TripleClick => vec![], + } + } + + fn key(&mut self, _cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { + if key == ToolKey::Escape && self.first.is_some() { + self.forget(); + } + vec![] + } + + /// A dropped press (a canceled touch, a second finger) undoes only what that press did: a press + /// on the second segment draws nothing and the first segment stays picked, and a press that + /// picked the first segment leaves none picked. + fn drop_press(&mut self, _cx: &ToolContext) -> Vec { + if self.press.take().is_some() { + self.found = None; + self.looked = false; + } else if std::mem::take(&mut self.picking) { + self.forget(); + } + vec![] + } + + fn claims_key(&self, _cx: &ToolContext, key: ToolKey) -> bool { + key == ToolKey::Escape && self.first.is_some() + } + + fn notify(&mut self, _cx: &ToolContext, what: &str) { + if what == DRAWN { + self.forget(); + } + } + + /// An edit, Undo or Redo outside the tool, or another document: the first segment may be gone. + fn history_moved(&mut self) { + self.forget(); + self.hover = None; + } + + /// The segment and the circle shown depend on what lies under the pointer, which panning, + /// zooming or an edit changes. + fn wants_rehover(&self) -> bool { + true + } + + fn hover_ended(&mut self, _cx: &ToolContext) { + self.hover = None; + if self.press.is_none() { + self.found = None; + self.looked = false; + } + } + + fn overlays(&self, cx: &ToolContext) -> Vec { + let mut out = vec![]; + if let Some(first) = &self.first { + out.push(Overlay::Path { path: segment_path(&first.curve), color: BLUE, width: 2.0, dashed: false }); + out.push(Overlay::Anchor { p: first.p, color: BLUE, filled: true, size: 7.0 }); + } + if let Some(hover) = &self.hover { + out.push(Overlay::Path { path: segment_path(&hover.curve), color: BLUE, width: 1.0, dashed: false }); + out.push(Overlay::Anchor { p: hover.p, color: BLUE, filled: false, size: 7.0 }); + } + if let Some(press) = &self.press + && press.radius.is_some() + { + out.push(Overlay::Line { a: press.at, b: self.pointer, color: GREY, dashed: false }); + } + if let Some(c) = &self.found { + let (at, r) = (c.circle.center, c.circle.radius); + // A tolerance of at least a ten-thousandth of the radius keeps a huge circle to a few + // dozen segments. + let tol = cx.tol(0.1).max(r * 1e-4); + out.push(Overlay::Path { path: kurbo::Circle::new(at, r).to_path(tol), color: RED, width: 1.0, dashed: false }); + let arm = cx.tol(4.0); + out.push(Overlay::Line { a: at - kurbo::Vec2::new(arm, 0.0), b: at + kurbo::Vec2::new(arm, 0.0), color: RED, dashed: false }); + out.push(Overlay::Line { a: at - kurbo::Vec2::new(0.0, arm), b: at + kurbo::Vec2::new(0.0, arm), color: RED, dashed: false }); + out.push(Overlay::Line { a: at, b: c.first, color: RED, dashed: true }); + out.push(Overlay::Line { a: at, b: c.second, color: RED, dashed: true }); + out.push(Overlay::Measure { p: self.pointer, text: format!("R: {}", cx.len(r)) }); + } else if self.looked { + // A label, which the canvas shows in the interface language. + out.push(Overlay::Label { p: self.pointer, text: NO_CIRCLE.into(), color: RED }); + } + out + } + + fn cursor(&self, _cx: &ToolContext, _p: Point, _mods: Mods) -> Cursor { + Cursor::Crosshair + } + + fn options(&self) -> Value { + json!({ "radius": self.radius }) + } + + fn set_option(&mut self, key: &str, v: &Value) { + if key == "radius" + && let Some(r) = v.as_f64().filter(|r| (RADIUS_RANGE.0..=RADIUS_RANGE.1).contains(r)) + { + self.radius = r; + } + } + + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + use crate::option_check as c; + match key { + "radius" => c::number(key, v, RADIUS_RANGE.0, RADIUS_RANGE.1), + _ => Err(c::unknown(key)), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::testutil::*; + use vectorcraft_doc::{Appearance, Document, Node, Selection}; + use vectorcraft_geom::{PathData, SubPath}; + + /// Two open lines, (100, 100)–(300, 100) and (100, 140)–(300, 140), and an L from (100, 300) + /// over to (300, 300) and down to (300, 400). + fn doc() -> Document { + let mut d = Document::new(500.0, 500.0); + let l = d.layers[0].id; + let lines: [&[(f64, f64)]; 3] = + [&[(100.0, 100.0), (300.0, 100.0)], &[(100.0, 140.0), (300.0, 140.0)], &[(100.0, 300.0), (300.0, 300.0), (300.0, 400.0)]]; + for pts in lines { + let id = d.alloc_id(); + let pts: Vec = pts.iter().map(|(x, y)| Point::new(*x, *y)).collect(); + d.insert(Some(l), 0, Node::path(id, PathData::single(SubPath::polyline(&pts, false)), Appearance::default_art())).unwrap(); + } + d + } + + fn ev(kind: PointerKind, x: f64, y: f64) -> PointerEvent { + PointerEvent::new(kind, x, y) + } + + fn shifted(kind: PointerKind, x: f64, y: f64) -> PointerEvent { + let mut e = ev(kind, x, y); + e.mods.shift = true; + e + } + + /// A release, with the tool told what its actions tell it, as the session does once the command + /// before the `Notify` has run. + fn up(t: &mut TangentCircleTool, cx: &ToolContext, e: &PointerEvent) -> Vec { + let acts = t.pointer(cx, e); + for a in &acts { + if let Action::Notify(what) = a { + t.notify(cx, what); + } + } + acts + } + + /// The circle an action list draws, as the box around it: (x, y, width, height). + fn drawn(actions: &[Action]) -> (f64, f64, f64, f64) { + let [Action::Exec(cmd, p), Action::Notify(what)] = actions else { panic!("{actions:?}") }; + assert_eq!((cmd.as_str(), what.as_str()), ("shape.circleThroughPoints", DRAWN)); + let pts: Vec = p["points"].as_array().unwrap().iter().map(|q| Point::new(q[0].as_f64().unwrap(), q[1].as_f64().unwrap())).collect(); + let (at, r) = vectorcraft_geom::shapes::circle_through(pts[0], pts[1], pts[2]).unwrap(); + (at.x - r, at.y - r, 2.0 * r, 2.0 * r) + } + + fn close(a: (f64, f64, f64, f64), b: (f64, f64, f64, f64)) -> bool { + [(a.0, b.0), (a.1, b.1), (a.2, b.2), (a.3, b.3)].iter().all(|(x, y)| (x - y).abs() < 1e-4) + } + + #[test] + fn two_clicks_draw_the_circle_tangent_at_the_first_click() { + let d = doc(); + let (sel, p) = (Selection::default(), paint()); + let cx = cx(&d, &sel, &p); + let mut t = TangentCircleTool::default(); + assert_eq!(t.cursor(&cx, Point::ZERO, Mods::default()), Cursor::Crosshair); + assert!(t.pointer(&cx, &ev(PointerKind::Down, 150.0, 101.0)).is_empty(), "the first segment"); + assert!(t.pointer(&cx, &ev(PointerKind::Up, 150.0, 101.0)).is_empty()); + // Over the second line: the circle through (150, 100) touching it shows, 20 pt in radius. + t.pointer(&cx, &ev(PointerKind::Move, 200.0, 139.0)); + let ov = t.overlays(&cx); + assert!(ov.iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text.starts_with("R: 20.00"))), "{ov:?}"); + assert!(ov.iter().filter(|o| matches!(o, Overlay::Line { dashed: true, .. })).count() == 2, "the radii: {ov:?}"); + // Moving along the same segment picks among the circles already found. + let kept = t.cache.clone(); + assert!(kept.as_ref().is_some_and(|(_, c)| c.len() == 1)); + t.pointer(&cx, &ev(PointerKind::Move, 250.0, 139.0)); + assert_eq!(t.cache, kept); + assert!(t.pointer(&cx, &ev(PointerKind::Down, 200.0, 139.0)).is_empty()); + let released = t.pointer(&cx, &ev(PointerKind::Up, 200.0, 139.0)); + assert!(close(drawn(&released), (130.0, 100.0, 40.0, 40.0)), "{released:?}"); + // Until the command has run and the tool is told, the first segment stays: a command that + // fails leaves it picked. + assert!(t.first.is_some() && !t.busy()); + t.notify(&cx, DRAWN); + assert!(t.first.is_none() && t.overlays(&cx).is_empty(), "ready for the next circle"); + // A quick second click on the second segment: the canvas sends its `Up` and then a + // double-click, which draws nothing more. + for (kind, x, y) in [(PointerKind::Down, 150.0, 101.0), (PointerKind::Up, 150.0, 101.0), (PointerKind::Down, 200.0, 139.0)] { + assert!(t.pointer(&cx, &ev(kind, x, y)).is_empty()); + } + let released = up(&mut t, &cx, &ev(PointerKind::Up, 200.0, 139.0)); + assert!(close(drawn(&released), (130.0, 100.0, 40.0, 40.0)), "{released:?}"); + assert!(t.pointer(&cx, &ev(PointerKind::DoubleClick, 200.0, 139.0)).is_empty()); + assert!(t.first.is_none() && !t.busy()); + } + + #[test] + fn shift_uses_the_radius_and_a_corner_takes_its_fillet() { + let d = doc(); + let (sel, p) = (Selection::default(), paint()); + let cx = cx(&d, &sel, &p); + let mut t = TangentCircleTool::default(); + t.set_option("radius", &json!(10)); + assert_eq!(t.options()["radius"], json!(10.0)); + // `tool.setOption` refuses a value outside 0.01 to 1000000, or one that is not a number, + // and any other option; set anyway, such a value leaves the radius as it is. + for good in [json!(0.01), json!(36), json!(1e6)] { + assert_eq!(t.check_option("radius", &good), Ok(()), "{good}"); + } + for bad in [json!(0), json!(0.005), json!(2e6), json!(-5), json!("12"), Value::Null] { + assert_eq!(t.check_option("radius", &bad), Err("`radius` must be a number from 0.01 to 1000000".into()), "{bad}"); + t.set_option("radius", &bad); + assert_eq!(t.options()["radius"], json!(10.0), "{bad}"); + } + assert!(t.check_option("size", &json!(10)).is_err()); + // The L's two segments: the circle of radius 10 in its corner. + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 300.0)); + t.pointer(&cx, &ev(PointerKind::Up, 150.0, 300.0)); + t.pointer(&cx, &shifted(PointerKind::Down, 300.0, 350.0)); + let released = up(&mut t, &cx, &shifted(PointerKind::Up, 300.0, 350.0)); + assert!(close(drawn(&released), (280.0, 300.0, 20.0, 20.0)), "{released:?}"); + // Shift pressed or let go during a click counts at the release: with a radius of 5 no + // circle reaches the line 40 pt away, and without Shift the click's circle is 20 pt. + let mut t = TangentCircleTool::default(); + t.set_option("radius", &json!(5)); + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Up, 150.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Down, 200.0, 139.0)); + t.pointer(&cx, &shifted(PointerKind::Drag, 200.0, 139.0)); + assert!(t.pointer(&cx, &shifted(PointerKind::Up, 200.0, 139.0)).is_empty(), "nothing drawn"); + assert!(t.first.is_some()); + t.pointer(&cx, &shifted(PointerKind::Down, 200.0, 139.0)); + let released = t.pointer(&cx, &ev(PointerKind::Up, 200.0, 139.0)); + assert!(close(drawn(&released), (130.0, 100.0, 40.0, 40.0)), "{released:?}"); + } + + #[test] + fn a_drag_sets_the_radius_with_shift_steps_and_a_slow_drag() { + let d = doc(); + let (sel, p) = (Selection::default(), paint()); + let cx = cx(&d, &sel, &p); + let mut t = TangentCircleTool::default(); + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 300.0)); + t.pointer(&cx, &ev(PointerKind::Up, 150.0, 300.0)); + t.pointer(&cx, &ev(PointerKind::Down, 300.0, 350.0)); + assert!(t.busy()); + // A drag 12.3 pt long asks for that radius; Shift rounds it (4 px at 100%: steps of 5). + assert!(t.pointer(&cx, &ev(PointerKind::Drag, 300.0, 362.3)).is_empty()); + assert!(t.overlays(&cx).iter().any(|o| matches!(o, Overlay::Line { dashed: false, color, .. } if *color == GREY))); + assert!((t.found.unwrap().circle.radius - 12.3).abs() < 1e-6); + t.pointer(&cx, &shifted(PointerKind::Drag, 300.0, 362.3)); + assert!((t.found.unwrap().circle.radius - 10.0).abs() < 1e-9); + // Cmd/Ctrl: 10 pt more of drag adds 1 pt. + let mut slow = ev(PointerKind::Drag, 300.0, 372.3); + slow.mods.cmd = true; + t.pointer(&cx, &slow); + assert!((t.found.unwrap().circle.radius - 13.3).abs() < 1e-6, "{:?}", t.found); + let released = up(&mut t, &cx, &ev(PointerKind::Up, 300.0, 372.3)); + assert!(close(drawn(&released), (286.7 - 13.3, 300.0, 26.6, 26.6)), "{released:?}"); + // A drag back past its press asks for no radius: no circle, not one through the first click. + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 300.0)); + t.pointer(&cx, &ev(PointerKind::Up, 150.0, 300.0)); + t.pointer(&cx, &ev(PointerKind::Down, 300.0, 350.0)); + t.pointer(&cx, &ev(PointerKind::Drag, 300.0, 360.0)); + t.pointer(&cx, &ev(PointerKind::Drag, 300.0, 350.0)); + assert!(t.found.is_none(), "{:?}", t.found); + t.pointer(&cx, &shifted(PointerKind::Drag, 300.0, 350.0)); + assert!(t.found.is_none(), "with Shift too: {:?}", t.found); + assert!(t.pointer(&cx, &ev(PointerKind::Up, 300.0, 350.0)).is_empty()); + // A release away from the last drag event: the release sets the radius. + t.pointer(&cx, &ev(PointerKind::Down, 300.0, 350.0)); + t.pointer(&cx, &ev(PointerKind::Drag, 300.0, 360.0)); + let released = up(&mut t, &cx, &ev(PointerKind::Up, 300.0, 365.0)); + assert!(close(drawn(&released), (300.0 - 30.0, 300.0, 30.0, 30.0)), "{released:?}"); + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 300.0)); + t.pointer(&cx, &ev(PointerKind::Up, 150.0, 300.0)); + // Cmd/Ctrl held from the start: a 20 pt drag gives 2 pt. + t.pointer(&cx, &ev(PointerKind::Down, 300.0, 350.0)); + let mut slow = ev(PointerKind::Drag, 300.0, 370.0); + slow.mods.cmd = true; + t.pointer(&cx, &slow); + assert!((t.found.unwrap().circle.radius - 2.0).abs() < 1e-6, "{:?}", t.found); + assert_eq!(round_step(2.0), 2.0); + assert_eq!(round_step(0.3), 0.5); + assert_eq!(round_step(7.0), 10.0); + } + + #[test] + fn no_circle_says_so_and_escape_forgets_the_first_segment() { + let d = doc(); + let (sel, p) = (Selection::default(), paint()); + let cx = cx(&d, &sel, &p); + let mut t = TangentCircleTool::default(); + // The first segment again (on the L, whose other segment is beside it): no circle. + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 300.0)); + t.pointer(&cx, &ev(PointerKind::Up, 150.0, 300.0)); + t.pointer(&cx, &shifted(PointerKind::Move, 200.0, 300.0)); + assert!(t.found.is_none() && t.looked, "{:?}", t.found); + t.key(&cx, ToolKey::Escape, Mods::default()); + // Nothing under the pointer: nothing picked. + assert!(t.pointer(&cx, &ev(PointerKind::Down, 50.0, 50.0)).is_empty()); + assert!(t.first.is_none()); + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 100.0)); + t.pointer(&cx, &ev(PointerKind::Up, 150.0, 100.0)); + // Shift with a radius of 5: no circle reaches the line 40 pt away. + t.set_option("radius", &json!(5)); + t.pointer(&cx, &shifted(PointerKind::Move, 200.0, 140.0)); + assert!(t.overlays(&cx).iter().any(|o| matches!(o, Overlay::Label { text, .. } if text == NO_CIRCLE))); + assert!(t.wants_rehover(), "the note follows what lies under a still pointer"); + t.pointer(&cx, &shifted(PointerKind::Down, 200.0, 140.0)); + assert!(t.pointer(&cx, &shifted(PointerKind::Up, 200.0, 140.0)).is_empty(), "nothing drawn"); + assert!(t.first.is_some(), "the first segment stays for another try"); + assert!(t.claims_key(&cx, ToolKey::Escape)); + t.key(&cx, ToolKey::Escape, Mods::default()); + assert!(t.first.is_none() && !t.claims_key(&cx, ToolKey::Escape)); + // An edit the tool did not make (or Undo, or another document) forgets it too. + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 100.0)); + t.pointer(&cx, &ev(PointerKind::Up, 150.0, 100.0)); + assert!(t.first.is_some()); + t.history_moved(); + assert!(t.first.is_none() && t.overlays(&cx).is_empty()); + } + + #[test] + fn a_dropped_press_undoes_only_what_it_did() { + let d = doc(); + let (sel, p) = (Selection::default(), paint()); + let cx = cx(&d, &sel, &p); + let mut t = TangentCircleTool::default(); + // A press on the second segment, dropped: nothing drawn, and the first segment stays. + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Up, 150.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Down, 200.0, 139.0)); + assert!(t.busy()); + assert!(t.drop_press(&cx).is_empty()); + assert!(t.pointer(&cx, &ev(PointerKind::Up, 200.0, 139.0)).is_empty(), "the release that follows draws nothing"); + assert!(t.first.is_some() && !t.busy()); + // The next click there draws the circle. + t.pointer(&cx, &ev(PointerKind::Down, 200.0, 139.0)); + let released = t.pointer(&cx, &ev(PointerKind::Up, 200.0, 139.0)); + assert!(close(drawn(&released), (130.0, 100.0, 40.0, 40.0)), "{released:?}"); + t.notify(&cx, DRAWN); + // A press that picked the first segment, dropped: no segment stays picked. + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 101.0)); + assert!(t.drop_press(&cx).is_empty()); + t.pointer(&cx, &ev(PointerKind::Up, 150.0, 101.0)); + assert!(t.first.is_none()); + // A dropped press that picked nothing leaves the first segment picked. + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Up, 150.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Down, 50.0, 50.0)); + assert!(t.drop_press(&cx).is_empty()); + t.pointer(&cx, &ev(PointerKind::Up, 50.0, 50.0)); + assert!(t.first.is_some()); + } + + #[test] + fn a_circle_the_three_points_cannot_draw_keeps_the_first_segment() { + // A circle the geometry found, moved to (x, 0) and given radius `r`. + let line = |y: f64| CubicBez::new(Point::new(0.0, y), Point::new(30.0, y), Point::new(60.0, y), Point::new(90.0, y)); + let found = circles_of_radius(line(0.0), &[line(40.0)], 20.0); + let circle = |x: f64, r: f64| { + let mut c = found[0]; + (c.circle.center, c.circle.radius, c.first, c.second) = (Point::new(x, 0.0), r, Point::new(x, -r), Point::new(x, r)); + c + }; + assert!(draw(&circle(100.0, 20.0), 1e-3).is_some()); + // At 10⁹ pt from the origin, where coordinates step by about 1.2e-7 pt, a radius of 5e-8 pt + // rounds the three points onto one line. + assert!(draw(&circle(1e9, 5e-8), 1e-3).is_none()); + // The preview leaves such a circle out, even nearest the pointer: no red circle for a click + // that draws nothing. + let at = Point::new(1e9, 0.0); + assert_eq!(nearest_to(vec![circle(1e9, 5e-8), circle(100.0, 20.0)], at, 1e-3), Some(circle(100.0, 20.0))); + assert_eq!(nearest_to(vec![circle(1e9, 5e-8)], at, 1e-3), None); + let d = doc(); + let (sel, p) = (Selection::default(), paint()); + let cx = cx(&d, &sel, &p); + let mut t = TangentCircleTool::default(); + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Up, 150.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Down, 200.0, 139.0)); + t.found = Some(circle(1e9, 5e-8)); + assert!(t.pointer(&cx, &ev(PointerKind::Up, 200.0, 139.0)).is_empty(), "nothing drawn"); + assert!(t.first.is_some(), "the first segment stays for another try"); + // A huge circle (segments 10³⁰ pt apart) shows with a few dozen segments, not millions. + t.found = Some(circle(0.0, 1e30)); + let segments: Vec = t + .overlays(&cx) + .iter() + .filter_map(|o| match o { + Overlay::Path { path, color, .. } if *color == RED => Some(path.elements().len()), + _ => None, + }) + .collect(); + assert!(matches!(segments[..], [n] if n < 100), "{segments:?}"); + } +} diff --git a/crates/tools/src/catalog.rs b/crates/tools/src/catalog.rs index cd6cbf627a..9397a79961 100644 --- a/crates/tools/src/catalog.rs +++ b/crates/tools/src/catalog.rs @@ -57,6 +57,7 @@ pub const TOOL_GROUPS: &[&[ToolInfo]] = &[ 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(crate::curvature_circle::ID, "Curvature Circle Tool", None, "tool-curvature-circle"), t("polygon", "Polygon Tool", None, "tool-polygon"), t("star", "Star Tool", None, "tool-star"), t("flare", "Flare Tool", None, "tool-flare"), @@ -154,6 +155,48 @@ pub fn tool_info(id: &str) -> Option<&'static ToolInfo> { all_tools().find(|t| t.id == id) } +/// One sentence on what each tool does, by tool id, for the tool card that General › Show Tool Cards +/// shows on hover. +const DESCRIPTIONS: &[(&str, &str)] = &[ + ("selection", "Selects whole objects and groups to move, resize or rotate them."), + ("directSelection", "Selects anchor points and path segments to reshape a path."), + ("pen", "Draws paths point by point, with straight segments and smooth curves."), + ("curvature", "Draws smooth curves through the points you click."), + ("type", "Adds text at a point, or in a frame you drag."), + ("rectangle", "Draws rectangles and squares."), + ("roundedRectangle", "Draws rectangles with rounded corners."), + ("ellipse", "Draws ellipses and circles."), + ("polygon", "Draws polygons with sides of equal length."), + ("star", "Draws stars."), + ("rotate", "Turns objects around a reference point."), + ("reflect", "Flips objects across an axis through a reference point."), + ("scale", "Resizes objects from a reference point."), + ("shear", "Slants objects from a reference point."), + ("hand", "Moves the view of the document."), + ("zoom", "Magnifies or reduces the view."), + ("eyedropper", "Copies the color and other attributes of one object to the selection."), + ("gradient", "Sets the direction and length of a gradient."), + ("artboard", "Creates, selects and resizes artboards."), + ("width", "Changes the width of a stroke along its length."), + ("puppetWarp", "Bends art by dragging pins placed on it."), + ("warp", "Pushes the outlines of paths in the direction you drag."), + ("twirl", "Twists the outlines of paths into swirls."), + ("pucker", "Pulls the outlines of paths in toward the brush."), + ("bloat", "Pushes the outlines of paths out from the brush."), + ("scallop", "Adds curved details along the outlines of paths."), + ("crystallize", "Adds spiky details along the outlines of paths."), + ("wrinkle", "Adds wrinkles along the outlines of paths."), + ("perspectiveSelection", "Moves, copies and resizes objects on the perspective grid."), + ("blend", "Makes a series of steps between two or more objects."), + ("dimension", "Places dimension lines that show measured lengths."), +]; + +/// One sentence on what the tool does, for its tool card; none for a tool without one, which keeps +/// its one-line tool tip. +pub fn tool_description(id: &str) -> Option<&'static str> { + DESCRIPTIONS.iter().find(|(tool, _)| *tool == id).map(|&(_, text)| text) +} + /// Tool for a single-key shortcut such as "V" or "Shift+M". pub fn tool_for_shortcut(s: &str) -> Option<&'static ToolInfo> { all_tools().find(|t| t.shortcut == Some(s)) @@ -202,4 +245,15 @@ mod tests { assert!(is_selection_tool("groupSelection") && !is_selection_tool("pen")); assert!(edits_anchors("pen") && !edits_anchors("rectangle")); } + + #[test] + fn descriptions_belong_to_tools() { + for (i, (id, text)) in DESCRIPTIONS.iter().enumerate() { + assert!(tool_info(id).is_some(), "{id} is not a tool id"); + assert!(DESCRIPTIONS[..i].iter().all(|(other, _)| other != id), "{id} is described twice"); + assert_eq!(tool_description(id), Some(*text)); + } + assert_eq!(tool_description("nonsense"), None); + assert_eq!(tool_description("slice"), None); + } } diff --git a/crates/tools/src/circle.rs b/crates/tools/src/circle.rs index 9e467b35d6..40f52290f4 100644 --- a/crates/tools/src/circle.rs +++ b/crates/tools/src/circle.rs @@ -8,7 +8,8 @@ //! 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 +//! step. A press let go within 2 screen points of where it was pressed is a click, also after a +//! drag. 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 @@ -137,10 +138,11 @@ impl CircleTool { vec![Action::Exec(c, v)] } - /// Is the press a drag at `ev`: dragged already, or `ev` is [`DRAG_PX`] or more from the press? + /// Is the press let go at `ev` a drag: is `ev` [`DRAG_PX`] or more from the press? A release + /// nearer the press is a click, also after a drag that came back to it. fn drags(&self, cx: &ToolContext, ev: &PointerEvent) -> bool { match self.press { - Some(Press::First { from, dragged, .. } | Press::Second { from, dragged, .. }) => dragged || ev.pos.distance(from) >= cx.tol(DRAG_PX), + Some(Press::First { from, .. } | Press::Second { from, .. }) => ev.pos.distance(from) >= cx.tol(DRAG_PX), None => false, } } @@ -156,9 +158,27 @@ impl Tool for CircleTool { 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 }); + // click, or a release within DRAG_PX of the press (also after a drag), keeps the points of + // the press. + if ev.kind == PointerKind::Up { + if self.drags(cx, ev) { + self.pointer(cx, &PointerEvent { kind: PointerKind::Drag, ..*ev }); + } else if let Some(press) = &mut self.press { + let (at, on_first) = match press { + Press::First { at, dragged, .. } => { + *dragged = false; + (*at, false) + } + Press::Second { at, on_first, dragged, .. } => { + *dragged = false; + (*at, *on_first) + } + }; + // A click on the first point places nothing: the pointer goes back to that point, so + // the tool shows no circle. + self.pointer = if on_first { self.first } else { Some(at) }; + self.snap.clear(); + } } match ev.kind { PointerKind::Move => { diff --git a/crates/tools/src/circle/tests.rs b/crates/tools/src/circle/tests.rs index e262d242ef..9d68bdbe27 100644 --- a/crates/tools/src/circle/tests.rs +++ b/crates/tools/src/circle/tests.rs @@ -120,6 +120,69 @@ fn a_drag_ends_where_it_is_let_go() { assert_eq!(t.pointer(&cx, &ev(up, (381.0, 360.0), Mods::default())), circle(&[(300.0, 300.0), (380.0, 360.0)])); } +/// A release within 2 screen points of the press is a click also after a drag that came back to +/// it: a second press draws the circle on the diameter to the press, a press on the first point +/// places nothing, and a first press places the first point. +#[test] +fn a_release_near_the_press_is_a_click_after_a_drag() { + 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!(drag(&mut t, &cx, (380.0, 300.0), &[(300.0, 360.0), (381.0, 300.0)], Mods::default()), circle(&[(300.0, 300.0), (380.0, 300.0)])); + click(&mut t, &cx, (300.0, 300.0)); + assert_eq!(drag(&mut t, &cx, (300.0, 300.0), &[(300.0, 380.0), (301.0, 300.0)], Mods::default()), vec![]); + assert!(t.ends_on_escape(&cx), "the first point stays"); + assert_eq!(click(&mut t, &cx, (380.0, 360.0)), circle(&[(300.0, 300.0), (380.0, 360.0)])); + assert_eq!(drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 300.0), (301.0, 300.0)], Mods::default()), vec![]); + assert!(t.ends_on_escape(&cx), "the press placed the first point"); + assert_eq!(click(&mut t, &cx, (380.0, 360.0)), circle(&[(300.0, 300.0), (380.0, 360.0)])); + // Let go near the press straight from far away, the tool shows no circle to the last drag. + t.pointer(&cx, &ev(PointerKind::Down, (300.0, 300.0), Mods::default())); + t.pointer(&cx, &ev(PointerKind::Drag, (380.0, 300.0), Mods::default())); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (301.0, 300.0), Mods::default())), vec![]); + assert_eq!(preview(&t.overlays(&cx)), None); + t.pointer(&cx, &ev(PointerKind::Down, (300.0, 300.0), Mods::default())); + t.pointer(&cx, &ev(PointerKind::Drag, (300.0, 380.0), Mods::default())); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (301.0, 300.0), Mods::default())), vec![]); + assert_eq!(preview(&t.overlays(&cx)), None); + assert!(t.ends_on_escape(&cx)); +} + +/// A click within 3 screen points of the first point, also one dragged away and let go where it +/// was pressed, places nothing and leaves no circle shown. +#[test] +fn a_click_near_the_first_point_shows_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, (300.0, 300.0)); + assert_eq!(drag(&mut t, &cx, (302.0, 300.0), &[(302.0, 380.0), (302.0, 300.0)], Mods::default()), vec![]); + assert_eq!(preview(&t.overlays(&cx)), None); + assert_eq!(click(&mut t, &cx, (302.0, 300.0)), vec![]); + assert_eq!(preview(&t.overlays(&cx)), None); + assert!(t.ends_on_escape(&cx), "the first point stays"); + assert_eq!(click(&mut t, &cx, (380.0, 360.0)), circle(&[(300.0, 300.0), (380.0, 360.0)])); +} + +/// A press on the first point, dragged to snap to the rectangle's corner anchor and let go near +/// the press, leaves no guides of the drag. +#[test] +fn a_release_near_the_press_hides_the_guides_of_the_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, 300.0)); + t.pointer(&cx, &ev(PointerKind::Down, (300.0, 300.0), Mods::default())); + t.pointer(&cx, &ev(PointerKind::Drag, (201.0, 201.0), Mods::default())); + assert!(!t.snap.guides().is_empty(), "the drag snapped to the corner anchor"); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (301.0, 300.0), Mods::default())), vec![]); + assert!(t.snap.guides().is_empty(), "{:?}", t.snap.guides()); +} + /// 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] diff --git a/crates/tools/src/context.rs b/crates/tools/src/context.rs index 0946ad7a2d..ae37c05465 100644 --- a/crates/tools/src/context.rs +++ b/crates/tools/src/context.rs @@ -222,6 +222,10 @@ pub struct ToolContext<'a> { pub glyph_snap: GlyphSnap, /// View → Show Corner Widget: paths show draggable Live Corners widgets in their corners. pub corner_widgets: bool, + /// The Control bar's Show Shape Widgets: selected live shapes show their corner, pie and side + /// widgets to the Selection tool and the shape tools. Direct Selection's corner widgets follow + /// [`Self::corner_widgets`] alone. + pub shape_widgets: bool, /// Which paint proxy is in front (true = Fill): the one the Gradient tool edits. pub fill_active: bool, /// The selected gradient stop (`gradient.selectStop`), marked on the gradient annotator. @@ -350,6 +354,10 @@ pub struct ToolContext<'a> { /// The objects of the Global Edit in progress (Select › Start Global Edit), the one it started /// from first, each with its transform; empty while Global Edit is off. pub global_edit: &'a [(NodeId, vectorcraft_geom::Affine)], + /// While an interaction is in progress: the document as it was when the interaction began, + /// which each preview of the interaction replaces the document with before it applies. None + /// outside an interaction. + pub interaction_doc: Option<&'a Document>, } impl ToolContext<'_> { diff --git a/crates/tools/src/corners.rs b/crates/tools/src/corners.rs index c60c6a7487..ab234cf507 100644 --- a/crates/tools/src/corners.rs +++ b/crates/tools/src/corners.rs @@ -132,9 +132,11 @@ impl CornerWidgets { Self::of(doc, selection, zoom, any_path)?.within_angle(max_angle) } - /// The widgets the active tool can drag (Direct Selection: `any_path`). + /// The widgets the active tool can drag (Direct Selection: `any_path`). The live shapes' widgets + /// of the other tools also need Show Shape Widgets. pub fn for_tool(cx: &ToolContext, any_path: bool) -> Option { - Self::showing(cx.doc, cx.selection, cx.zoom, any_path, cx.corner_widgets, cx.corner_widget_max_angle) + let on = cx.corner_widgets && (any_path || cx.shape_widgets); + Self::showing(cx.doc, cx.selection, cx.zoom, any_path, on, cx.corner_widget_max_angle) } /// The centres of the widgets that show. diff --git a/crates/tools/src/corners/tests.rs b/crates/tools/src/corners/tests.rs index e555782d12..21b240b453 100644 --- a/crates/tools/src/corners/tests.rs +++ b/crates/tools/src/corners/tests.rs @@ -406,6 +406,28 @@ fn widgets_off_or_elsewhere_keep_the_tools_behaviour() { assert_eq!(a[0], Action::Begin("Move".into())); } +/// With Show Shape Widgets off, a live rectangle's widgets hide from the Selection tool and the +/// shape tools, and a drag from one moves the object; Direct Selection still shows and drags them +/// while Show Corner Widget is on. +#[test] +fn hidden_shape_widgets_leave_direct_selections_corners() { + let (d, id) = live_rect(0.0, Affine::translate((100.0, 100.0))); + let s = selected(id); + let p = paint(); + let c = ToolContext { shape_widgets: false, ..cx(&d, &s, &p) }; + let at = Point::new(110.0, 110.0); + assert!(CornerWidgets::for_tool(&c, false).is_none()); + assert!(!over_widget(&c, at, false) && double_click(&c, at, false).is_none()); + assert!(CornerWidgets::for_tool(&c, true).is_some_and(|w| w.visible().count() == 4)); + assert!(over_widget(&c, at, true)); + let mut t = crate::create("selection"); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, at.x, at.y)); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 130.0, 110.0))[0], Action::Begin("Move".into())); + // Show Corner Widget off hides Direct Selection's too. + let off = ToolContext { corner_widgets: false, ..c }; + assert!(CornerWidgets::for_tool(&off, true).is_none()); +} + /// #511: Direct Selection shows a widget in each of a star's ten corners (the Selection tool /// none: a star isn't a live shape); dragging a tip's inward rounds them all as one step. #[test] diff --git a/crates/tools/src/curvature_circle.rs b/crates/tools/src/curvature_circle.rs new file mode 100644 index 0000000000..b484651181 --- /dev/null +++ b/crates/tools/src/curvature_circle.rs @@ -0,0 +1,242 @@ +//! The Curvature Circle tool draws the circle that touches a path at a point and bends as the path +//! bends there (`shape.curvatureCircle`). +//! +//! The pointer snaps to the nearest path within 5 screen points, or within Smart Guides › Snapping +//! Tolerance when that is larger, and the tool shows the circle that matches the path there: a +//! dashed outline (solid once it is more than 50,000 screen points around), its center as a small +//! cross, a line from the center to the point it touches and, with Measurement Labels on, its +//! radius by the pointer, with an asterisk when the segment is the usual cubic of a circular arc +//! of 90° or less and the circle has the arc's own radius. A click draws it, in one undo step, and a +//! press dragged 2 screen points or more, or canceled with Escape, draws nothing. The circle goes on +//! the side the path bends toward; with Shift held at the press, on the other side. On a straight +//! stretch, at a cusp, at a corner, or where the circle would reach past the canvas, the pointer +//! shows "Straight segment", "Cusp", "Corner" or "Circle too large" instead, and a click draws +//! nothing. The pointer passes over the circles the tool drew until another tool is chosen or an +//! edit, Undo or Redo is made outside the tool. + +use std::collections::HashSet; + +use serde_json::json; +use vectorcraft_doc::{MAX_COORD, NodeId}; +use vectorcraft_geom::curvature::{CurvatureCircle, NoCircle, curvature_circle_on}; +use vectorcraft_geom::{Point, Rect, Vec2, shapes}; + +use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; + +pub const ID: &str = "curvatureCircle"; + +/// How near (screen points) a path pulls the pointer, unless the Smart Guides' snapping tolerance +/// is larger. +const SNAP_PX: f64 = 5.0; +/// 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; +/// The longest outline (screen points) the preview draws dashed, about 7,000 dashes. +const DASHED_PX: f64 = 50_000.0; + +/// The point of a path the pointer snapped to: the path, subpath, segment and `t` on it. +#[derive(Clone, Copy, Debug, PartialEq)] +struct Hit { + id: NodeId, + subpath: usize, + segment: usize, + t: f64, +} + +/// What the tool shows at a hit. +enum Found { + Circle(CurvatureCircle), + /// The pointer's text, and where the path is. + Refused(&'static str, Point), +} + +#[derive(Default)] +pub struct CurvatureCircleTool { + /// The point under the pointer, and whether Shift was held. + hover: Option<(Hit, bool)>, + /// The press in progress, where the pointer was pressed: what a release draws. + press: Option<(Hit, bool)>, + from: Point, + /// The circles the tool drew since the history last moved outside it. + drawn: HashSet, +} + +/// The nearest point within reach of `p` on the paths a click can pick, guides and the paths in +/// `skip` left out; of paths at the same distance, a selected one, then the one on top. +fn hit_at(cx: &ToolContext, p: Point, skip: &HashSet) -> Option { + let tol = cx.tol(SNAP_PX).max(cx.snap_tol()); + let mut best: Option<(Hit, f64)> = None; + for id in crate::draw2::candidate_paths(cx) { + if skip.contains(&id) { + continue; + } + let Some(pd) = cx.doc.node(id).filter(|n| !n.is_guide()).and_then(|n| n.path_data()) else { continue }; + // A path whose control points' box lies out of reach holds no point within reach. + if pd.control_bounds().is_none_or(|b| !b.inflate(tol, tol).contains(p)) { + continue; + } + if let Some((subpath, segment, t, _, d)) = pd.nearest(p) + && d <= tol + && best.is_none_or(|(_, b)| d < b) + { + best = Some((Hit { id, subpath, segment, t }, d)); + } + } + best.map(|(hit, _)| hit) +} + +/// The circle at `hit` as `shape.curvatureCircle` draws it, or why it draws none; `None` when the +/// path or segment is gone. +fn found(cx: &ToolContext, hit: Hit, convex: bool) -> Option { + let sp = cx.doc.node(hit.id)?.path_data()?.subpaths.get(hit.subpath)?; + if hit.segment >= sp.segment_count() { + return None; + } + let at = vectorcraft_geom::ParamCurve::eval(&sp.segment(hit.segment), hit.t); + Some(match curvature_circle_on(sp, hit.segment, hit.t, convex) { + Ok(c) if on_canvas(&c) => Found::Circle(c), + Ok(_) => Found::Refused("Circle too large", at), + Err(NoCircle::Straight) => Found::Refused("Straight segment", at), + Err(NoCircle::Cusp) => Found::Refused("Cusp", at), + Err(NoCircle::Corner) => Found::Refused("Corner", at), + }) +} + +/// Does the circle stay on the canvas? +fn on_canvas(c: &CurvatureCircle) -> bool { + let (p, r) = (c.center, c.radius); + [p.x - r, p.y - r, p.x + r, p.y + r].iter().all(|v| v.abs() <= MAX_COORD) +} + +impl Tool for CurvatureCircleTool { + fn id(&self) -> &'static str { + ID + } + + fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { + if !ev.pos.is_finite() { + return vec![]; + } + match ev.kind { + PointerKind::Move => { + self.hover = hit_at(cx, ev.pos, &self.drawn).map(|h| (h, ev.mods.shift)); + vec![] + } + PointerKind::Down => { + self.press = hit_at(cx, ev.pos, &self.drawn).map(|h| (h, ev.mods.shift)); + self.hover = self.press; + self.from = ev.pos; + vec![] + } + // A drag is not a click: the release draws nothing. + PointerKind::Drag => { + if ev.pos.distance(self.from) >= cx.tol(DRAG_PX) { + self.press = None; + self.hover = None; + } + vec![] + } + PointerKind::Up => { + let press = self.press.take(); + self.hover = hit_at(cx, ev.pos, &self.drawn).map(|h| (h, ev.mods.shift)); + let Some((hit, convex)) = press else { return vec![] }; + if ev.pos.distance(self.from) >= cx.tol(DRAG_PX) || !matches!(found(cx, hit, convex), Some(Found::Circle(_))) { + return vec![]; + } + let p = json!({"id": hit.id.0, "subpath": hit.subpath, "segment": hit.segment, "t": hit.t, "convex": convex}); + vec![Action::Exec("shape.curvatureCircle".into(), p), Action::Notify("created".into())] + } + PointerKind::DoubleClick | PointerKind::TripleClick => vec![], + } + } + + /// Escape during a press cancels it: the release draws nothing. + fn key(&mut self, _cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { + if key == ToolKey::Escape && self.press.take().is_some() { + self.hover = None; + } + vec![] + } + + fn claims_key(&self, _cx: &ToolContext, key: ToolKey) -> bool { + key == ToolKey::Escape && self.press.is_some() + } + + /// A dropped press (a second finger, a canceled touch) draws nothing. + fn drop_press(&mut self, _cx: &ToolContext) -> Vec { + self.press = None; + vec![] + } + + /// The circle shown depends on the path under the pointer, which an edit, an undo or a zoom + /// (the reach is in screen points) changes. + fn wants_rehover(&self) -> bool { + true + } + + /// The command selects the circle it drew; the tool adds it to the circles the pointer passes + /// over. + fn notify(&mut self, cx: &ToolContext, what: &str) { + if what == "created" + && let [id] = cx.selection.objects[..] + { + self.drawn.insert(id); + } + } + + fn deactivate(&mut self, _cx: &ToolContext) -> Vec { + self.hover = None; + self.press = None; + self.drawn.clear(); + vec![] + } + + fn hover_ended(&mut self, _cx: &ToolContext) { + if self.press.is_none() { + self.hover = None; + } + } + + /// An edit, Undo or Redo made outside the tool, or another document, may move or remove the + /// path under the pointer, and the pointer reaches the circles the tool drew again. + fn history_moved(&mut self) { + self.hover = None; + self.press = None; + self.drawn.clear(); + } + + fn overlays(&self, cx: &ToolContext) -> Vec { + let Some((hit, convex)) = self.hover else { return vec![] }; + let color = crate::draw2::FEEDBACK; + let mut o = vec![]; + match found(cx, hit, convex) { + Some(Found::Circle(c)) => { + let r = c.radius; + let path = shapes::ellipse(Rect::new(c.center.x - r, c.center.y - r, c.center.x + r, c.center.y + r)).to_bezpath(); + // The outline is drawn solid when it is longer than DASHED_PX on screen. + let dashed = std::f64::consts::TAU * r <= cx.tol(DASHED_PX); + o.push(Overlay::Path { path, color, width: 1.0, dashed }); + o.push(Overlay::Line { a: c.center, b: c.at, color, dashed: false }); + let arm = cx.tol(CROSS_PX); + o.push(Overlay::Line { a: c.center - Vec2::new(arm, 0.0), b: c.center + Vec2::new(arm, 0.0), color, dashed: false }); + o.push(Overlay::Line { a: c.center - Vec2::new(0.0, arm), b: c.center + Vec2::new(0.0, arm), color, dashed: false }); + o.push(Overlay::Anchor { p: c.at, color, filled: true, size: 6.0 }); + if cx.measurement_labels { + let star = if c.nominal { "*" } else { "" }; + o.push(Overlay::Measure { p: c.at + Vec2::new(cx.tol(12.0), cx.tol(12.0)), text: format!("R: {}{star}", cx.len(r)) }); + } + } + Some(Found::Refused(text, at)) => o.push(Overlay::Label { p: at, text: text.into(), color }), + None => {} + } + o + } + + fn cursor(&self, _cx: &ToolContext, _p: Point, _mods: Mods) -> Cursor { + Cursor::Crosshair + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/tools/src/curvature_circle/tests.rs b/crates/tools/src/curvature_circle/tests.rs new file mode 100644 index 0000000000..d417af58dc --- /dev/null +++ b/crates/tools/src/curvature_circle/tests.rs @@ -0,0 +1,286 @@ +use super::*; +use crate::testutil::*; +use vectorcraft_doc::{Appearance, Document, Node, Selection}; +use vectorcraft_geom::PathData; + +fn ev(kind: PointerKind, (x, y): (f64, f64), mods: Mods) -> PointerEvent { + PointerEvent::new(kind, x, y).with_mods(mods) +} + +/// A document holding `paths`, the first one on top. +fn doc_with(paths: &[PathData]) -> Document { + let mut d = Document::new(500.0, 500.0); + let l = d.layers[0].id; + for path in paths.iter().rev() { + let id = d.alloc_id(); + d.insert(Some(l), usize::MAX, Node::path(id, path.clone(), Appearance::default_art())).unwrap(); + } + d +} + +/// A circle of radius 100 centered at (200, 200). +fn circle() -> PathData { + shapes::ellipse(Rect::new(100.0, 100.0, 300.0, 300.0)) +} + +fn click(t: &mut CurvatureCircleTool, cx: &ToolContext, p: (f64, f64), mods: Mods) -> Vec { + let mut acts = t.pointer(cx, &ev(PointerKind::Move, p, mods)); + acts.extend(t.pointer(cx, &ev(PointerKind::Down, p, mods))); + acts.extend(t.pointer(cx, &ev(PointerKind::Up, p, mods))); + acts +} + +/// The one command `acts` runs, followed by the tool's notice that it drew: the command's params. +fn params(acts: &[Action]) -> serde_json::Value { + let [Action::Exec(c, v), Action::Notify(what)] = acts else { panic!("one command: {acts:?}") }; + assert_eq!(c, "shape.curvatureCircle"); + assert_eq!(what, "created"); + v.clone() +} + +/// 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) +} + +fn label(o: &[Overlay]) -> Option { + o.iter().find_map(|o| match o { + Overlay::Label { text, .. } => Some(text.clone()), + _ => None, + }) +} + +/// Over a circle, the tool shows the circle itself, its center, the radius to the point it touches +/// and "R: 100 pt*" (an arc's own radius); a click draws it on the point of the path nearest the +/// pointer. +#[test] +fn a_click_on_a_circle_draws_the_circle_that_matches_it() { + let d = doc_with(&[circle()]); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CurvatureCircleTool::default(); + t.pointer(&cx, &ev(PointerKind::Move, (302.0, 200.0), Mods::default())); + let o = t.overlays(&cx); + assert!(near(preview(&o).expect("the circle is shown"), Rect::new(100.0, 100.0, 300.0, 300.0)), "{o:?}"); + let center = Point::new(200.0, 200.0); + assert!(o.iter().any(|o| matches!(o, Overlay::Line { a, b, .. } if *a == center && b.distance(Point::new(300.0, 200.0)) < 1e-9)), "{o:?}"); + assert!(o.iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text.starts_with("R: 100") && text.ends_with('*'))), "{o:?}"); + let without_labels = ToolContext { measurement_labels: false, ..cx }; + assert!(!t.overlays(&without_labels).iter().any(|o| matches!(o, Overlay::Measure { .. }))); + let v = params(&click(&mut t, &cx, (302.0, 200.0), Mods::default())); + assert_eq!(v["convex"], json!(false)); + let id = d.layers[0].children().unwrap()[0].id; + assert_eq!(v["id"], json!(id.0)); + let sp = &d.node(id).unwrap().path_data().unwrap().subpaths[0]; + let seg = sp.segment(v["segment"].as_u64().unwrap() as usize); + let at = vectorcraft_geom::ParamCurve::eval(&seg, v["t"].as_f64().unwrap()); + assert!(at.distance(Point::new(300.0, 200.0)) < 1e-6, "{v}"); +} + +/// Shift held at the press puts the circle on the other side of the path, and the preview follows +/// Shift too. +#[test] +fn shift_puts_the_circle_on_the_other_side() { + let d = doc_with(&[circle()]); + 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 = CurvatureCircleTool::default(); + t.pointer(&cx, &ev(PointerKind::Move, (300.0, 200.0), shift)); + assert!(near(preview(&t.overlays(&cx)).expect("the circle is shown"), Rect::new(300.0, 100.0, 500.0, 300.0)), "{:?}", t.overlays(&cx)); + assert_eq!(params(&click(&mut t, &cx, (300.0, 200.0), shift))["convex"], json!(true)); +} + +/// On a straight segment the pointer shows "Straight segment", at a cusp "Cusp", at a corner +/// anchor "Corner", and where the circle would reach past the canvas "Circle too large"; a click +/// there draws nothing. +#[test] +fn straight_segments_cusps_and_huge_circles_are_refused() { + let line = PathData::from_bezpath(&vectorcraft_geom::BezPath::from_svg("M0 400 L400 400").unwrap()); + // A handle drawn back onto its anchor at (0, 0). + let cusp = PathData::from_bezpath(&vectorcraft_geom::BezPath::from_svg("M0 0 C0 0 60 40 100 0").unwrap()); + let gentle = PathData::from_bezpath(&vectorcraft_geom::BezPath::from_svg("M0 450 C100 450.0000001 200 450.0000001 300 450").unwrap()); + // A curve that meets a line at a corner anchor (150, 250). + let corner = PathData::from_bezpath(&vectorcraft_geom::BezPath::from_svg("M0 250 C50 200 100 200 150 250 L300 250").unwrap()); + let d = doc_with(&[line, cusp, gentle, corner]); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CurvatureCircleTool::default(); + let refused = [((200.0, 401.0), "Straight segment"), ((-1.0, -1.0), "Cusp"), ((150.0, 251.0), "Corner"), ((150.0, 451.0), "Circle too large")]; + for (at, want) in refused { + t.pointer(&cx, &ev(PointerKind::Move, at, Mods::default())); + let o = t.overlays(&cx); + assert_eq!(label(&o).as_deref(), Some(want), "{o:?}"); + assert_eq!(preview(&o), None); + assert_eq!(click(&mut t, &cx, at, Mods::default()), vec![], "{want}"); + } +} + +/// Away from every path the tool shows nothing and a click draws nothing; the pointer reaches a +/// path within 5 screen points, so at 200% within 2.5 pt. +#[test] +fn the_pointer_reaches_a_path_within_5_screen_points() { + let d = doc_with(&[circle()]); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, snapping_tolerance: 0.0, ..cx(&d, &s, &p) }; + let mut t = CurvatureCircleTool::default(); + assert_eq!(click(&mut t, &cx, (200.0, 200.0), Mods::default()), vec![]); + assert!(t.overlays(&cx).is_empty()); + assert_eq!(click(&mut t, &cx, (306.0, 200.0), Mods::default()), vec![]); + assert_eq!(click(&mut t, &cx, (304.0, 200.0), Mods::default()).len(), 2); + let zoomed = ToolContext { zoom: 2.0, ..cx }; + assert_eq!(click(&mut t, &zoomed, (303.0, 200.0), Mods::default()), vec![]); + assert_eq!(click(&mut t, &zoomed, (302.0, 200.0), Mods::default()).len(), 2); + // A larger snapping tolerance reaches farther, with Smart Guides off or on. + for smart_guides in [false, true] { + let wide = ToolContext { snapping_tolerance: 10.0, smart_guides, ..cx }; + assert_eq!(click(&mut t, &wide, (309.0, 200.0), Mods::default()).len(), 2, "{smart_guides}"); + assert_eq!(click(&mut t, &wide, (311.0, 200.0), Mods::default()), vec![], "{smart_guides}"); + } +} + +/// Of two paths within reach, the nearer one is used, even when the other one is selected: a +/// selected circle 4 pt from the pointer loses to a circle under it. +#[test] +fn the_nearest_path_wins_over_a_selected_one() { + let far = shapes::ellipse(Rect::new(104.0, 100.0, 304.0, 300.0)); + let d = doc_with(&[circle(), far]); + let ids: Vec = d.layers[0].children().unwrap().iter().map(|n| n.id).collect(); + let far_id = *ids.iter().find(|id| d.node(**id).unwrap().path_data().unwrap().bounds().unwrap().x0 > 100.5).unwrap(); + let s = Selection { objects: vec![far_id], ..Selection::default() }; + let p = paint(); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CurvatureCircleTool::default(); + let v = params(&click(&mut t, &cx, (300.0, 200.0), Mods::default())); + assert_ne!(v["id"], json!(far_id.0), "{v}"); +} + +/// A guide is not a path the tool draws from, even when it is selected. +#[test] +fn a_selected_guide_is_left_out() { + let mut d = doc_with(&[circle()]); + let id = d.layers[0].children().unwrap()[0].id; + if let Some(vectorcraft_doc::NodeKind::Path { guide, .. }) = d.node_mut(id).map(|n| &mut n.kind) { + *guide = true; + } + let s = Selection { objects: vec![id], ..Selection::default() }; + let p = paint(); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CurvatureCircleTool::default(); + assert_eq!(click(&mut t, &cx, (300.0, 200.0), Mods::default()), vec![]); + assert!(t.overlays(&cx).is_empty()); +} + +/// After a click on a circle drawn with the Ellipse tool, the next hover and click pass over the +/// circle the tool drew (selected and on top of it) and use the circle under it again, until an +/// edit made outside the tool. +#[test] +fn the_next_click_passes_over_the_circle_just_drawn() { + let d = doc_with(&[circle(), circle()]); + let ids: Vec = d.layers[0].children().unwrap().iter().rev().map(|n| n.id).collect(); + let (drawn, under) = (ids[0], ids[1]); + let s = Selection { objects: vec![drawn], ..Selection::default() }; + let p = paint(); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CurvatureCircleTool::default(); + t.notify(&cx, "created"); + t.pointer(&cx, &ev(PointerKind::Move, (302.0, 200.0), Mods::default())); + assert_eq!(t.hover.map(|(h, _)| h.id), Some(under)); + assert_eq!(params(&click(&mut t, &cx, (302.0, 200.0), Mods::default()))["id"], json!(under.0)); + t.history_moved(); + assert_eq!(params(&click(&mut t, &cx, (302.0, 200.0), Mods::default()))["id"], json!(drawn.0)); +} + +/// A press that a second finger or a canceled touch drops draws nothing on the release, and an +/// edit made outside the tool drops what the pointer was over. +#[test] +fn a_dropped_press_and_an_outside_edit_draw_nothing() { + let d = doc_with(&[circle()]); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CurvatureCircleTool::default(); + t.pointer(&cx, &ev(PointerKind::Down, (300.0, 200.0), Mods::default())); + t.drop_press(&cx); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (300.0, 200.0), Mods::default())), vec![]); + t.pointer(&cx, &ev(PointerKind::Move, (300.0, 200.0), Mods::default())); + t.history_moved(); + assert!(t.overlays(&cx).is_empty()); +} + +/// Escape during a press cancels it, and the tool takes Escape only while a press is held; the +/// tool asks to be hovered again after an edit or a zoom. +#[test] +fn escape_cancels_a_press() { + let d = doc_with(&[circle()]); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CurvatureCircleTool::default(); + assert!(!t.claims_key(&cx, ToolKey::Escape)); + t.pointer(&cx, &ev(PointerKind::Down, (300.0, 200.0), Mods::default())); + assert!(t.claims_key(&cx, ToolKey::Escape)); + t.key(&cx, ToolKey::Escape, Mods::default()); + assert!(t.overlays(&cx).is_empty()); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (300.0, 200.0), Mods::default())), vec![]); + assert!(t.wants_rehover()); +} + +/// The preview of a circle more than 50,000 screen points around is drawn solid; a smaller one is +/// dashed. +#[test] +fn a_huge_preview_is_drawn_solid() { + let big = shapes::ellipse(Rect::new(-10_000.0, -10_000.0, 10_000.0, 10_000.0)); + let d = doc_with(&[big]); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CurvatureCircleTool::default(); + t.pointer(&cx, &ev(PointerKind::Move, (10_001.0, 0.0), 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:?}"); +} + +/// A press dragged 2 screen points or more is not a click and draws nothing; a press that moves +/// less still draws the circle. +#[test] +fn a_drag_draws_nothing() { + let d = doc_with(&[circle()]); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CurvatureCircleTool::default(); + let press = |t: &mut CurvatureCircleTool, to: (f64, f64)| { + t.pointer(&cx, &ev(PointerKind::Down, (300.0, 200.0), Mods::default())); + t.pointer(&cx, &ev(PointerKind::Drag, to, Mods::default())); + t.pointer(&cx, &ev(PointerKind::Up, to, Mods::default())) + }; + assert_eq!(press(&mut t, (300.0, 230.0)), vec![]); + // The circle at the press is not shown once the press is a drag; at a release away from every + // path nothing is shown. + t.pointer(&cx, &ev(PointerKind::Down, (300.0, 200.0), Mods::default())); + t.pointer(&cx, &ev(PointerKind::Drag, (250.0, 200.0), Mods::default())); + assert!(t.overlays(&cx).is_empty()); + t.pointer(&cx, &ev(PointerKind::Up, (250.0, 200.0), Mods::default())); + assert!(t.overlays(&cx).is_empty()); + assert_eq!(press(&mut t, (300.0, 202.0)), vec![]); + assert_eq!(press(&mut t, (300.0, 201.0)).len(), 2); + // A release that far away with no drag before it is not a click either. + t.pointer(&cx, &ev(PointerKind::Down, (300.0, 200.0), Mods::default())); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (300.0, 230.0), Mods::default())), vec![]); +} + +/// The tool is in the Ellipse tool's group, after the Circle tool. +#[test] +fn the_curvature_circle_tool_follows_the_circle_tool() { + let tool = crate::create(ID); + assert_eq!(tool.id(), ID); + let group = crate::catalog::group_of(ID).unwrap(); + let ids: Vec<&str> = crate::TOOL_GROUPS[group].iter().map(|t| t.id).collect(); + let circle = ids.iter().position(|id| *id == crate::circle::ID).unwrap(); + assert_eq!(ids.get(circle + 1), Some(&ID)); +} diff --git a/crates/tools/src/dimension.rs b/crates/tools/src/dimension.rs index 894e75ed3d..5e2e179bdf 100644 --- a/crates/tools/src/dimension.rs +++ b/crates/tools/src/dimension.rs @@ -88,9 +88,17 @@ pub struct DimensionTool { /// While a Linear dimension is placed with its line on the level of another dimension's line: /// the ends of that other line. A Smart Guide runs along the level across both lines. level_guide: Option<(Point, Point)>, - /// While a dimension is placed: the lines of the visible, unlocked linear dimensions in the - /// document before its first preview ([`dimension_lines`]), which its line can line up with. + /// While a linear dimension is placed: the lines of the visible, unlocked linear dimensions in + /// the document ([`dimension_lines`]), which its line can line up with while Smart Guides are + /// on. With Smart Guides on, they are read again when the document they come from has changed. levels: Vec, + /// Which document `levels` were read from: the open document's id and revision, or, while an + /// interaction is in progress, the open document's id and the address of the document the + /// interaction began with. + levels_at: (u64, u64, usize), + /// The document's next object id at the dimension's first preview: the id its preview takes + /// (`dimension.create` gives the dimension the next id). The preview is not a level. + preview_id: u64, } /// What a linear dimension between `a` and `b` measures with the pointer at `p` while it is @@ -439,6 +447,9 @@ fn on_dimensions(cx: &ToolContext, p: Point) -> Option<(Point, bool)> { } } for c in n.children().into_iter().flatten().rev() { + if *budget == 0 { + return; + } lines(c, measured, p, reach, budget, best); } } @@ -453,6 +464,9 @@ fn on_dimensions(cx: &ToolContext, p: Point) -> Option<(Point, bool)> { return; } for c in n.children().into_iter().flatten().rev() { + if *budget == 0 { + return; + } visit(c, p, reach, budget, best); } } @@ -461,6 +475,9 @@ fn on_dimensions(cx: &ToolContext, p: Point) -> Option<(Point, bool)> { } let (reach, mut budget, mut best) = ([cx.tol(ANCHOR_REACH), cx.tol(8.0)], 20_000usize, Best::default()); for n in cx.doc.layers.iter().rev() { + if budget == 0 { + break; + } visit(n, p, reach, &mut budget, &mut best); } best.end.map(|(_, q)| (q, true)).or_else(|| best.line.map(|(_, q)| (q, false))) @@ -469,11 +486,14 @@ fn on_dimensions(cx: &ToolContext, p: Point) -> Option<(Point, bool)> { /// The line of a linear dimension already drawn: its ends and its direction. type DimensionLine = ((Point, Point), Vec2); -/// The lines of the visible, unlocked linear dimensions in the document. Bounded work, as in -/// [`on_dimensions`]. -fn dimension_lines(cx: &ToolContext) -> Vec { - fn visit(n: &Node, budget: &mut usize, out: &mut Vec) { - if *budget == 0 || !n.visible || n.locked { +/// The lines of the visible, unlocked linear dimensions in `doc`, except the preview of the +/// dimension being placed: a dimension with the id `preview.0` that measures the points +/// `preview.1`. Bounded work, as in [`on_dimensions`]. +fn dimension_lines(doc: &vectorcraft_doc::Document, preview: (u64, [Point; 2])) -> Vec { + fn visit(n: &Node, preview: (u64, [Point; 2]), budget: &mut usize, out: &mut Vec) { + let is_preview = n.id.0 == preview.0 + && n.extras().dimension.as_ref().is_some_and(|d| d.a.distance(preview.1[0]) < 1e-9 && d.b.distance(preview.1[1]) < 1e-9); + if *budget == 0 || !n.visible || n.locked || is_preview { return; } *budget -= 1; @@ -484,12 +504,18 @@ fn dimension_lines(cx: &ToolContext) -> Vec { return; } for c in n.children().into_iter().flatten().rev() { - visit(c, budget, out); + if *budget == 0 { + return; + } + visit(c, preview, budget, out); } } let (mut budget, mut out) = (20_000usize, vec![]); - for n in cx.doc.layers.iter().rev() { - visit(n, &mut budget, &mut out); + for n in doc.layers.iter().rev() { + if budget == 0 { + break; + } + visit(n, preview, &mut budget, &mut out); } out } @@ -725,9 +751,24 @@ impl DimensionTool { } // With Smart Guides on, a linear dimension's line lands on the level of a parallel // dimension line already drawn within the Smart Guides snapping tolerance. The lines are - // read before the first preview, so the preview of this dimension is not one of them. - if !self.began { - self.levels = dimension_lines(cx); + // read at the first preview and, with Smart Guides on, again when the document they come + // from has changed since. They come from the document the next preview applies to: while + // the interaction is in progress, the document as it began, which each preview starts + // again from, so a dimension that a command moves or hides in between, and that the next + // preview puts back, stays a level where it was, and the previews themselves do not make + // the tool read the lines again. The preview of this dimension is not one of them. + if d.mode == DimensionMode::Linear { + if !self.began { + self.preview_id = cx.doc.peek_next_id(); + } + let (from, at) = match cx.interaction_doc { + Some(began) => (began, (cx.revision.0, 0, std::ptr::from_ref(began).addr())), + None => (cx.doc, (cx.revision.0, cx.revision.1, 0)), + }; + if !self.began || (cx.smart_guides && self.levels_at != at) { + self.levels = dimension_lines(from, (self.preview_id, [d.a, d.b])); + self.levels_at = at; + } } let level = if cx.smart_guides { line_level(&self.levels, d, p, cx.snap_tol()) } else { None }; d.place(level.map_or(p, |(on_level, _)| on_level)); @@ -1092,6 +1133,219 @@ mod tests { } } + /// The lines of the dimensions in the document are read only for a linear dimension. They are + /// read with Smart Guides off too, so a line placed after Smart Guides are turned on lines up. + #[test] + fn dimension_lines_are_read_only_for_a_linear_dimension() { + use vectorcraft_doc::{Node, NodeKind}; + let (mut d, _) = doc_with_rect(); + let id = d.alloc_id(); + let mut drawn = Node::new(id, NodeKind::Group { children: vec![], clip: false }); + let pt = Point::new; + drawn.extras_mut().dimension = + Some(Box::new(DimensionTool::default().recipe(DimensionMode::Linear, pt(300.0, 300.0), pt(400.0, 300.0), pt(350.0, 300.0), None))); + let l = d.layers[0].id; + d.insert(Some(l), usize::MAX, drawn).unwrap(); + let (s, p) = (Selection::default(), paint()); + let ev = |kind, x: f64, y: f64| PointerEvent::new(kind, x, y); + let c = cx(&d, &s, &p); + let off = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = DimensionTool::default(); + for (x, y) in [(400.0, 400.0), (450.0, 400.0)] { + t.pointer(&off, &ev(PointerKind::Down, x, y)); + t.pointer(&off, &ev(PointerKind::Up, x, y)); + } + assert!(matches!(t.pointer(&off, &ev(PointerKind::Move, 420.0, 450.0)).first(), Some(Action::Begin(_)))); + assert_eq!(t.levels.len(), 1); + let acts = t.pointer(&c, &ev(PointerKind::Move, 420.0, 302.0)); + let Some(Action::Preview(_, params)) = acts.last() else { panic!("{acts:?}") }; + assert_eq!(params["offset"], json!(-100.0), "on the level of the line drawn at y = 300"); + let mut t = DimensionTool::default(); + t.set_option("mode", &json!("angular")); + t.pointer(&c, &ev(PointerKind::Down, 100.0, 100.0)); + assert!(matches!(t.pointer(&c, &ev(PointerKind::Drag, 130.0, 140.0)).first(), Some(Action::Begin(_)))); + assert!(t.levels.is_empty(), "an angular dimension reads no lines"); + // A radius (dragged outwards from a circle) and a diameter (inwards) read none either. + let circle = d.alloc_id(); + let round = vectorcraft_geom::shapes::ellipse(Rect::new(400.0, 150.0, 500.0, 250.0)); + d.insert(Some(l), usize::MAX, Node::path(circle, round, vectorcraft_doc::Appearance::default_art())).unwrap(); + let c = cx(&d, &s, &p); + for (to, mode) in [(530.0, "radius"), (470.0, "diameter")] { + let mut t = DimensionTool::default(); + t.set_option("mode", &json!("radial")); + t.pointer(&c, &ev(PointerKind::Down, 500.0, 200.0)); + let acts = t.pointer(&c, &ev(PointerKind::Drag, to, 200.0)); + assert!(matches!(acts.first(), Some(Action::Begin(_))), "{mode}: {acts:?}"); + let Some(Action::Preview(_, params)) = acts.last() else { panic!("{mode}: {acts:?}") }; + assert_eq!(params["mode"], json!(mode)); + assert!(t.levels.is_empty(), "a {mode} dimension reads no lines"); + } + } + + /// A dimension hidden, locked or deleted while another is placed is no longer a level, and one + /// shown again or grouped is: the lines are read again when the document's revision moves. The + /// preview of the dimension itself, with the id the document gave next when it began, is never + /// a level. + #[test] + fn dimension_lines_are_read_again_when_the_document_changes() { + use vectorcraft_doc::{Node, NodeKind}; + let (mut d, _) = doc_with_rect(); + let pt = Point::new; + let line = |y: f64| Some(Box::new(DimensionTool::default().recipe(DimensionMode::Linear, pt(300.0, y), pt(400.0, y), pt(350.0, y), None))); + let id = d.alloc_id(); + let mut drawn = Node::new(id, NodeKind::Group { children: vec![], clip: false }); + drawn.extras_mut().dimension = line(300.0); + let l = d.layers[0].id; + d.insert(Some(l), usize::MAX, drawn).unwrap(); + let (s, p) = (Selection::default(), paint()); + let ev = |kind, x: f64, y: f64| PointerEvent::new(kind, x, y); + let offset = |t: &mut DimensionTool, c: &ToolContext| { + let acts = t.pointer(c, &ev(PointerKind::Move, 420.0, 302.0)); + let Some(Action::Preview(_, params)) = acts.last() else { panic!("{acts:?}") }; + params["offset"].clone() + }; + let mut t = DimensionTool::default(); + let c = cx(&d, &s, &p); + for (x, y) in [(400.0, 400.0), (450.0, 400.0)] { + t.pointer(&c, &ev(PointerKind::Down, x, y)); + t.pointer(&c, &ev(PointerKind::Up, x, y)); + } + assert!(matches!(t.pointer(&c, &ev(PointerKind::Move, 420.0, 450.0)).first(), Some(Action::Begin(_)))); + assert_eq!(offset(&mut t, &c), json!(-100.0), "on the level of the line drawn at y = 300"); + // With Smart Guides off the lines are not read; turned on, they are read as they are now. + let mut hidden = d.clone(); + hidden.node_mut(id).unwrap().visible = false; + let off = ToolContext { revision: (0, 1), smart_guides: false, ..cx(&hidden, &s, &p) }; + offset(&mut t, &off); + assert_eq!(t.levels.len(), 1, "not read with Smart Guides off"); + let on = ToolContext { revision: (0, 1), ..cx(&hidden, &s, &p) }; + assert_eq!(offset(&mut t, &on), json!(-98.0), "read when Smart Guides are turned on"); + for (rev, edit) in [(1, "hidden"), (2, "locked"), (3, "deleted")] { + let mut doc = d.clone(); + match edit { + "hidden" => doc.node_mut(id).unwrap().visible = false, + "locked" => doc.node_mut(id).unwrap().locked = true, + _ => { + doc.remove(id).unwrap(); + } + } + let c = ToolContext { revision: (0, rev), ..cx(&doc, &s, &p) }; + assert_eq!(offset(&mut t, &c), json!(-98.0), "{edit}: off every level"); + } + let c = ToolContext { revision: (0, 4), ..cx(&d, &s, &p) }; + assert_eq!(offset(&mut t, &c), json!(-100.0), "shown again: on the level"); + // Grouped while it is placed, in a group with the id the preview takes: still a level. + let mut doc = d.clone(); + let moved = doc.remove(id).unwrap(); + let group = doc.alloc_id(); + doc.insert(Some(l), usize::MAX, Node::new(group, NodeKind::Group { children: vec![moved], clip: false })).unwrap(); + let c = ToolContext { revision: (0, 5), ..cx(&doc, &s, &p) }; + assert_eq!(offset(&mut t, &c), json!(-100.0), "grouped: on the level"); + // The dimension's own preview, which takes the next id and measures its points, is not a + // level. Another dimension that takes that id is. + let mut own = DimensionTool::default().recipe(DimensionMode::Linear, pt(400.0, 400.0), pt(450.0, 400.0), pt(425.0, 400.0), None); + own.place(pt(425.0, 304.0)); + assert_eq!(own.line_ends(), (pt(400.0, 304.0), pt(450.0, 304.0))); + for (rev, made, level) in [(6, Some(Box::new(own)), json!(-98.0)), (7, line(304.0), json!(-96.0))] { + let mut doc = d.clone(); + let mut preview = Node::new(doc.alloc_id(), NodeKind::Group { children: vec![], clip: false }); + preview.extras_mut().dimension = made; + doc.node_mut(id).unwrap().visible = false; + doc.insert(Some(l), usize::MAX, preview).unwrap(); + let c = ToolContext { revision: (0, rev), ..cx(&doc, &s, &p) }; + assert_eq!(offset(&mut t, &c), level, "revision {rev}"); + } + } + + /// While the interaction is in progress, the lines are read from the document it began with, + /// which the next preview starts from, not from the document a command changed in between: a + /// dimension moved or hidden there stays a level where it was. + #[test] + fn dimension_lines_are_read_from_the_document_the_preview_applies_to() { + use vectorcraft_doc::{Node, NodeKind}; + let (mut d, _) = doc_with_rect(); + let pt = Point::new; + let line = |y: f64| Some(Box::new(DimensionTool::default().recipe(DimensionMode::Linear, pt(300.0, y), pt(400.0, y), pt(350.0, y), None))); + let id = d.alloc_id(); + let mut drawn = Node::new(id, NodeKind::Group { children: vec![], clip: false }); + drawn.extras_mut().dimension = line(300.0); + let l = d.layers[0].id; + d.insert(Some(l), usize::MAX, drawn).unwrap(); + let (s, p) = (Selection::default(), paint()); + let ev = |kind, x: f64, y: f64| PointerEvent::new(kind, x, y); + let offset = |t: &mut DimensionTool, c: &ToolContext, y: f64| { + let acts = t.pointer(c, &ev(PointerKind::Move, 420.0, y)); + let Some(Action::Preview(_, params)) = acts.last() else { panic!("{acts:?}") }; + params["offset"].clone() + }; + let mut t = DimensionTool::default(); + let c = cx(&d, &s, &p); + for (x, y) in [(400.0, 400.0), (450.0, 400.0)] { + t.pointer(&c, &ev(PointerKind::Down, x, y)); + t.pointer(&c, &ev(PointerKind::Up, x, y)); + } + assert!(matches!(t.pointer(&c, &ev(PointerKind::Move, 420.0, 450.0)).first(), Some(Action::Begin(_)))); + for (rev, edit) in [(1, "moved"), (2, "hidden")] { + let mut doc = d.clone(); + match edit { + "moved" => doc.node_mut(id).unwrap().extras_mut().dimension = line(320.0), + _ => doc.node_mut(id).unwrap().visible = false, + } + let c = ToolContext { revision: (0, rev), interaction_doc: Some(&d), ..cx(&doc, &s, &p) }; + assert_eq!(offset(&mut t, &c, 318.0), json!(-82.0), "{edit}: not on the level at y = 320"); + assert_eq!(offset(&mut t, &c, 302.0), json!(-100.0), "{edit}: on the level at y = 300"); + } + // A revision that moves with the same document the interaction began with does not read + // the lines again; another document it began with does. + t.levels.clear(); + let c = ToolContext { revision: (0, 3), interaction_doc: Some(&d), ..cx(&d, &s, &p) }; + assert_eq!(offset(&mut t, &c, 302.0), json!(-98.0), "not read again"); + let again = d.clone(); + let c = ToolContext { revision: (0, 4), interaction_doc: Some(&again), ..cx(&d, &s, &p) }; + assert_eq!(offset(&mut t, &c, 302.0), json!(-100.0), "read again"); + } + + /// The preview of the dimension itself does not count toward the 20,000 objects read: a + /// dimension that was the last one read stays a level once the preview is in front of it. + #[test] + fn the_preview_does_not_push_the_last_dimension_read_out_of_reach() { + use std::sync::Arc; + use vectorcraft_doc::{Node, NodeKind}; + let (mut d, _) = doc_with_rect(); + let pt = Point::new; + let line = |y: f64| Some(Box::new(DimensionTool::default().recipe(DimensionMode::Linear, pt(300.0, y), pt(400.0, y), pt(350.0, y), None))); + let mut drawn = Node::new(d.alloc_id(), NodeKind::Group { children: vec![], clip: false }); + drawn.extras_mut().dimension = line(300.0); + // The layer, the group and 19,997 empty groups before the dimension: it is the 20,000th. + let mut children = vec![Arc::new(drawn)]; + children.extend((0..19_997).map(|_| Arc::new(Node::new(d.alloc_id(), NodeKind::Group { children: vec![], clip: false })))); + let l = d.layers[0].id; + let group = Node::new(d.alloc_id(), NodeKind::Group { children, clip: false }); + d.insert(Some(l), usize::MAX, group).unwrap(); + let (s, p) = (Selection::default(), paint()); + let ev = |kind, x: f64, y: f64| PointerEvent::new(kind, x, y); + let offset = |t: &mut DimensionTool, c: &ToolContext| { + let acts = t.pointer(c, &ev(PointerKind::Move, 420.0, 302.0)); + let Some(Action::Preview(_, params)) = acts.last() else { panic!("{acts:?}") }; + params["offset"].clone() + }; + let mut t = DimensionTool::default(); + let c = cx(&d, &s, &p); + for (x, y) in [(400.0, 400.0), (450.0, 400.0)] { + t.pointer(&c, &ev(PointerKind::Down, x, y)); + t.pointer(&c, &ev(PointerKind::Up, x, y)); + } + assert!(matches!(t.pointer(&c, &ev(PointerKind::Move, 420.0, 450.0)).first(), Some(Action::Begin(_)))); + assert_eq!(offset(&mut t, &c), json!(-100.0), "the 20,000th object is read"); + let mut previewed = d.clone(); + let mut preview = Node::new(previewed.alloc_id(), NodeKind::Group { children: vec![], clip: false }); + preview.extras_mut().dimension = + Some(Box::new(DimensionTool::default().recipe(DimensionMode::Linear, pt(400.0, 400.0), pt(450.0, 400.0), pt(425.0, 304.0), None))); + previewed.insert(Some(l), usize::MAX, preview).unwrap(); + let c = ToolContext { revision: (0, 1), ..cx(&previewed, &s, &p) }; + assert_eq!(offset(&mut t, &c), json!(-100.0), "still read with the preview in front"); + } + #[test] fn a_dropped_placement_press_does_not_commit_the_dimension() { let (d, _) = doc_with_rect(); diff --git a/crates/tools/src/distort/width.rs b/crates/tools/src/distort/width.rs index 005b8e9473..b2050dbbdf 100644 --- a/crates/tools/src/distort/width.rs +++ b/crates/tools/src/distort/width.rs @@ -7,8 +7,9 @@ //! either onto another width point makes a discontinuous point (the width steps there). Shift-click //! adds width points to the selection (or takes them out), and dragging one of several selected //! points moves or widens them all. Double-clicking a stroke opens Width Point Edit (the -//! `widthPoint` dialog), editing a hit point or creating one on confirmation. Delete/Backspace -//! removes the selected width points. +//! `widthPoint` dialog), editing a hit point or creating one on confirmation; on one of several +//! selected points it edits all of them (`indices`). Delete/Backspace removes the selected width +//! points. //! //! Gestures preview `stroke.widthPoint.set {id, t, left, right, index?}` (side widths in points), //! `stroke.widthPoint.copy {id, index, t}` or, for several points, `stroke.widthProfile.set {ids, @@ -117,6 +118,9 @@ 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 width points selected before a click on one of them selected just that one, and + /// whether the button has gone down again since: a double-click on that point edits them all. + before_click: Option<((NodeId, Vec), bool)>, /// 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>, @@ -360,6 +364,9 @@ impl Tool for WidthTool { } PointerKind::TripleClick => vec![], PointerKind::DoubleClick => { + // The double-click's first click selected just the point under it: the points + // selected before it are selected again. + let before_click = self.before_click.take().and_then(|(sel, pressed)| pressed.then_some(sel)); let spot = match self.edit_spot_at(cx, p) { Ok(spot) => spot, Err(false) => return vec![], @@ -374,11 +381,32 @@ impl Tool for WidthTool { self.selected = Some((spot.owner, vec![spot.t])); return vec![Action::Dialog("widthPoint".into(), json!({"id": spot.owner.0, "t": spot.t}))]; }; - self.selected = Some((spot.owner, vec![w.t])); - vec![Action::Dialog("widthPoint".into(), json!({"id": spot.owner.0, "index": w.index, "adjustAdjoining": ev.mods.shift}))] + if let Some((owner, ts)) = before_click + && owner == spot.owner + && self.is_selected(owner, w.t) + && ts.iter().any(|t| (t - w.t).abs() <= SAME_T) + { + self.selected = Some((owner, ts)); + } + // A selected point edits every selected point; another one edits itself alone. + if !self.is_selected(spot.owner, w.t) { + self.selected = Some((spot.owner, vec![w.t])); + } + // Every selected entry goes to the dialog, which opens one point (or the two + // halves of a discontinuous point) as `index` would. + let indices = self.selected_indices(cx, spot.owner); + let mut params = json!({"id": spot.owner.0, "adjustAdjoining": ev.mods.shift}); + if indices.len() > 1 { + params["indices"] = json!(indices); + } else { + params["index"] = json!(w.index); + } + vec![Action::Dialog("widthPoint".into(), params)] } PointerKind::Down => { self.before_press = self.selected.clone(); + // Only the press right after the click counts as the double-click's second one. + self.before_click = self.before_click.take().filter(|(_, pressed)| !pressed).map(|(sel, _)| (sel, true)); let spot = match self.edit_spot_at(cx, p) { Ok(spot) => spot, Err(brushed) => { @@ -455,7 +483,14 @@ impl Tool for WidthTool { let dt = d.t - d.spot.t; self.selected = match (d.group.is_some(), d.moved, self.selected.take()) { // A click on one of several selected points selects just that one. - (true, false, _) if !ev.mods.shift => Some((d.spot.owner, vec![d.spot.t])), + (true, false, sel) if !ev.mods.shift => { + // Only a selection of several places: a discontinuous point alone also + // drags as a group, and its click must not replace the remembered one. + if let Some(sel) = sel.filter(|(_, ts)| ts.len() > 1) { + self.before_click = Some((sel, false)); + } + Some((d.spot.owner, vec![d.spot.t])) + } // Points moved together stay selected. (true, _, Some((id, ts))) if d.mode == Mode::Move => Some((id, ts.into_iter().map(|t| (t + dt).clamp(0.0, 1.0)).collect())), (true, _, sel) => sel, @@ -1037,4 +1072,74 @@ mod tests { assert!(t.pointer(&c, &ev(PointerKind::DoubleClick, 120.0, 250.0, mods)).is_empty(), "not on a stroked path"); } } + + #[test] + fn double_click_on_one_of_several_selected_points_edits_them_all() { + let (d, id) = doc_three_points(); + let (s, p) = (Selection::default(), paint()); + let c = cx(&d, &s, &p); + let (none, shift) = (Mods::default(), Mods { shift: true, ..Default::default() }); + let click = |t: &mut WidthTool, x: f64, mods: Mods| { + t.pointer(&c, &ev(PointerKind::Down, x, 200.0, mods)); + t.pointer(&c, &ev(PointerKind::Up, x, 200.0, mods)); + }; + // The events a double-click sends: two clicks, then the double-click. + let double_click = |t: &mut WidthTool, x: f64, mods: Mods| { + click(t, x, mods); + click(t, x, mods); + match t.pointer(&c, &ev(PointerKind::DoubleClick, x, 200.0, mods)).as_slice() { + [Action::Dialog(kind, v)] if kind == "widthPoint" => v.clone(), + acts => panic!("expected Width Point Edit: {acts:?}"), + } + }; + for mods in [none, shift] { + let mut t = WidthTool::default(); + click(&mut t, 150.0, none); + click(&mut t, 250.0, shift); + let v = double_click(&mut t, 250.0, mods); + assert_eq!((&v["id"], &v["indices"]), (&json!(id.0), &json!([1, 3])), "{mods:?}"); + assert!(v.get("index").is_none()); + assert_eq!(v["adjustAdjoining"], json!(mods.shift)); + assert_eq!(t.selected_indices(&c, id), vec![1, 3], "the selection is kept"); + // A point outside the selection edits itself alone, and is selected alone. + let v = double_click(&mut t, 200.0, none); + assert_eq!(v["index"], json!(2)); + assert!(v.get("indices").is_none()); + assert_eq!(t.selected_indices(&c, id), vec![2]); + } + // A discontinuous point among them keeps both halves, and double-clicking it keeps the others. + let (mut d2, _) = doc_line(); + let points = vec![(0.0, 1.0, 1.0), (0.25, 1.0, 1.0), (0.5, 1.0, 1.0), (0.5, 2.0, 2.0), (0.75, 1.0, 1.0), (1.0, 1.0, 1.0)]; + d2.node_mut(id).unwrap().appearance.stroke_mut().unwrap().profile = Some(WidthProfile { points }); + let c2 = cx(&d2, &s, &p); + let mut t = WidthTool::default(); + for (x, mods) in [(150.0, none), (200.0, shift), (200.0, none), (200.0, none)] { + t.pointer(&c2, &ev(PointerKind::Down, x, 200.0, mods)); + t.pointer(&c2, &ev(PointerKind::Up, x, 200.0, mods)); + } + let acts = t.pointer(&c2, &ev(PointerKind::DoubleClick, 200.0, 200.0, none)); + let [Action::Dialog(_, v)] = acts.as_slice() else { panic!("expected Width Point Edit: {acts:?}") }; + assert_eq!(v["indices"], json!([1, 2, 3])); + // Three points at nearly one place are selected together and all go to the dialog. + let (mut d3, _) = doc_line(); + let points = vec![(0.0, 1.0, 1.0), (0.5, 1.0, 1.0), (0.5000005, 2.0, 2.0), (0.5000009, 3.0, 3.0), (1.0, 1.0, 1.0)]; + d3.node_mut(id).unwrap().appearance.stroke_mut().unwrap().profile = Some(WidthProfile { points }); + let c3 = cx(&d3, &s, &p); + let mut t = WidthTool::default(); + for _ in 0..2 { + t.pointer(&c3, &ev(PointerKind::Down, 200.0, 200.0, none)); + t.pointer(&c3, &ev(PointerKind::Up, 200.0, 200.0, none)); + } + let acts = t.pointer(&c3, &ev(PointerKind::DoubleClick, 200.0, 200.0, none)); + let [Action::Dialog(_, v)] = acts.as_slice() else { panic!("expected Width Point Edit: {acts:?}") }; + assert_eq!(v["indices"], json!([1, 2, 3])); + // A click on one of the selected points, then a double-click on it later, edits that point. + let mut t = WidthTool::default(); + click(&mut t, 150.0, none); + click(&mut t, 250.0, shift); + click(&mut t, 250.0, none); + click(&mut t, 200.0, none); + let v = double_click(&mut t, 250.0, none); + assert_eq!(v["index"], json!(3)); + } } diff --git a/crates/tools/src/draw2.rs b/crates/tools/src/draw2.rs index 9401dcd4c2..3c663006e5 100644 --- a/crates/tools/src/draw2.rs +++ b/crates/tools/src/draw2.rs @@ -102,17 +102,18 @@ pub(crate) fn pen_bearing(q: PenPose) -> Option { (from_upright >= 1.0).then(|| (-y).atan2(x).to_degrees()) } -/// The 0..1 that each of the Eraser's variation modes Pressure, Tilt, Bearing and Rotation reads -/// from a pen at `pressure` (0..1) held as `pose`, leaning toward `bearing` (degrees, from -/// [`pen_bearing`]): 0 gives the value less its variation and 1 the value plus it, as -/// `path.eraseRegion` reads a stroke's points. Tilt reads 1 upright and 0 lying flat; Bearing and -/// Rotation read ½ plus the angle over 360°, the rotation turned counter-clockwise. What the pen -/// does not give reads ½, the value itself. -pub(crate) fn pen_controls(pressure: f64, pose: Option, bearing: Option) -> [f64; 4] { +/// The 0..1 that each of the Eraser's variation modes Pressure, Tilt, Bearing, Rotation and Stylus +/// Wheel reads, in that order, from a pen at `pressure` (0..1) held as `pose`, leaning toward +/// `bearing` (degrees, from [`pen_bearing`]): 0 gives the value less its variation and 1 the value +/// plus it, as `path.eraseRegion` reads a stroke's points. Tilt reads 1 upright and 0 lying flat; +/// Bearing and Rotation read ½ plus the angle over 360°, the rotation turned counter-clockwise; +/// Stylus Wheel reads the pen's wheel (0..1). What the pen does not give reads ½, the value itself. +pub(crate) fn pen_controls(pressure: f64, pose: Option, bearing: Option) -> [f64; 5] { let tilt = pose.and_then(|q| q.tilt).map_or(0.5, |t| 1.0 - pen_lean(t).1 / 90.0); let rotation = pose.and_then(|q| q.rotation).map_or(0.5, |r| 0.5 + vectorcraft_geom::normalize_deg(-f64::from(r)) / 360.0); let bearing = bearing.map_or(0.5, |b| 0.5 + b / 360.0); - [pressure, tilt, bearing, rotation].map(|c| if c.is_finite() { c.clamp(0.0, 1.0) } else { 0.5 }) + let wheel = pose.and_then(|q| q.wheel).map_or(0.5, f64::from); + [pressure, tilt, bearing, rotation, wheel].map(|c| if c.is_finite() { c.clamp(0.0, 1.0) } else { 0.5 }) } /// Create a drawing tool by id (None = not one of ours). @@ -365,7 +366,7 @@ pub(crate) fn walk_pickable<'a>(cx: &ToolContext<'a>, mut f: impl FnMut(&'a vect } /// Editable path nodes, selected ones first, then the rest top-most first ([`walk_pickable`]). -fn candidate_paths(cx: &ToolContext) -> Vec { +pub(crate) fn candidate_paths(cx: &ToolContext) -> Vec { let mut v: Vec = cx.selection.objects.iter().copied().filter(|id| cx.doc.node(*id).is_some_and(|n| n.path_data().is_some())).collect(); let mut rest = vec![]; walk_pickable(cx, |n| { @@ -374,8 +375,9 @@ fn candidate_paths(cx: &ToolContext) -> Vec { } }); rest.reverse(); + let mut seen: std::collections::HashSet = v.iter().copied().collect(); for id in rest { - if !v.contains(&id) { + if seen.insert(id) { v.push(id); } } diff --git a/crates/tools/src/draw2/anchor.rs b/crates/tools/src/draw2/anchor.rs index 93d2595016..1fe1fd72f3 100644 --- a/crates/tools/src/draw2/anchor.rs +++ b/crates/tools/src/draw2/anchor.rs @@ -11,7 +11,8 @@ //! still held: at 45° steps from where it was). Space held during a convert- or handle-drag moves //! the anchor, handles and all, as while drawing with the Pen. Blend spine points and handles //! follow the same conversions (#2544). -//! Scissors: click a path to split it there (Alt = add, as the Add Anchor Point tool does). +//! Scissors: hover and click snap as the Pen does; click a path to split it there (Alt = add, +//! as the Add Anchor Point tool does). use serde_json::json; use vectorcraft_doc::NodeId; @@ -19,8 +20,8 @@ use vectorcraft_geom::Point; use super::{hit_anchor, hit_segment, insert_anchor, remove_anchor}; use crate::direct::hit_handle; -use crate::guides::HandleSnap; -use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; +use crate::guides::{DrawSnap, HandleSnap}; +use crate::{Action, Cursor, Mods, Overlay, PixelOp, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; use vectorcraft_geom::constrain_angle_from; #[derive(Clone, Copy, Debug)] @@ -94,12 +95,25 @@ enum SpaceResume { SpineHandle { id: NodeId, ai: usize, out: bool }, } +/// The cursor reuses the last hover's point, with DrawSnap checking its target inputs. The +/// Scissors-only inputs also bind the resolved point to the current cut eligibility. +struct ScissorsHover { + raw: Point, + snapped: Point, + zoom: f64, + isolation: Option, + selection_tolerance: f64, +} + pub struct AnchorTool { id: &'static str, state: State, /// Smart guides of the handle being dragged, and what it snaps to. guides: Vec, snap: HandleSnap, + /// Scissors uses the drawing tools' targets; Anchor Point keeps its own handle snap above. + scissors_snap: DrawSnap, + scissors_hover: Option, /// Move offset while Shift-dragging an anchor or spine point (pointer, delta). measure: Option<(Point, f64, f64)>, /// While Space is held during a convert/handle drag, the shape gesture to return to. @@ -117,7 +131,85 @@ impl AnchorTool { "scissors" => "scissors", _ => "addAnchor", }; - Self { id, state: State::Idle, guides: vec![], snap: HandleSnap::default(), measure: None, space_resume: None, lent: false } + Self { + id, + state: State::Idle, + guides: vec![], + snap: HandleSnap::default(), + scissors_snap: DrawSnap::default(), + scissors_hover: None, + measure: None, + space_resume: None, + lent: false, + } + } + + fn clear_scissors_snap(&mut self) { + self.scissors_snap.clear(); + self.scissors_hover = None; + } + + fn current_scissors_hover(&self, cx: &ToolContext) -> Option<&ScissorsHover> { + self.scissors_hover.as_ref().filter(|h| { + h.zoom == cx.zoom + && h.isolation == cx.isolation + && h.selection_tolerance == cx.selection_tolerance + && self.scissors_snap.is_current(cx, &[]) + }) + } + + /// Keep a shared art snap unless it prevents a cut the raw pointer could make. Outside art + /// still supplies alignment and intersection guides; pixel and grid snapping keep precedence. + fn resolve_scissors_snap(&mut self, cx: &ToolContext, raw: Point, snapped: Point) -> Point { + let eligible = |p| hit_anchor(cx, p, 0.0).is_some() || hit_segment(cx, p, cx.pick_tol()).is_some(); + let fallback = (cx.smart_guides || cx.snap_to_point) + && !cx.snaps_to_pixel(PixelOp::Drawing) + && !cx.snap_to_grid + && snapped != raw + && !eligible(snapped) + && eligible(raw); + let snapped = if fallback { + self.scissors_snap.clear(); + raw + } else { + snapped + }; + self.scissors_hover = + Some(ScissorsHover { raw, snapped, zoom: cx.zoom, isolation: cx.isolation, selection_tolerance: cx.selection_tolerance }); + snapped + } + + /// Prefer a path actually at the snapped point before a nearby selected path. The small + /// tolerance covers curve-meeting roundoff. Pixel, grid and alignment points can lie off all + /// paths; there the ordinary full pick radius keeps the existing selected-path priority. + fn scissors_segment(cx: &ToolContext, p: Point) -> Option<(NodeId, usize, usize, f64)> { + let tol = cx.pick_tol(); + if cx.smart_guides || cx.snap_to_point || cx.snaps_to_pixel(PixelOp::Drawing) || cx.snap_to_grid { + super::segment_in(cx, super::candidate_paths(cx), p, tol.min(1e-6)).or_else(|| hit_segment(cx, p, tol)) + } else { + hit_segment(cx, p, tol) + } + } + + fn scissors_press(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { + let p = ev.pos; + if ev.mods.alt { + return Self::add(cx, p); + } + let snapped = self.scissors_snap.press(cx, p, &[], None); + let p = self.resolve_scissors_snap(cx, p, snapped); + let point = cx.point_tol(); + // A path snap must not be pulled to a nearby anchor by the larger pick radius. + // Shared anchor targets and the path's anchors use the same stored coordinates. + let snapping = cx.smart_guides || cx.snap_to_point || cx.snaps_to_pixel(PixelOp::Drawing) || cx.snap_to_grid; + let anchor_tol = if snapping { 0.0 } else { point }; + if let Some((id, si, ai)) = hit_anchor(cx, p, anchor_tol) { + return vec![Action::Exec("path.split".into(), json!({"id": id.0, "subpath": si, "anchor": ai}))]; + } + match Self::scissors_segment(cx, p) { + Some((id, si, seg, t)) => vec![Action::Exec("path.split".into(), json!({"id": id.0, "subpath": si, "segment": seg, "t": t}))], + None => vec![], + } } /// The Anchor Point tool as the Pen lends it with Alt held: an Alt-drag on a handle moves only @@ -317,7 +409,10 @@ impl Tool for AnchorTool { /// handle, a segment, a blend spine's point, handle or segment) cancels it: what it moved goes /// back and the release does nothing. Escape after a press that has not moved yet drops the /// press, so its release converts nothing. - fn key(&mut self, _cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { + fn key(&mut self, _cx: &ToolContext, key: ToolKey, mods: Mods) -> Vec { + if self.id == "scissors" && (key == ToolKey::Escape || mods.alt) { + self.clear_scissors_snap(); + } if key != ToolKey::Escape || matches!(self.state, State::Idle) { return vec![]; } @@ -339,8 +434,9 @@ impl Tool for AnchorTool { } fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { let p = ev.pos; - // Anchors and handle ends are picked from a little further than segments. - let (tol, point) = (cx.pick_tol(), cx.point_tol()); + if self.id == "scissors" && ev.mods.alt { + self.clear_scissors_snap(); + } match (self.id, ev.kind) { ("addAnchor", PointerKind::Down) => { if ev.mods.alt { @@ -356,18 +452,18 @@ impl Tool for AnchorTool { Self::delete(cx, p) } } - ("scissors", PointerKind::Down) => { - if ev.mods.alt { - return Self::add(cx, p); - } - if let Some((id, si, ai)) = hit_anchor(cx, p, point) { - return vec![Action::Exec("path.split".into(), json!({"id": id.0, "subpath": si, "anchor": ai}))]; - } - match hit_segment(cx, p, tol) { - Some((id, si, seg, t)) => vec![Action::Exec("path.split".into(), json!({"id": id.0, "subpath": si, "segment": seg, "t": t}))], - None => vec![], + ("scissors", PointerKind::Move) => { + if !ev.mods.alt { + let snapped = self.scissors_snap.hover(cx, p, &[], None); + self.resolve_scissors_snap(cx, p, snapped); } + vec![] } + ("scissors", PointerKind::Up) => { + self.clear_scissors_snap(); + vec![] + } + ("scissors", PointerKind::Down) => self.scissors_press(cx, ev), ("anchorPoint", PointerKind::Down) => { self.space_resume = None; self.state = Self::press_target(cx, p); @@ -572,7 +668,14 @@ impl Tool for AnchorTool { _ => vec![], } } + fn hover_ended(&mut self, _cx: &ToolContext) { + self.clear_scissors_snap(); + } + fn wants_rehover(&self) -> bool { + self.id == "scissors" && self.scissors_hover.is_some() + } fn deactivate(&mut self, _cx: &ToolContext) -> Vec { + self.clear_scissors_snap(); self.measure = None; let st = std::mem::replace(&mut self.state, State::Idle); match st { @@ -591,6 +694,9 @@ impl Tool for AnchorTool { if matches!(self.state, State::Handle { .. }) { out.extend(self.guides.iter().cloned()); } + if self.id == "scissors" && self.current_scissors_hover(cx).is_some() { + out.extend_from_slice(self.scissors_snap.guides()); + } if cx.measurement_labels && let Some((p, dx, dy)) = self.measure { @@ -606,11 +712,8 @@ impl Tool for AnchorTool { "deleteAnchor" => Cursor::PenAdd, "scissors" if m.alt => Cursor::PenAdd, "scissors" => { - if hit_segment(cx, p, cx.pick_tol()).is_some() { - Cursor::Scissors - } else { - Cursor::ScissorsNotAllowed - } + let p = self.current_scissors_hover(cx).filter(|h| h.raw == p).map_or(p, |h| h.snapped); + if hit_segment(cx, p, cx.pick_tol()).is_some() { Cursor::Scissors } else { Cursor::ScissorsNotAllowed } } _ => match self.state { State::Reshape { .. } => Cursor::ReshapeSegment, diff --git a/crates/tools/src/draw2/anchor/tests.rs b/crates/tools/src/draw2/anchor/tests.rs index 4e4af7f997..ba4bd4df27 100644 --- a/crates/tools/src/draw2/anchor/tests.rs +++ b/crates/tools/src/draw2/anchor/tests.rs @@ -301,6 +301,317 @@ fn scissors_splits_at_segment() { ); } +fn scissors_crossing() -> (vectorcraft_doc::Document, NodeId, Selection) { + let (mut d, rect) = doc_with_rect(); + let line = d.alloc_id(); + d.insert( + Some(d.layers[0].id), + 1, + vectorcraft_doc::Node::path( + line, + vectorcraft_geom::shapes::line(Point::new(145.0, 90.0), Point::new(165.0, 130.0)), + vectorcraft_doc::Appearance::default_art(), + ), + ) + .unwrap(); + // The selected rectangle is the cut target even though the crossing line is above it. + let mut selected = Selection::default(); + selected.set([rect]); + (d, rect, selected) +} + +fn scissors_cut_at(d: &vectorcraft_doc::Document, id: NodeId, actions: &[Action]) -> Point { + let [Action::Exec(command, args)] = actions else { panic!("expected one split: {actions:?}") }; + assert_eq!(command, "path.split"); + assert_eq!(args["id"], id.0); + let si = args["subpath"].as_u64().unwrap() as usize; + let sp = &d.node(id).unwrap().path_data().unwrap().subpaths[si]; + if let Some(anchor) = args["anchor"].as_u64() { + sp.anchors[anchor as usize].p + } else { + // A straight segment still has cubic parameters: check geometry, not a linear t. + sp.segment(args["segment"].as_u64().unwrap() as usize).eval(args["t"].as_f64().unwrap()) + } +} + +fn scissors_labels(tool: &AnchorTool, cx: &ToolContext) -> Vec<(String, Point)> { + tool.overlays(cx).into_iter().filter_map(|o| if let Overlay::Label { text, p, .. } = o { Some((text, p)) } else { None }).collect() +} + +/// #6470: the hover and the cut use the drawing tools' intersection, with their existing pixel, +/// grid and Smart Guides/Snap to Point precedence. Turning Smart Guides off restores the raw cut. +#[test] +fn scissors_snaps_intersections_with_the_drawing_options() { + let (mut d, rect, selected) = scissors_crossing(); + d.grid = vectorcraft_doc::GridPrefs { spacing: 20.0, subdivisions: 1 }; + let paint = paint(); + for (smart, point, pixel, grid, x, label) in [ + (true, true, false, false, 150.0, Some("intersect")), + (false, false, false, false, 152.0, None), + (false, true, false, false, 152.0, None), + (true, true, true, false, 152.0, None), + (true, true, false, true, 160.0, None), + ] { + let c = ToolContext { smart_guides: smart, snap_to_point: point, snap_to_pixel: pixel, snap_to_grid: grid, ..cx(&d, &selected, &paint) }; + let mut tool = AnchorTool::new("scissors"); + assert!(tool.pointer(&c, &PointerEvent::new(PointerKind::Move, 152.0, 101.5)).is_empty()); + let hovered = scissors_labels(&tool, &c); + let actions = tool.pointer(&c, &PointerEvent::new(PointerKind::Down, 152.0, 101.5)); + let cut = scissors_cut_at(&d, rect, &actions); + assert!(cut.distance(Point::new(x, 100.0)) < 1e-6, "smart={smart}, point={point}, pixel={pixel}, grid={grid}: {cut:?}"); + assert_eq!(hovered, label.map(|s| (s.to_string(), Point::new(x, 100.0))).into_iter().collect::>()); + assert!(tool.pointer(&c, &PointerEvent::new(PointerKind::Up, 152.0, 101.5)).is_empty()); + assert!(tool.overlays(&c).is_empty()); + } +} + +/// Snapping chooses the path it names, rather than a selected path merely within pick tolerance. +/// With every snap off, the existing selected-path priority still applies to the raw pointer. +#[test] +fn scissors_snapped_path_beats_nearby_selected_path() { + let (mut d, rect) = doc_with_rect(); + let line = d.alloc_id(); + d.insert( + Some(d.layers[0].id), + 1, + vectorcraft_doc::Node::path( + line, + vectorcraft_geom::shapes::line(Point::new(120.0, 102.0), Point::new(240.0, 102.0)), + vectorcraft_doc::Appearance::default_art(), + ), + ) + .unwrap(); + let mut selected = Selection::default(); + selected.set([rect]); + let paint = paint(); + for (smart, point, at, owner, target) in [ + (false, false, (150.0, 101.6), rect, (150.0, 100.0)), + (true, true, (150.0, 101.6), line, (150.0, 102.0)), + (false, true, (150.0, 101.6), rect, (150.0, 100.0)), + (false, true, (150.0, 102.0), line, (150.0, 102.0)), + ] { + let (at, target) = (Point::from(at), Point::from(target)); + let c = ToolContext { smart_guides: smart, snap_to_point: point, snap_to_pixel: false, snap_to_grid: false, ..cx(&d, &selected, &paint) }; + let mut tool = AnchorTool::new("scissors"); + tool.pointer(&c, &PointerEvent::new(PointerKind::Move, at.x, at.y)); + let labels = scissors_labels(&tool, &c); + if smart { + assert_eq!(labels.len(), 1, "{labels:?}"); + assert_eq!(labels[0].0, "path"); + assert!(labels[0].1.distance(Point::new(150.0, 102.0)) < 1e-6, "{labels:?}"); + } else { + assert!(labels.is_empty(), "{labels:?}"); + } + assert_eq!(tool.cursor(&c, at, Mods::default()), Cursor::Scissors); + let actions = tool.pointer(&c, &PointerEvent::new(PointerKind::Down, at.x, at.y)); + assert!(scissors_cut_at(&d, owner, &actions).distance(target) < 1e-6, "smart={smart}, point={point}: {actions:?}"); + } +} + +/// Outside art can give an isolated path useful guides, but an unusable art snap must not turn a +/// valid raw cut into a miss. Pixel/grid precedence still forbids falling back to the raw point. +#[test] +fn scissors_keeps_valid_isolated_cuts_when_outside_art_snaps() { + let (mut d, rect) = doc_with_rect(); + let outside = d.alloc_id(); + d.insert( + Some(d.layers[0].id), + 1, + vectorcraft_doc::Node::path( + outside, + vectorcraft_geom::shapes::line(Point::new(150.0, 103.5), Point::new(350.0, 350.0)), + vectorcraft_doc::Appearance::default_art(), + ), + ) + .unwrap(); + let mut selected = Selection::default(); + selected.set([rect]); + let paint = paint(); + let at = Point::new(150.0, 100.0); + for snapping in [false, true] { + let c = ToolContext { + isolation: Some(rect), + smart_guides: snapping, + snap_to_point: snapping, + snap_to_pixel: false, + snap_to_grid: false, + ..cx(&d, &selected, &paint) + }; + let mut tool = AnchorTool::new("scissors"); + tool.pointer(&c, &PointerEvent::new(PointerKind::Move, at.x, at.y)); + let labels = scissors_labels(&tool, &c); + let cursor = tool.cursor(&c, at, Mods::default()); + let actions = tool.pointer(&c, &PointerEvent::new(PointerKind::Down, at.x, at.y)); + assert!(scissors_cut_at(&d, rect, &actions).distance(at) < 1e-6, "snapping={snapping}: {actions:?}"); + assert_eq!(cursor, Cursor::Scissors, "snapping={snapping}"); + assert!(labels.is_empty(), "rejected outside snap must not guide the raw cut: {labels:?}"); + assert!(scissors_labels(&tool, &c).is_empty(), "the press also discards its rejected guide"); + } + + // The same isolation may still use an outside path's intersection on the eligible rectangle. + let (d, rect, selected) = scissors_crossing(); + let c = ToolContext { isolation: Some(rect), ..cx(&d, &selected, &paint) }; + let mut tool = AnchorTool::new("scissors"); + let at = Point::new(152.0, 101.5); + tool.pointer(&c, &PointerEvent::new(PointerKind::Move, at.x, at.y)); + let labels = scissors_labels(&tool, &c); + assert_eq!(labels.len(), 1, "{labels:?}"); + assert_eq!(labels[0].0, "intersect"); + assert!(labels[0].1.distance(Point::new(150.0, 100.0)) < 1e-6, "{labels:?}"); + assert_eq!(tool.cursor(&c, at, Mods::default()), Cursor::Scissors); + let actions = tool.pointer(&c, &PointerEvent::new(PointerKind::Down, at.x, at.y)); + assert!(scissors_cut_at(&d, rect, &actions).distance(Point::new(150.0, 100.0)) < 1e-6, "{actions:?}"); + + // A grid snap away from the path remains a miss even though the raw point is cuttable. + let (mut d, rect) = doc_with_rect(); + d.node_mut(rect).unwrap().transform(vectorcraft_geom::Affine::translate((0.0, 3.5)), true); + d.grid = vectorcraft_doc::GridPrefs { spacing: 20.0, subdivisions: 1 }; + let mut selected = Selection::default(); + selected.set([rect]); + let c = ToolContext { isolation: Some(rect), snap_to_grid: true, ..cx(&d, &selected, &paint) }; + let mut tool = AnchorTool::new("scissors"); + let at = Point::new(150.0, 103.5); + tool.pointer(&c, &PointerEvent::new(PointerKind::Move, at.x, at.y)); + assert_eq!(tool.cursor(&c, at, Mods::default()), Cursor::ScissorsNotAllowed); + assert!(tool.pointer(&c, &PointerEvent::new(PointerKind::Down, at.x, at.y)).is_empty()); + assert!(scissors_labels(&tool, &c).is_empty()); +} + +/// Path and alignment labels use the same targets as the Pen. A configured snap reach beyond the +/// anchor's pick radius proves that snapping chooses the anchor rather than a nearby segment. +#[test] +fn scissors_shows_paths_alignment_and_configured_anchor_snaps() { + let (d, rect) = doc_with_rect(); + let (selected, paint) = (Selection::default(), paint()); + for (at, smart, point, reach, label, target, cuts) in [ + ((170.0, 201.0), true, true, 4.0, Some("path"), (170.0, 200.0), true), + ((151.5, 431.0), true, true, 4.0, Some("align"), (150.0, 431.0), false), + ((201.0, 105.5), true, true, 8.0, Some("anchor"), (200.0, 100.0), true), + ((201.0, 105.5), true, true, 4.0, Some("path"), (200.0, 105.5), true), + // Snap to Point keeps the anchor target without Smart Guides labels. + ((201.0, 105.5), false, true, 8.0, None, (200.0, 100.0), true), + // Outside Smart Guides' reach, but inside the legacy 4.5 px anchor pick radius. + ((200.0, 104.25), true, true, 4.0, Some("path"), (200.0, 104.25), true), + ((200.0, 104.25), false, false, 4.0, None, (200.0, 100.0), true), + ] { + let c = + ToolContext { smart_guides: smart, snap_to_point: point, snapping_tolerance: reach, snap_tolerance: reach, ..cx(&d, &selected, &paint) }; + let mut tool = AnchorTool::new("scissors"); + tool.pointer(&c, &PointerEvent::new(PointerKind::Move, at.0, at.1)); + let target = Point::from(target); + let labels = scissors_labels(&tool, &c); + if let Some(label) = label { + assert_eq!(labels.len(), 1, "at={at:?}, smart={smart}, point={point}, reach={reach}, want={label}: {labels:?}"); + assert_eq!(labels[0].0, label); + assert!(labels[0].1.distance(target) < 1e-6, "{labels:?}"); + } else { + assert!(labels.is_empty(), "{labels:?}"); + } + let actions = tool.pointer(&c, &PointerEvent::new(PointerKind::Down, at.0, at.1)); + if cuts { + assert!(scissors_cut_at(&d, rect, &actions).distance(target) < 1e-6, "{actions:?}"); + if target == Point::new(200.0, 100.0) { + assert!(matches!(&actions[..], [Action::Exec(_, v)] if v["anchor"] == 1)); + } + } else { + assert!(actions.is_empty(), "a guide away from every path must not cut: {actions:?}"); + } + } +} + +/// A cached snap is for the same raw position, document state and drawing options only. A press +/// gathers fresh targets, even when a previous hover's document state is reused by a caller. +#[test] +fn scissors_cursor_and_press_use_current_snaps() { + let (d, rect) = doc_with_rect(); + let (selected, paint) = (Selection::default(), paint()); + let mut c = cx(&d, &selected, &paint); + let mut tool = AnchorTool::new("scissors"); + let at = Point::new(204.0, 140.0); + tool.pointer(&c, &PointerEvent::new(PointerKind::Move, at.x, at.y)); + assert_eq!(tool.cursor(&c, at, Mods::default()), Cursor::Scissors); + assert_eq!(tool.cursor(&c, Point::new(204.0, 160.0), Mods::default()), Cursor::ScissorsNotAllowed); + assert!(!tool.overlays(&c).is_empty()); + // These interaction inputs can change without a document revision. The old hover must not + // keep moving the cursor onto the path or showing guides until another pointer move. + c.selection_tolerance = 1.0; + assert_eq!(tool.cursor(&c, at, Mods::default()), Cursor::ScissorsNotAllowed); + assert!(tool.overlays(&c).is_empty()); + c.selection_tolerance = 3.0; + tool.pointer(&c, &PointerEvent::new(PointerKind::Move, at.x, at.y)); + assert_eq!(tool.cursor(&c, at, Mods::default()), Cursor::Scissors); + assert!(!tool.overlays(&c).is_empty()); + c.isolation = Some(rect); + assert_eq!(tool.cursor(&c, at, Mods::default()), Cursor::ScissorsNotAllowed); + assert!(tool.overlays(&c).is_empty()); + c.isolation = None; + tool.pointer(&c, &PointerEvent::new(PointerKind::Move, at.x, at.y)); + assert_eq!(tool.cursor(&c, at, Mods::default()), Cursor::Scissors); + assert!(!tool.overlays(&c).is_empty()); + c.smart_guides = false; + c.snap_to_point = false; + assert_eq!(tool.cursor(&c, at, Mods::default()), Cursor::ScissorsNotAllowed); + assert!(tool.overlays(&c).is_empty()); + c.smart_guides = true; + c.snap_to_point = true; + c.zoom = 2.0; + assert_eq!(tool.cursor(&c, at, Mods::default()), Cursor::ScissorsNotAllowed); + c.zoom = 1.0; + c.revision.1 += 1; + assert_eq!(tool.cursor(&c, at, Mods::default()), Cursor::ScissorsNotAllowed); + + let (crossing, _, selected) = scissors_crossing(); + let before = cx(&crossing, &selected, &paint); + let mut tool = AnchorTool::new("scissors"); + tool.pointer(&before, &PointerEvent::new(PointerKind::Move, 152.0, 101.5)); + let after = cx(&d, &selected, &paint); + let actions = tool.pointer(&after, &PointerEvent::new(PointerKind::Down, 152.0, 101.5)); + assert!(scissors_cut_at(&d, rect, &actions).distance(Point::new(152.0, 100.0)) < 1e-6, "{actions:?}"); +} + +/// Ending the hover, release, Escape (including a dropped touch) and switching tools drop both the +/// guides and the cursor's snap. Alt lends the raw Add Anchor Point tool, with no Scissors guide. +#[test] +fn scissors_clears_its_snap_when_the_interaction_ends_or_alt_takes_over() { + let (d, _) = doc_with_rect(); + let (selected, paint) = (Selection::default(), paint()); + let c = cx(&d, &selected, &paint); + for ending in 0..7 { + let mut tool = AnchorTool::new("scissors"); + tool.pointer(&c, &PointerEvent::new(PointerKind::Move, 204.0, 140.0)); + assert!(!tool.overlays(&c).is_empty()); + match ending { + 0 => { + tool.pointer(&c, &PointerEvent::new(PointerKind::Up, 204.0, 140.0)); + } + 1 => { + tool.key(&c, ToolKey::Escape, Mods::default()); + } + 2 => { + tool.drop_press(&c); + } + 3 => { + tool.deactivate(&c); + } + 4 => tool.hover_ended(&c), + _ => { + let alt = Mods { alt: true, ..Mods::default() }; + let kind = if ending == 5 { PointerKind::Move } else { PointerKind::Down }; + let event = PointerEvent::new(kind, 170.0, 201.0); + let mut add = AnchorTool::new("addAnchor"); + let actions = tool.pointer(&c, &event.with_mods(alt)); + assert_eq!(actions, add.pointer(&c, &event)); + if kind == PointerKind::Down { + assert!(matches!(&actions[..], [Action::Exec(command, _)] if command == "path.insertAnchor")); + } + assert_eq!(tool.cursor(&c, event.pos, alt), Cursor::PenAdd); + } + } + assert!(tool.overlays(&c).is_empty(), "ending {ending}"); + assert_eq!(tool.cursor(&c, Point::new(204.0, 140.0), Mods::default()), Cursor::ScissorsNotAllowed, "ending {ending}"); + } +} + /// With Alt held the Scissors tool acts as the Add Anchor Point tool: a click sends what the Add /// Anchor Point tool's click sends (an anchor inserted on a segment, nothing away from every path) /// and never splits, and the cursor is the Add Anchor Point tool's everywhere. Without Alt it cuts @@ -611,6 +922,49 @@ fn anchor_point_shift_drag_honors_measurement_labels() { assert!(!t.overlays(&off).iter().any(|o| matches!(o, Overlay::Measure { .. }))); } +/// Disabled Drawing pixel snapping must behave like the same effective art-snap mode. +/// Drawing enabled is the ordinary pixel-priority control at this integer cut point. +#[test] +fn scissors_drawing_pixel_option_keeps_valid_isolated_cuts() { + let (mut d, rect) = doc_with_rect(); + let outside = d.alloc_id(); + d.insert( + Some(d.layers[0].id), + 1, + vectorcraft_doc::Node::path( + outside, + vectorcraft_geom::shapes::line(Point::new(150.0, 103.5), Point::new(350.0, 350.0)), + vectorcraft_doc::Appearance::default_art(), + ), + ) + .unwrap(); + let mut selected = Selection::default(); + selected.set([rect]); + let paint = paint(); + let at = Point::new(150.0, 100.0); + for drawing in [true, false] { + let c = ToolContext { + isolation: Some(rect), + smart_guides: true, + snap_to_point: true, + snap_to_pixel: true, + pixel_snap: crate::PixelSnap { drawing, ..Default::default() }, + snap_to_grid: false, + ..cx(&d, &selected, &paint) + }; + let mut tool = AnchorTool::new("scissors"); + tool.pointer(&c, &PointerEvent::new(PointerKind::Move, at.x, at.y)); + let labels = scissors_labels(&tool, &c); + let cursor = tool.cursor(&c, at, Mods::default()); + let actions = tool.pointer(&c, &PointerEvent::new(PointerKind::Down, at.x, at.y)); + assert!(!actions.is_empty(), "drawing={drawing}: expected a valid isolated cut"); + assert!(scissors_cut_at(&d, rect, &actions).distance(at) < 1e-6, "drawing={drawing}: {actions:?}"); + assert_eq!(cursor, Cursor::Scissors, "drawing={drawing}"); + assert!(labels.is_empty(), "rejected outside snap must not guide the raw cut: {labels:?}"); + assert!(scissors_labels(&tool, &c).is_empty(), "the press also discards its rejected guide"); + } +} + /// Alt held while dragging a handle links it with the opposite handle (`link`), making the /// anchor smooth; without Alt the handle moves on its own. Shift with Alt keeps the 45° steps, an /// Alt-click still retracts the handle, and Escape cancels the linking drag. The Pen, lending the diff --git a/crates/tools/src/draw2/gesture.rs b/crates/tools/src/draw2/gesture.rs index fac5bcd90b..ba5e8afe9c 100644 --- a/crates/tools/src/draw2/gesture.rs +++ b/crates/tools/src/draw2/gesture.rs @@ -10,8 +10,9 @@ //! Guides and Snap to Point: it shows no Smart Guides, hovering or drawing, and its ends follow the //! hand. Snap to Grid and Snap to Pixel still move its ends (`grid_snaps`). The Paintbrush records the pen pressure of each point (a stroke a pen //! pressed less than fully on sends `[x, y, pressure]` points) for pressure-sensitive brushes, and -//! the pen's tilt and barrel rotation where the pen reads them (`[x, y, pressure, tiltX, tiltY, -//! rotation]` points, `null` for what a point lacks) for brushes that vary with them. The Blob +//! the pen's tilt, barrel rotation and airbrush finger wheel where the pen reads them (`[x, y, +//! pressure, tiltX, tiltY, rotation, wheel]` points, `null` for what a point lacks) for brushes +//! that vary with them. The Blob //! Brush and Eraser also record pressure when their Size varies with Pressure, and the Eraser //! records the pressure, tilt and rotation that its Angle, Roundness and Size variations follow; //! while it erases, its tip outline at the pointer takes the angle, roundness and size the pen @@ -104,8 +105,8 @@ pub struct GestureTool { /// The pen pressure of each of `points` (the Paintbrush, the Blob Brush with Size on Pressure, /// and the Eraser with any of its variations on Pressure). pressures: Vec, - /// The pen's tilt and rotation at each of `points` (the Paintbrush, and the Eraser with any of - /// its variations on Tilt, Bearing or Rotation). + /// The pen's tilt, rotation and wheel at each of `points` (the Paintbrush, and the Eraser with + /// any of its variations on Tilt, Bearing or Rotation). poses: Vec>, active: bool, began: bool, @@ -962,7 +963,8 @@ impl GestureTool { self.id != "pencil" || self.live_preview } - /// Add a stroke sample, with the pen's pressure, tilt and rotation of the event `ev` there. + /// Add a stroke sample, with the pen's pressure, tilt, rotation and wheel of the event `ev` + /// there. fn push(&mut self, p: Point, ev: &PointerEvent) { if let Some(last) = self.points.last() { self.length += last.distance(p); @@ -970,7 +972,8 @@ impl GestureTool { self.points.push(p); let modes = self.tip_modes(); // The poses go out beside the pressures (`stroke_json`), so a stroke that keeps one keeps both. - let posed = self.id == "paintbrush" || modes.iter().any(|m| matches!(m, Variation::Tilt | Variation::Bearing | Variation::Rotation)); + let posed = self.id == "paintbrush" + || modes.iter().any(|m| matches!(m, Variation::Tilt | Variation::Bearing | Variation::Rotation | Variation::StylusWheel)); if posed || modes.contains(&Variation::Pressure) { self.pressures.push(ev.pressure); self.light |= ev.pressure < 1.0; @@ -1122,7 +1125,7 @@ impl GestureTool { let Some(name) = vectorcraft_brush::current(cx.doc) else { return vec![] }; let Some(brush) = vectorcraft_brush::find(cx.doc, &name) else { return vec![] }; let BrushKind::Bristle(bristle) = brush.kind else { return vec![] }; - let [pressure, tilt, bearing, rotation] = super::pen_controls(pressure, Some(pose), super::pen_bearing(pose)); + let [pressure, tilt, bearing, rotation, _] = super::pen_controls(pressure, Some(pose), super::pen_bearing(pose)); let size = bristle.size.max(0.1) * cx.paint.stroke_width.max(0.0) * (0.5 + pressure) * (1.25 - 0.5 * tilt); if size <= 0.0 { return vec![]; @@ -1274,6 +1277,7 @@ impl GestureTool { Variation::Tilt => posed && self.poses.iter().flatten().any(|q| q.tilt.is_some()), Variation::Bearing => posed && self.bearings.iter().any(Option::is_some), Variation::Rotation => posed && self.poses.iter().flatten().any(|q| q.rotation.is_some()), + Variation::StylusWheel => posed && self.poses.iter().flatten().any(|q| q.wheel.is_some()), Variation::Fixed | Variation::Random => false, }; if self.smoothing { @@ -1314,7 +1318,7 @@ impl GestureTool { let (a, b) = ((a - 0.5) * 360.0, (b - 0.5) * 360.0); 0.5 + vectorcraft_geom::normalize_deg(a + vectorcraft_geom::normalize_deg(b - a) / 2.0) / 360.0 }; - self.tip_of_controls([(a[0] + b[0]) / 2.0, (a[1] + b[1]) / 2.0, turn(a[2], b[2]), turn(a[3], b[3])]) + self.tip_of_controls([(a[0] + b[0]) / 2.0, (a[1] + b[1]) / 2.0, turn(a[2], b[2]), turn(a[3], b[3]), (a[4] + b[4]) / 2.0]) } /// What each of the variation modes Pressure, Tilt, Bearing and Rotation reads at point `i` of @@ -1323,7 +1327,7 @@ impl GestureTool { /// the bearing of the last point up to it that the pen leaned 1° or more at, or before the /// first such point the bearing of that first one. What the release does not read /// ([`Self::reads_pressures`], [`Self::reads_poses`]) reads ½, the values themselves. - fn controls_of_point(&self, i: usize) -> [f64; 4] { + fn controls_of_point(&self, i: usize) -> [f64; 5] { let pressure = if self.reads_pressures() { self.pressures.get(i).map_or(0.5, |p| f64::from(*p)) } else { 0.5 }; let (pose, bearing) = if self.reads_poses() { (self.poses.get(i).copied().flatten(), self.bearings.get(i).copied().flatten().or(self.first_bearing)) @@ -1352,7 +1356,7 @@ impl GestureTool { /// The Eraser's angle, roundness and size where its tip outline shows: while it erases, each /// value on a mode that follows the pen goes from the value less its Variation to the value /// plus it as the pen reads now (the pressure once the pen has pressed less than fully, the - /// tilt and rotation of the last point, and the bearing of the last point the pen leaned 1° or + /// tilt, rotation and wheel of the last point, and the bearing of the last point the pen leaned 1° or /// more at), as `path.eraseRegion` reads the stroke; before a press, and for Random, Fixed and a /// pen that gives no reading, the values themselves. The Blob Brush's are its own values. fn tip_now(&self) -> [f64; 3] { @@ -1373,7 +1377,7 @@ impl GestureTool { /// The tip's angle, roundness and size where the modes Pressure, Tilt, Bearing and Rotation /// read `controls` (0..1 each, [`super::pen_controls`]). - fn tip_of_controls(&self, controls: [f64; 4]) -> [f64; 3] { + fn tip_of_controls(&self, controls: [f64; 5]) -> [f64; 3] { let base = [self.angle, self.roundness, self.size]; let variations = [self.angle_variation, self.roundness_variation, self.size_variation]; let mut out = base; @@ -1383,6 +1387,7 @@ impl GestureTool { Variation::Tilt => controls[1], Variation::Bearing => controls[2], Variation::Rotation => controls[3], + Variation::StylusWheel => controls[4], Variation::Fixed | Variation::Random => continue, }; // The size goes past a nib's 1296 pt, as `path.eraseRegion` sweeps it. @@ -1392,20 +1397,28 @@ impl GestureTool { [angle, roundness.clamp(1.0, 100.0), size.max(super::MIN_BRUSH_SIZE)] } - /// The stroke's points: `[x, y, pressure, tiltX, tiltY, rotation]` when a pen read its tilt or - /// rotation anywhere along it (`null` for what a point lacks, and for the pressure of a stroke + /// The stroke's points: `[x, y, pressure, tiltX, tiltY, rotation, wheel]` when a pen read its + /// wheel anywhere along it, else `[x, y, pressure, tiltX, tiltY, rotation]` when it read its + /// tilt or rotation anywhere (`null` for what a point lacks, and for the pressure of a stroke /// pressed fully all along), else `[x, y, pressure]` when a pen pressed less than fully /// anywhere (a mouse always presses fully), else `[x, y]`. fn stroke_json(&self) -> Value { let n = self.points.len(); let pressed = self.pressures.len() == n && self.pressures.iter().any(|p| *p < 1.0); - let posed = self.poses.len() == n && self.poses.iter().flatten().any(|q| q.tilt.is_some() || q.rotation.is_some()); + let poses = || self.poses.iter().flatten(); + let wheeled = self.poses.len() == n && poses().any(|q| q.wheel.is_some()); + let posed = wheeled || (self.poses.len() == n && poses().any(|q| q.tilt.is_some() || q.rotation.is_some())); let round = |v: f32, k: f64| (f64::from(v) * k).round() / k; if posed { let points = self.points.iter().zip(&self.pressures).zip(&self.poses).map(|((p, f), q)| { let q = q.unwrap_or_default(); let (tilt, rotation) = (q.tilt.map(|t| t.map(|v| round(v, 100.0))), q.rotation.map(|r| round(r, 100.0))); - json!([p.x, p.y, pressed.then(|| round(*f, 1000.0)), tilt.map(|t| t[0]), tilt.map(|t| t[1]), rotation]) + let pressure = pressed.then(|| round(*f, 1000.0)); + if wheeled { + json!([p.x, p.y, pressure, tilt.map(|t| t[0]), tilt.map(|t| t[1]), rotation, q.wheel.map(|w| round(w, 1000.0))]) + } else { + json!([p.x, p.y, pressure, tilt.map(|t| t[0]), tilt.map(|t| t[1]), rotation]) + } }); Value::Array(points.collect()) } else if pressed { diff --git a/crates/tools/src/draw2/gesture/tests.rs b/crates/tools/src/draw2/gesture/tests.rs index 7ecc0bed03..87d18ca4b4 100644 --- a/crates/tools/src/draw2/gesture/tests.rs +++ b/crates/tools/src/draw2/gesture/tests.rs @@ -124,7 +124,7 @@ fn paintbrush_sends_pen_tilt_and_rotation() { let Some(Action::Preview(_, v)) = last.first() else { panic!("{last:?}") }; v["points"].clone() }; - let leaning = |x: f32, r: Option| Some(PenPose { tilt: Some([x, -10.0]), rotation: r }); + let leaning = |x: f32, r: Option| Some(PenPose { tilt: Some([x, -10.0]), rotation: r, wheel: None }); assert_eq!( stroke("paintbrush", 0.5, [leaning(30.0, Some(45.0)), leaning(40.0, Some(-90.0)), None]), json!([[0.0, 0.0, 0.5, 30.0, -10.0, 45.0], [40.0, 0.0, 0.5, 40.0, -10.0, 270.0], [80.0, 0.0, 0.5, null, null, null]]) @@ -134,6 +134,12 @@ fn paintbrush_sends_pen_tilt_and_rotation() { // A pose that reads nothing is a mouse's. assert_eq!(stroke("paintbrush", 1.0, [Some(PenPose::default()); 3]), json!([[0.0, 0.0], [40.0, 0.0], [80.0, 0.0]])); assert_eq!(stroke("pencil", 0.5, [leaning(30.0, Some(45.0)); 3]), json!([[0.0, 0.0], [40.0, 0.0], [80.0, 0.0]])); + // An airbrush pen's finger wheel comes seventh, and a point without it sends null. + let wheel = |w: f32| Some(PenPose { wheel: Some(w), ..PenPose::default() }); + assert_eq!( + stroke("paintbrush", 1.0, [wheel(0.0), wheel(0.25), None]), + json!([[0.0, 0.0, null, null, null, null, 0.0], [40.0, 0.0, null, null, null, null, 0.25], [80.0, 0.0, null, null, null, null, null]]) + ); } #[test] @@ -3059,8 +3065,10 @@ fn bristle_tip_annotator_follows_a_rotation_capable_pen() { Some(vectorcraft_geom::Shape::bounding_box(path)) }; let mut tool = GestureTool::new("paintbrush"); - let at = - |rotation| PointerEvent { pen: Some(PenPose { tilt: Some([30.0, 0.0]), rotation }), ..PointerEvent::new(PointerKind::Move, 100.0, 50.0) }; + let at = |rotation| PointerEvent { + pen: Some(PenPose { tilt: Some([30.0, 0.0]), rotation, wheel: None }), + ..PointerEvent::new(PointerKind::Move, 100.0, 50.0) + }; assert!(bounds(&tool, &view).is_none()); tool.pointer(&view, &PointerEvent::new(PointerKind::Move, 100.0, 50.0)); assert!(bounds(&tool, &view).is_none(), "mouse"); @@ -3193,7 +3201,7 @@ fn the_eraser_tip_follows_its_variation_modes() { assert_eq!(t.check_option(k, &json!(mode.id())), Ok(()), "{k} {mode:?}"); } } - let modes = "must be one of `fixed`, `random`, `pressure`, `tilt`, `bearing`, `rotation`"; + let modes = "must be one of `fixed`, `random`, `pressure`, `tilt`, `bearing`, `rotation`, `stylusWheel`"; 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())); @@ -3208,7 +3216,7 @@ fn the_eraser_tip_follows_its_variation_modes() { near(tip(&t), (90.0, 47.5, 110.0, 52.5)); // Erasing with the barrel turned half way round and the pen upright, the tip stands upright and // is 28 by 7 pt; Random leaves the roundness as set. - let pen = Some(PenPose { tilt: Some([0.0, 0.0]), rotation: Some(180.0) }); + let pen = Some(PenPose { tilt: Some([0.0, 0.0]), rotation: Some(180.0), wheel: None }); t.pointer(&cx, &PointerEvent { pen, pressure: 0.5, ..PointerEvent::new(PointerKind::Down, 100.0, 50.0) }); t.pointer(&cx, &PointerEvent { pen, pressure: 0.5, ..PointerEvent::new(PointerKind::Drag, 200.0, 50.0) }); near(tip(&t), (196.5, 36.0, 203.5, 64.0)); @@ -3245,6 +3253,43 @@ fn the_eraser_tip_follows_its_variation_modes() { assert_eq!(b.options()["sizeMode"], json!("pressure")); } +/// An Eraser value on Stylus Wheel follows the wheel the pen recorded, in the tip outline while it +/// erases and in the points the release sends; a pen that gives no wheel reads half way, the value +/// itself. +#[test] +fn the_eraser_tip_follows_the_stylus_wheel() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let cx = cx(&d, &s, &p); + let tip = |t: &GestureTool| match &t.overlays(&cx)[..] { + [.., Overlay::Path { path, color: [0, 0, 0], width: 1.0, .. }] => vectorcraft_geom::Shape::bounding_box(path), + o => panic!("{o:?}"), + }; + let near = |b: vectorcraft_geom::Rect, want: (f64, f64, f64, f64)| { + assert!([b.x0 - want.0, b.y0 - want.1, b.x1 - want.2, b.y1 - want.3].iter().all(|e| e.abs() < 0.01), "{b:?} vs {want:?}"); + }; + let mut t = GestureTool::new("eraser"); + for (k, v) in [("size", json!(20)), ("roundness", json!(25)), ("angleMode", json!("stylusWheel")), ("angleVariation", json!(90))] { + t.set_option(k, &v); + } + assert_eq!(t.options()["angleMode"], json!("stylusWheel")); + // The wheel at the far end of its travel turns the 20 by 5 pt tip upright. + let wheel = |w: Option| Some(PenPose { tilt: None, rotation: None, wheel: w }); + t.pointer(&cx, &PointerEvent { pen: wheel(Some(1.0)), ..PointerEvent::new(PointerKind::Down, 100.0, 50.0) }); + t.pointer(&cx, &PointerEvent { pen: wheel(Some(1.0)), ..PointerEvent::new(PointerKind::Drag, 200.0, 50.0) }); + near(tip(&t), (197.5, 40.0, 202.5, 60.0)); + let acts = t.pointer(&cx, &PointerEvent { pen: wheel(Some(1.0)), ..PointerEvent::new(PointerKind::Up, 200.0, 50.0) }); + let Some(Action::Exec(c, v)) = acts.first() else { panic!("{acts:?}") }; + assert_eq!((c.as_str(), &v["angleMode"]), ("path.eraseRegion", &json!("stylusWheel"))); + assert_eq!(v["points"], json!([[100.0, 50.0, null, null, null, null, 1.0], [200.0, 50.0, null, null, null, null, 1.0]])); + // A pen without a wheel keeps the tip lying level. + t.pointer(&cx, &PointerEvent { pen: wheel(None), ..PointerEvent::new(PointerKind::Down, 100.0, 50.0) }); + t.pointer(&cx, &PointerEvent { pen: wheel(None), ..PointerEvent::new(PointerKind::Drag, 200.0, 50.0) }); + near(tip(&t), (190.0, 47.5, 210.0, 52.5)); + t.pointer(&cx, &PointerEvent { pen: wheel(None), ..PointerEvent::new(PointerKind::Up, 200.0, 50.0) }); +} + /// The Eraser's tip outline follows a pen turned in place, which adds no stroke point, and the /// release erases with that reading; and its size passes 1296 pt as `path.eraseRegion` sweeps it. #[test] @@ -3264,8 +3309,8 @@ fn the_eraser_tip_turns_in_place_and_passes_a_nib_size() { for (k, v) in [("size", json!(20)), ("roundness", json!(25)), ("angleMode", json!("rotation")), ("angleVariation", json!(90))] { t.set_option(k, &v); } - let level = Some(PenPose { tilt: None, rotation: Some(0.0) }); - let turned = Some(PenPose { tilt: None, rotation: Some(180.0) }); + let level = Some(PenPose { tilt: None, rotation: Some(0.0), wheel: None }); + let turned = Some(PenPose { tilt: None, rotation: Some(180.0), wheel: None }); t.pointer(&cx, &PointerEvent { pen: level, pressure: 0.5, ..PointerEvent::new(PointerKind::Down, 100.0, 50.0) }); t.pointer(&cx, &PointerEvent { pen: level, pressure: 0.5, ..PointerEvent::new(PointerKind::Drag, 200.0, 50.0) }); near(tip(&t), (190.0, 47.5, 210.0, 52.5)); @@ -3290,8 +3335,8 @@ fn the_eraser_tip_turns_in_place_and_passes_a_nib_size() { // With Angle on Bearing, a pen that leaned only at the last point and stands up there again // leaves no bearing: the tip lies level, as set. t.set_option("angleMode", &json!("bearing")); - let upright = Some(PenPose { tilt: Some([0.0, 0.0]), rotation: None }); - let leaning = Some(PenPose { tilt: Some([0.0, 45.0]), rotation: None }); + let upright = Some(PenPose { tilt: Some([0.0, 0.0]), rotation: None, wheel: None }); + let leaning = Some(PenPose { tilt: Some([0.0, 45.0]), rotation: None, wheel: None }); t.pointer(&cx, &PointerEvent { pen: upright, pressure: 0.5, ..PointerEvent::new(PointerKind::Down, 100.0, 50.0) }); t.pointer(&cx, &PointerEvent { pen: leaning, pressure: 0.5, ..PointerEvent::new(PointerKind::Drag, 200.0, 50.0) }); assert!(tip(&t).height() > 6.0, "{:?}", tip(&t)); @@ -3303,7 +3348,7 @@ fn the_eraser_tip_turns_in_place_and_passes_a_nib_size() { for (k, v) in [("size", json!(1000)), ("sizeMode", json!("tilt")), ("sizeVariation", json!(1000))] { t.set_option(k, &v); } - let upright = Some(PenPose { tilt: Some([0.0, 0.0]), rotation: None }); + let upright = Some(PenPose { tilt: Some([0.0, 0.0]), rotation: None, wheel: None }); t.pointer(&cx, &PointerEvent { pen: upright, pressure: 0.5, ..PointerEvent::new(PointerKind::Down, 100.0, 50.0) }); t.pointer(&cx, &PointerEvent { pen: upright, pressure: 0.5, ..PointerEvent::new(PointerKind::Drag, 200.0, 50.0) }); near(tip(&t), (-800.0, -950.0, 1200.0, 1050.0)); @@ -3339,9 +3384,9 @@ fn the_eraser_drag_area_follows_its_variation_modes() { t.set_option(k, v); } }; - let upright = Some(PenPose { tilt: Some([0.0, 0.0]), rotation: None }); - let turned = Some(PenPose { tilt: None, rotation: Some(180.0) }); - let level = Some(PenPose { tilt: None, rotation: Some(0.0) }); + let upright = Some(PenPose { tilt: Some([0.0, 0.0]), rotation: None, wheel: None }); + let turned = Some(PenPose { tilt: None, rotation: Some(180.0), wheel: None }); + let level = Some(PenPose { tilt: None, rotation: Some(0.0), wheel: None }); let press = |t: &mut GestureTool, pen: Option, kind: PointerKind, x: f64| { t.pointer(&cx, &PointerEvent { pen, pressure: 0.5, ..PointerEvent::new(kind, x, 150.0) }); }; @@ -3380,7 +3425,7 @@ fn the_eraser_drag_area_follows_its_variation_modes() { // lying flat the tip is 25% round and stands upright. let mut t = GestureTool::new("eraser"); set(&mut t, &[("size", json!(20)), ("angle", json!(90)), ("roundnessMode", json!("tilt")), ("roundnessVariation", json!(75))]); - let flat = Some(PenPose { tilt: Some([90.0, 0.0]), rotation: None }); + let flat = Some(PenPose { tilt: Some([90.0, 0.0]), rotation: None, wheel: None }); press(&mut t, flat, PointerKind::Down, 50.0); press(&mut t, flat, PointerKind::Drag, 150.0); near(bounds(&t), (47.5, 140.0, 152.5, 160.0)); @@ -3430,8 +3475,8 @@ fn the_eraser_drag_area_matches_the_release_when_pressure_or_a_mode_starts_durin let near = |b: vectorcraft_geom::Rect, want: (f64, f64, f64, f64)| { assert!([b.x0 - want.0, b.y0 - want.1, b.x1 - want.2, b.y1 - want.3].iter().all(|e| e.abs() < 0.01), "{b:?} vs {want:?}"); }; - let upright = Some(PenPose { tilt: Some([0.0, 0.0]), rotation: None }); - let leaning = Some(PenPose { tilt: Some([45.0, 0.0]), rotation: None }); + let upright = Some(PenPose { tilt: Some([0.0, 0.0]), rotation: None, wheel: None }); + let leaning = Some(PenPose { tilt: Some([45.0, 0.0]), rotation: None, wheel: None }); let press = |t: &mut GestureTool, pen: Option, pressure: f32, kind: PointerKind, x: f64| { t.pointer(&cx, &PointerEvent { pen, pressure, ..PointerEvent::new(kind, x, 150.0) }); }; @@ -3521,14 +3566,14 @@ fn the_eraser_drag_area_gives_the_first_lean_to_the_points_before_it() { let mut shown = vec![]; for (i, (tilt, x)) in poses.into_iter().zip([50.0, 100.0, 150.0, 200.0, 250.0]).enumerate() { let kind = if i == 0 { PointerKind::Down } else { PointerKind::Drag }; - let pen = Some(PenPose { tilt: Some(tilt), rotation: Some(30.0) }); + let pen = Some(PenPose { tilt: Some(tilt), rotation: Some(30.0), wheel: None }); t.pointer(&cx, &PointerEvent { pen, pressure: 1.0, ..PointerEvent::new(kind, x, 150.0) }); if i > 0 { shown.push(bounds(&t)); } } if let Some(tilt) = in_place { - let pen = Some(PenPose { tilt: Some(tilt), rotation: Some(30.0) }); + let pen = Some(PenPose { tilt: Some(tilt), rotation: Some(30.0), wheel: None }); t.pointer(&cx, &PointerEvent { pen, pressure: 1.0, ..PointerEvent::new(PointerKind::Drag, 250.2, 150.0) }); shown.push(bounds(&t)); } diff --git a/crates/tools/src/guides/snap.rs b/crates/tools/src/guides/snap.rs index 496ad00bfb..de09341bc7 100644 --- a/crates/tools/src/guides/snap.rs +++ b/crates/tools/src/guides/snap.rs @@ -384,6 +384,12 @@ pub(super) fn visible(cx: &ToolContext) -> Option { } impl DrawSnap { + /// Whether the last hover or press still has the current targets, without gathering the art + /// again. A caller caching the snapped point can use this before reusing it for a cursor. + pub(crate) fn is_current(&self, cx: &ToolContext, exclude: &[NodeId]) -> bool { + self.targets.as_ref().is_some_and(|(key, _)| key.as_ref() == Some(&SnapKey::of(cx, exclude))) + } + /// Snap the pointer hovering at `p` (the art but `exclude` as targets, the anchors of /// `exclude` still pulling), reusing the targets while nothing they depend on changed. pub fn hover(&mut self, cx: &ToolContext, p: Point, exclude: &[NodeId], from: Option<&Leave>) -> Point { diff --git a/crates/tools/src/guides/targets.rs b/crates/tools/src/guides/targets.rs index a68c6af385..6022ab68fb 100644 --- a/crates/tools/src/guides/targets.rs +++ b/crates/tools/src/guides/targets.rs @@ -119,6 +119,27 @@ fn parallel(a: Vec2, b: Vec2) -> bool { scale > 1e-18 && a.dot(b) > 0.0 && a.cross(b).abs() <= 1e-6 * scale } +/// `seg` as a line from its start to its end when it runs straight: a line, or a curve whose +/// control points lie on that line and that stays between its ends (a straight path with its +/// handles drawn out along it). +fn straight(seg: PathSeg) -> Option { + use vectorcraft_geom::kurbo::ParamCurveExtrema; + let (l, ctrl) = match seg { + PathSeg::Line(l) => return Some(l), + PathSeg::Quad(q) => (Line::new(q.p0, q.p2), [q.p1, q.p1]), + PathSeg::Cubic(c) => (Line::new(c.p0, c.p3), [c.p1, c.p2]), + }; + let d = l.p1 - l.p0; + let len2 = d.hypot2(); + if !len2.is_finite() || len2 <= 1e-18 || !ctrl.into_iter().all(|p| d.cross(p - l.p0).abs() <= 1e-9 * len2) { + return None; + } + // The curve's own bounds, not its control points', must stay within the ends' box. + let (b, ends) = (ParamCurveExtrema::bounding_box(&seg), Rect::from_points(l.p0, l.p1)); + let eps = 1e-9 * len2.sqrt(); + (b.x0 >= ends.x0 - eps && b.x1 <= ends.x1 + eps && b.y0 >= ends.y0 - eps && b.y1 <= ends.y1 + eps).then_some(l) +} + /// Does the curve `seg` run around `center` the whole way, as an arc of a circle about it drawn /// with curves does: nearly square to the center all along, and its distance from the center /// varying by no more than 0.03%? A circle drawn with four curves ([`vectorcraft_geom::shapes::ellipse`]) @@ -257,9 +278,10 @@ impl Targets { Self::moving(cx, exclude, Gather::Bounds) } - /// [`Self::for_move`]'s targets for a selection moved by one of its anchors (#7411): the path - /// segments of the art but `exclude` too, which that anchor lands on ([`Self::snap_onto_path`]), - /// as a dragged anchor does with Direct Selection. + /// [`Self::for_move`]'s targets for a selection moved by one of its anchors (#7411) or by a + /// point of a path's stroke or outline (#8568): the path segments of the art but `exclude` too, + /// which that point lands on ([`Self::snap_onto_path`]), as a dragged anchor does with Direct + /// Selection. pub fn for_move_by_anchor(cx: &ToolContext, exclude: &[NodeId]) -> Self { Self::moving(cx, exclude, Gather::Segments) } @@ -1036,15 +1058,57 @@ impl Targets { Some((q, self.label(q, Kind::Edge.label()).into_iter().collect())) } + /// [`Self::snap_onto_path`] for a selection held by a point `p` of a path's edge, its bounds + /// now `r` (#8568). Where paths cross, or on a curved segment, the point lands as + /// `snap_onto_path` lands it. On a straight segment, the selection then slides along that + /// segment, so the point stays on it, until its bounds line up with the other art or are spaced + /// evenly with it ([`Self::snap_rects_along`]), else until they line up with a ruler guide of + /// `rulers` ([`Self::snap_moved_along_to_rulers`]). A slide goes at most twice `tol` and not + /// past the segment's ends. Returns where the point goes and the guides. + pub(crate) fn snap_held_onto_path(&self, p: Point, r: Rect, tol: f64, rulers: Option<&Targets>) -> Option<(Point, Vec)> { + if self.segments.is_empty() { + return None; + } + if let Some(q) = self.crossing_with(p, tol, rulers.map_or(&self.rulers, |r| &r.rulers)) { + return Some((q, self.label(q, "intersect").into_iter().collect())); + } + let (seg, q) = self.nearest_segment(p, tol)?; + let on_path = |q: Point| self.label(q, Kind::Edge.label()); + let Some(l) = straight(seg) else { return Some((q, on_path(q).into_iter().collect())) }; + let len = (l.p1 - l.p0).hypot(); + if !len.is_finite() || len <= 1e-9 { + return Some((q, on_path(q).into_iter().collect())); + } + let u = (l.p1 - l.p0) / len; + let moved = r + (q - p); + // How far the point may slide each way: twice `tol`, and not past the segment's ends. + let at = (q - l.p0).dot(u); + let within = ((-at).max(-2.0 * tol), (len - at).min(2.0 * tol)); + let (s, mut ov) = Some(self.slide_rects_along(&[moved], u, tol, within)) + .filter(|(.., hit)| *hit) + .or_else(|| rulers.map(|t| t.slide_moved_along_to_rulers(q, moved, u, tol, within)).filter(|(.., hit)| *hit)) + .map_or((Vec2::ZERO, vec![]), |(s, ov, _)| (s, ov)); + let q = q + s; + // The point's label is "path", the label a ruler guide's slide puts there too. + ov.retain(|o| !matches!(o, Overlay::Label { .. })); + ov.extend(on_path(q)); + Some((q, ov)) + } + /// The nearest point within `tol` of `p` on a target segment. fn on_segment(&self, p: Point, tol: f64) -> Option { + self.nearest_segment(p, tol).map(|(_, q)| q) + } + + /// [`Self::on_segment`], with the segment the point is on. + fn nearest_segment(&self, p: Point, tol: f64) -> Option<(PathSeg, Point)> { self.segments .iter() .filter(|(b, _)| b.inflate(tol, tol).contains(p)) .map(|(_, c)| (c, c.nearest(p, 1e-6))) .filter(|(_, n)| n.distance_sq <= tol * tol) .min_by(|a, b| a.1.distance_sq.total_cmp(&b.1.distance_sq)) - .map(|(c, n)| c.eval(n.t)) + .map(|(c, n)| (*c, c.eval(n.t))) } /// Where two target paths, a path and a ruler guide, or two ruler guides cross, the crossing @@ -1152,9 +1216,16 @@ impl Targets { /// it is spaced evenly along an axis the line runs along. Returns the shift (along `dir`) and /// the guides. pub(crate) fn snap_rects_along(&self, rects: &[Rect], dir: Vec2, tol: f64) -> (Vec2, Vec) { + let (s, ov, _) = self.slide_rects_along(rects, dir, tol, (f64::NEG_INFINITY, f64::INFINITY)); + (s, ov) + } + + /// [`Self::snap_rects_along`] for a slide of `within` (the least and the most way along + /// `dir`), also saying whether anything lined up or was spaced evenly. + fn slide_rects_along(&self, rects: &[Rect], dir: Vec2, tol: f64, (lo, hi): (f64, f64)) -> (Vec2, Vec, bool) { let len = dir.hypot(); if !len.is_finite() || len <= 1e-9 { - return (Vec2::ZERO, vec![]); + return (Vec2::ZERO, vec![], false); } let u = dir / len; // The axes the line runs along: the x axis (`true`) and the y axis, and how far a step of @@ -1170,7 +1241,7 @@ impl Targets { for v in vs { for (t, from, _) in lines_near(lines, v, tol).iter().filter(|(t, ..)| (t - v).abs() <= tol) { let s = (t - v) / c; - if best.is_none_or(|b| s.abs() < b.0.abs()) { + if (lo..=hi).contains(&s) && best.is_none_or(|b| s.abs() < b.0.abs()) { best = Some((s, *t, *from, x)); } } @@ -1185,17 +1256,41 @@ impl Targets { self.line(Point::new(from.x.min(m.x0), t), Point::new(from.x.max(m.x1), t)) } }); - return (u * s, ov.into_iter().collect()); + return (u * s, ov.into_iter().collect(), true); } - let [r] = rects else { return (Vec2::ZERO, vec![]) }; + let [r] = rects else { return (Vec2::ZERO, vec![], false) }; if self.boxes.is_empty() { - return (Vec2::ZERO, vec![]); + return (Vec2::ZERO, vec![], false); } - let spaced = - axes.filter_map(|(x, c)| self.even_spacing(*r, x, tol).map(|(shift, _)| (shift / c, x))).min_by(|a, b| a.0.abs().total_cmp(&b.0.abs())); - let Some((s, x)) = spaced else { return (Vec2::ZERO, vec![]) }; + // The slide that spaces it evenly along each axis, within `lo..=hi` along the line. A slide + // along a slanted line also moves it across, so the gaps must still be equal where it ends + // up. + let spaced = axes + .filter_map(|(x, c)| { + // A level or upright slide along that axis keeps its row. + let level = (if x { u.y } else { u.x }).abs() <= 1e-9; + // At most 8 slides are checked where they end up, to bound the work per pointer move. + let checked = std::cell::Cell::new(0_usize); + let fits = |shift: f64| { + let s = shift / c; + if !(lo..=hi).contains(&s) { + return false; + } + if level { + return true; + } + if checked.get() >= 8 { + return false; + } + checked.set(checked.get() + 1); + self.even_spacing(*r + u * s, x, tol).is_some_and(|(rest, _)| rest.abs() <= 1e-6) + }; + self.even_spacing_by(*r, x, tol, Some(&fits)).map(|(shift, _)| (shift / c, x)) + }) + .min_by(|a, b| a.0.abs().total_cmp(&b.0.abs())); + let Some((s, x)) = spaced else { return (Vec2::ZERO, vec![], false) }; let gaps = self.even_spacing(*r + u * s, x, tol).map(|(_, gaps)| gaps).unwrap_or_default(); - (u * s, gaps.into_iter().flat_map(|g| self.gap_marks(g, x, tol)).collect()) + (u * s, gaps.into_iter().flat_map(|g| self.gap_marks(g, x, tol)).collect(), true) } /// Snap rectangles that move together (an artboard and its bleed): the edge or centre of any @@ -1240,6 +1335,12 @@ impl Targets { /// neighbour before or after it as two other objects of the row are apart, or as far from both /// neighbours; and the equal gaps then, as (start, end, where across) along that axis. fn even_spacing(&self, r: Rect, x: bool, tol: f64) -> Option<(f64, Vec<[f64; 3]>)> { + self.even_spacing_by(r, x, tol, None) + } + + /// [`Self::even_spacing`] for the nearest shift along that axis that `accept` takes (any shift + /// when `None`). + fn even_spacing_by(&self, r: Rect, x: bool, tol: f64, accept: Option<&dyn Fn(f64) -> bool>) -> Option<(f64, Vec<[f64; 3]>)> { let (r0, r1) = span(&r, x); let len = r1 - r0; let (c0, c1) = span(&r, !x); @@ -1276,8 +1377,36 @@ impl Targets { starts.extend(before.map(|a| (a.2 + g, Some(*g)))); starts.extend(after.map(|b| (b.1 - g - len, Some(*g)))); } - let (start, repeats) = - starts.into_iter().filter(|(t, _)| (t - r0).abs() <= tol).min_by(|a, b| (a.0 - r0).abs().total_cmp(&(b.0 - r0).abs()))?; + starts.retain(|(t, _)| (t - r0).abs() <= tol); + let nearer = |a: &(f64, Option), b: &(f64, Option)| (a.0 - r0).abs().total_cmp(&(b.0 - r0).abs()); + let (start, repeats) = match accept { + // The nearest start, the first proposed among equally near ones. + None => starts.into_iter().min_by(nearer)?, + Some(accept) => { + // Nearest first; the sort is stable, so equally near starts keep the order they + // were proposed in. Starts as near as each other are at most two shifts (one each + // way), so the shifts refused at the current distance are few, and each is asked + // about once. + starts.sort_by(nearer); + let mut refused: Vec = vec![]; + let mut at = f64::NAN; + starts.into_iter().find(|(t, _)| { + let shift = t - r0; + if shift.abs() != at { + at = shift.abs(); + refused.clear(); + } + if refused.contains(&shift) { + return false; + } + let ok = accept(shift); + if !ok { + refused.push(shift); + } + ok + })? + } + }; let at = r + if x { Vec2::new(start - r0, 0.0) } else { Vec2::new(0.0, start - r0) }; let (end, mut gaps) = (start + len, vec![]); if let Some((a, _, a1)) = before @@ -1385,9 +1514,16 @@ impl Targets { /// shortest slide winning and at most twice `tol` (a line nearly parallel to a guide would /// carry the selection far to meet it). Returns the shift along the line and the guides. pub(crate) fn snap_moved_along_to_rulers(&self, p: Point, r: Rect, dir: Vec2, tol: f64) -> (Vec2, Vec) { + let (s, ov, _) = self.slide_moved_along_to_rulers(p, r, dir, tol, (f64::NEG_INFINITY, f64::INFINITY)); + (s, ov) + } + + /// [`Self::snap_moved_along_to_rulers`] for a slide of `within` (the least and the most way + /// along `dir`), also saying whether the bounds lined up with a guide. + fn slide_moved_along_to_rulers(&self, p: Point, r: Rect, dir: Vec2, tol: f64, (lo, hi): (f64, f64)) -> (Vec2, Vec, bool) { let len = dir.hypot(); if !len.is_finite() || len <= 1e-9 { - return (Vec2::ZERO, vec![]); + return (Vec2::ZERO, vec![], false); } let u = dir / len; // The way along the line, where the guide is and where it starts, and whether it is upright. @@ -1399,16 +1535,22 @@ impl Targets { let vs = if vertical { [r.x0, r.center().x, r.x1] } else { [r.y0, r.center().y, r.y1] }; let (mid, half) = if vertical { (Point::new(0.0, r.center().y), r.height() / 2.0) } else { (Point::new(r.center().x, 0.0), r.width() / 2.0) }; - for (t, from, _) in self.rulers.iter().filter(|g| g.vertical == vertical).filter_map(|g| g.line_at(mid, tol + half)) { + for g in self.rulers.iter().filter(|g| g.vertical == vertical) { for v in vs { - let s = (t - v) / c; - if (t - v).abs() <= tol && s.abs() <= 2.0 * tol && best.is_none_or(|b| s.abs() < b.0.abs()) { + let s = (g.pos - v) / c; + if (g.pos - v).abs() > tol || s.abs() > 2.0 * tol || !(lo..=hi).contains(&s) || best.is_some_and(|b| s.abs() >= b.0.abs()) { + continue; + } + // The guide runs past the bounds: for a slide held to `within`, where the slide + // puts them; for a Shift move, where the move put them. + let at = if lo.is_finite() || hi.is_finite() { r.center() + u * s } else { mid }; + if let Some((t, from, _)) = g.line_at(at, tol + half) { best = Some((s, t, from, vertical)); } } } } - let Some((s, t, from, vertical)) = best else { return (Vec2::ZERO, vec![]) }; + let Some((s, t, from, vertical)) = best else { return (Vec2::ZERO, vec![], false) }; let moved = r + u * s; let line = if vertical { self.line(Point::new(t, from.y.min(moved.y0)), Point::new(t, from.y.max(moved.y1))) @@ -1417,7 +1559,7 @@ impl Targets { }; let mut ov: Vec = line.into_iter().collect(); ov.extend(self.label(p + u * s, "align")); - (u * s, ov) + (u * s, ov, true) } /// Snap a bounding-box resize. `a` is the scale [`crate::bbox::scale_for_drag`] gave for diff --git a/crates/tools/src/input.rs b/crates/tools/src/input.rs index 9fa2eab661..80c857abe6 100644 --- a/crates/tools/src/input.rs +++ b/crates/tools/src/input.rs @@ -46,8 +46,8 @@ pub struct PointerEvent { pub backquote: bool, #[serde(default = "one")] pub pressure: f32, - /// The pen's tilt and barrel rotation, when the pointer is a pen that reads either (a mouse: - /// `None`). + /// The pen's tilt, barrel rotation and finger wheel, when the pointer is a pen that reads any of + /// them (a mouse: `None`). #[serde(default, skip_serializing_if = "Option::is_none")] pub pen: Option, } @@ -58,23 +58,27 @@ fn one() -> f32 { /// How a pen is held, as far as it reads it. Tilt is in degrees, each −90..90 as Pointer Events /// give it, in document axes: `[x, y]`, x positive when the pen leans to the right and y positive -/// when it leans down the page. Rotation is the barrel's, in degrees clockwise (0..360). +/// when it leans down the page. Rotation is the barrel's, in degrees clockwise (0..360). The wheel +/// is where an airbrush pen's finger wheel is set, 0..1 from one end of its travel to the other. #[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] pub struct PenPose { #[serde(default, skip_serializing_if = "Option::is_none")] pub tilt: Option<[f32; 2]>, #[serde(default, skip_serializing_if = "Option::is_none")] pub rotation: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub wheel: Option, } impl PenPose { - /// Within its ranges: each tilt is clamped to −90..90 and the rotation brought into 0..360; a - /// tilt or rotation that is not a number is left out. + /// Within its ranges: each tilt is clamped to −90..90, the rotation brought into 0..360 and the + /// wheel clamped to 0..1; a tilt, rotation or wheel that is not a number is left out. pub fn sanitized(self) -> Self { let tilt = self.tilt.filter(|t| t.iter().all(|v| v.is_finite())).map(|t| t.map(|v| v.clamp(-90.0, 90.0))); // `rem_euclid` can round a tiny negative angle up to 360 itself. let rotation = self.rotation.filter(|r| r.is_finite()).map(|r| r.rem_euclid(360.0)).map(|r| if r >= 360.0 { 0.0 } else { r }); - Self { tilt, rotation } + let wheel = self.wheel.filter(|w| w.is_finite()).map(|w| w.clamp(0.0, 1.0)); + Self { tilt, rotation, wheel } } } @@ -92,14 +96,15 @@ impl PointerEvent { } /// The pen's tilt and rotation of a pointer event given as JSON (control channel, MCP): /// `tiltX` and `tiltY` (degrees, −90..90, in document axes; one without the other is 0) and - /// `rotation` (degrees clockwise, brought into 0..360). Values that are not numbers are left - /// out; `None` without any. + /// `rotation` (degrees clockwise, brought into 0..360) and `wheel` (an airbrush pen's finger + /// wheel, clamped to 0..1). Values that are not numbers are left out; `None` without any. pub fn json_pen(e: &Value) -> Option { let num = |k: &str| e.get(k).and_then(Value::as_f64).filter(|f| f.is_finite()); let tilt = |v: Option| v.map_or(0.0, |v| v.clamp(-90.0, 90.0) as f32); let (tx, ty) = (num("tiltX"), num("tiltY")); let tilt = (tx.is_some() || ty.is_some()).then(|| [tilt(tx), tilt(ty)]); - let pose = PenPose { tilt, rotation: num("rotation").map(|r| r.rem_euclid(360.0) as f32) }.sanitized(); + let rotation = num("rotation").map(|r| r.rem_euclid(360.0) as f32); + let pose = PenPose { tilt, rotation, wheel: num("wheel").map(|w| w.clamp(0.0, 1.0) as f32) }.sanitized(); (pose != PenPose::default()).then_some(pose) } /// How long the pointer then holds still, in seconds, from a JSON pointer event's `holdMs` @@ -113,11 +118,13 @@ impl PointerEvent { v.get("backquote").map_or(Ok(default), |b| b.as_bool().ok_or_else(|| "`backquote` must be a boolean".to_owned())) } /// Checks the optional keys of a JSON pointer event (control channel, MCP): `pressure`, - /// `holdMs`, `tiltX`, `tiltY` and `rotation` must be numbers, and `space` must be `doc` or - /// `screen`. A key that is absent or null keeps its default. + /// `holdMs`, `tiltX`, `tiltY`, `rotation` and `wheel` must be numbers, and `space` must be + /// `doc` or `screen`. A key that is absent or null keeps its default. pub fn json_check(e: &Value) -> Result<(), String> { let given = |k: &str| e.get(k).filter(|v| !v.is_null()); - if let Some(k) = ["pressure", "holdMs", "tiltX", "tiltY", "rotation"].into_iter().find(|k| given(k).is_some_and(|v| v.as_f64().is_none())) { + if let Some(k) = + ["pressure", "holdMs", "tiltX", "tiltY", "rotation", "wheel"].into_iter().find(|k| given(k).is_some_and(|v| v.as_f64().is_none())) + { return Err(format!("`{k}` must be a number")); } if given("space").is_some_and(|v| !matches!(v.as_str(), Some("doc" | "screen"))) { @@ -157,13 +164,13 @@ mod tests { use serde_json::json; for ok in [ json!({}), - json!({"pressure": 0.5, "holdMs": 10, "tiltX": -5, "tiltY": 5, "rotation": 400, "space": "screen"}), + json!({"pressure": 0.5, "holdMs": 10, "tiltX": -5, "tiltY": 5, "rotation": 400, "wheel": 0.25, "space": "screen"}), json!({"pressure": null, "space": null}), json!({"space": "doc"}), ] { assert_eq!(PointerEvent::json_check(&ok), Ok(()), "{ok}"); } - for k in ["pressure", "holdMs", "tiltX", "tiltY", "rotation"] { + for k in ["pressure", "holdMs", "tiltX", "tiltY", "rotation", "wheel"] { for bad in [json!("1"), json!(true), json!([1])] { assert_eq!(PointerEvent::json_check(&json!({k: bad})), Err(format!("`{k}` must be a number")), "{k}: {bad}"); } @@ -172,6 +179,19 @@ mod tests { assert_eq!(PointerEvent::json_check(&json!({"space": bad})), Err("`space` must be doc or screen".to_owned()), "{bad}"); } } + + #[test] + fn json_pen_reads_the_wheel_within_its_range() { + use serde_json::json; + let wheel = |v: Value| PointerEvent::json_pen(&json!({"wheel": v})).and_then(|q| q.wheel); + assert_eq!(wheel(json!(0.25)), Some(0.25)); + assert_eq!(wheel(json!(-3)), Some(0.0)); + assert_eq!(wheel(json!(7)), Some(1.0)); + assert_eq!(wheel(json!(null)), None); + assert_eq!(PointerEvent::json_pen(&json!({"wheel": 0.5})), Some(PenPose { wheel: Some(0.5), ..PenPose::default() })); + assert_eq!(PenPose { wheel: Some(f32::NAN), ..PenPose::default() }.sanitized(), PenPose::default()); + assert_eq!(PenPose { wheel: Some(1.5), ..PenPose::default() }.sanitized().wheel, Some(1.0)); + } } /// Keys tools care about. diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index 0b7bef755f..c864d529a2 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -15,6 +15,7 @@ pub mod catalog; pub mod circle; pub mod corners; pub mod cropimage; +pub mod curvature_circle; pub mod cut; pub mod dimension; pub mod direct; @@ -47,6 +48,7 @@ pub mod slice; pub mod symbolism; pub mod text; pub mod touchtype; +pub mod trace_split; pub mod typewidget; pub mod xform; @@ -385,6 +387,7 @@ pub fn create(id: &str) -> Box { "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()), + curvature_circle::ID => Box::new(curvature_circle::CurvatureCircleTool::default()), // Not in the toolbar: `file.place.queue` loads it. "place" => Box::new(place::PlaceTool::default()), other => symbolism::create(other) @@ -630,6 +633,7 @@ pub(crate) mod testutil { snap_to_glyph: false, glyph_snap: GlyphSnap::default(), corner_widgets: true, + shape_widgets: true, fill_active: true, gradient_stop: None, appearance_item: None, @@ -677,6 +681,7 @@ pub(crate) mod testutil { plane_targets: distort::perspective::widget::PlaneTargets::ALL, precise_cursors: false, global_edit: &[], + interaction_doc: None, } } diff --git a/crates/tools/src/mirror.rs b/crates/tools/src/mirror.rs index 5560fbc321..31253003d9 100644 --- a/crates/tools/src/mirror.rs +++ b/crates/tools/src/mirror.rs @@ -184,4 +184,29 @@ mod tests { spec.kind = RepeatKind::Mirror { angle: f64::NAN, center: Point::ZERO }; assert!(MirrorAxis::of(&doc, &selection, 1.0).is_none()); } + + #[test] + fn a_tool_switch_cancels_a_mirror_axis_drag() { + use crate::{PointerEvent, PointerKind, Tool}; + let (mut doc, id) = doc_with_rect(); + let mut source = doc.node(id).unwrap().clone(); + source.id = doc.alloc_id(); + doc.node_mut(id).unwrap().kind = NodeKind::Repeat(RepeatSpec::mirror(vec![Arc::new(source)], 90.0, 10.0)); + let mut selection = Selection::default(); + selection.set([id]); + let paint = paint(); + let c = cx(&doc, &selection, &paint); + let axis = MirrorAxis::of(&doc, &selection, c.zoom).unwrap(); + let mut t = crate::select::SelectionTool::default(); + assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, axis.center.x, axis.center.y)).is_empty()); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, axis.center.x + 20.0, axis.center.y)); + assert!(matches!(a.first(), Some(Action::Begin(l)) if l == "Repeat Options"), "{a:?}"); + assert_eq!(t.deactivate(&c), vec![Action::Cancel]); + assert!(!t.busy()); + // A press that has not moved the axis leaves nothing to cancel. + t.pointer(&c, &PointerEvent::new(PointerKind::Down, axis.center.x, axis.center.y)); + assert!(t.busy()); + assert!(t.deactivate(&c).is_empty()); + assert!(!t.busy()); + } } diff --git a/crates/tools/src/pen.rs b/crates/tools/src/pen.rs index 7b12599b62..3fd145868c 100644 --- a/crates/tools/src/pen.rs +++ b/crates/tools/src/pen.rs @@ -51,6 +51,10 @@ pub struct PenTool { /// The anchor a press placed, while the drag shapes its handles. drag: Option, hover: Option, + /// The pointer at the last hover before snapping: a press picks anchors there first. + hover_raw: Option, + /// The modifiers at the last hover: with Alt a press may go to the Anchor Point tool. + hover_mods: Mods, /// The incoming handle of the anchor being dragged out, as last previewed. in_h: Point, /// The first anchor, as it was when a press on it began closing the path, and its outgoing @@ -297,6 +301,8 @@ impl Tool for PenTool { match ev.kind { PointerKind::Move => { self.hover = Some(p); + self.hover_raw = Some(ev.pos); + self.hover_mods = ev.mods; vec![] } PointerKind::Down => { @@ -337,7 +343,9 @@ impl Tool for PenTool { } } // An end of another open path: the two become one, and the path is finished. - if let Some((other, other_si, at_first)) = raw_other.or_else(|| open_end_at(cx, p, tol, Some((id, si)))) { + if let Some((other, other_si, at_first)) = + raw_other.or_else(|| if p != ev.pos { open_end_at(cx, p, tol, Some((id, si))) } else { None }) + { self.stop(); let end = if at_first { "first" } else { "last" }; let mut params = json!({"ids": [id.0, other.0], "ends": ["last", end]}); @@ -522,22 +530,30 @@ impl Tool for PenTool { // The rubber band preference hides only the preview segment; Measurement Labels decides the readout. if self.drag.is_none() && self.handle.is_none() - && let (Some((id, _, _, last, out)), Some(h)) = (self.active(cx), self.hover) + && let (Some((id, si, first, last, out)), Some(h)) = (self.active(cx), self.hover) { - if cx.pen_rubber_band { - // The segment a click at `h` adds: it leaves the last anchor along its outgoing - // handle and arrives at the new corner anchor without a handle. + // The segment a click at `h` adds, if any: it leaves the last anchor along its outgoing + // handle and arrives at the anchor the click ends it on, with that anchor's handle. + let raw = self.hover_raw.unwrap_or(h); + let segment = + if cx.pen_rubber_band || cx.measurement_labels { click_end(cx, (id, si, first, last), raw, h, self.hover_mods) } else { None }; + if cx.pen_rubber_band + && let Some((end, end_h)) = segment + { let mut bp = BezPath::new(); bp.move_to(last); - if out.distance(last) > 1e-9 { - bp.curve_to(out, h, h); + if out.distance(last) > 1e-9 || end_h.distance(end) > 1e-9 { + bp.curve_to(out, end_h, end); } else { - bp.line_to(h); + bp.line_to(end); } o.push(Overlay::Path { path: bp, color: cx.doc.layer_color(id), width: 1.0, dashed: false }); } - if cx.measurement_labels && last.distance(h) > 1e-9 { - o.push(Overlay::Measure { p: h + Vec2::new(cx.tol(12.0), cx.tol(12.0)), text: cx.segment_measure_label(last, h) }); + if cx.measurement_labels + && let Some((end, _)) = segment + && last.distance(end) > 1e-9 + { + o.push(Overlay::Measure { p: h + Vec2::new(cx.tol(12.0), cx.tol(12.0)), text: cx.segment_measure_label(last, end) }); } } o.extend_from_slice(self.snap.guides()); @@ -641,6 +657,46 @@ impl PenTool { } } +/// Where a click ends the next segment of subpath `si` of path `id` (first anchor `first`, last +/// anchor `last`), and the incoming handle it arrives with, for a pointer at `raw` that snaps to +/// `h`. The anchors are picked in the order a press picks them: at `raw` first, then at `h`. On the +/// first anchor the path closes, with that anchor's incoming handle retracted +/// ([`PenTool::begin_close`]). On an end of another open path the two join, and the segment arrives +/// with that end's own handle on the joining side. Anywhere else the click adds a corner anchor at `h`. +/// None where the click adds no segment: on the last anchor (its outgoing handle retracts), with +/// Alt over the path (the Anchor Point tool takes the press, [`alt_converts`]), and on an end of +/// another path that lies on the last anchor (`path.join` merges the two ends into one anchor). +fn click_end(cx: &ToolContext, (id, si, first, last): (NodeId, usize, Point, Point), raw: Point, h: Point, m: Mods) -> Option<(Point, Point)> { + let tol = cx.tol(5.0).max(cx.point_tol()); + let closing_end = last_anchor(cx, id, Some(si)).filter(|(_, ai)| *ai > 0).map(|_| first); + match pick_endpoint(closing_end, last, raw, tol, Endpoint::First) { + Some(Endpoint::First) => return Some((first, first)), + Some(Endpoint::Last) => return None, + None => {} + } + if alt_converts(cx, raw, m) { + return None; + } + let raw_other = open_end_at(cx, raw, tol, Some((id, si))); + if raw_other.is_none() && h != raw { + match pick_endpoint(closing_end, last, h, tol, Endpoint::First) { + Some(Endpoint::First) => return Some((first, first)), + Some(Endpoint::Last) => return None, + None => {} + } + } + let other = raw_other.or_else(|| if h != raw { open_end_at(cx, h, tol, Some((id, si))) } else { None }); + let joined = other.and_then(|(other, osi, at_first)| { + let sp = cx.doc.node(other)?.path_data()?.subpaths.get(osi)?; + if at_first { sp.anchors.first().map(|a| (a.p, a.h_in)) } else { sp.anchors.last().map(|a| (a.p, a.h_out)) } + }); + match joined { + Some((end, _)) if end.distance(last) < 1e-6 => None, + Some(joined) => Some(joined), + None => Some((h, h)), + } +} + /// The first anchor of subpath `si` of path `id`. pub(crate) fn first_anchor(cx: &ToolContext, id: NodeId, si: usize) -> Option { cx.doc.node(id)?.path_data()?.subpaths.get(si)?.anchors.first().copied() diff --git a/crates/tools/src/pie.rs b/crates/tools/src/pie.rs index af79c1ce46..ae9d934954 100644 --- a/crates/tools/src/pie.rs +++ b/crates/tools/src/pie.rs @@ -115,9 +115,9 @@ impl PieWidget { out } - /// The widgets the Selection tool can drag (its bounding box showing). + /// The widgets the Selection tool can drag (its bounding box and the shape widgets showing). pub fn for_tool(cx: &ToolContext) -> Vec { - if !cx.show_bbox { + if !cx.show_bbox || !cx.shape_widgets { return vec![]; } Self::of(cx.doc, cx.selection, cx.zoom) @@ -248,9 +248,14 @@ mod tests { let w = PieWidget::of(&d, &s, 1.0); assert!(near(w[0].on, Point::new(200.0, 100.0)) && near(w[0].at, Point::new(200.0, 88.0)), "{w:?}"); assert!(near(w[1].at, Point::new(312.0, 150.0)), "{w:?}"); - // No widgets with the bounding box hidden, with nothing selected, or on another shape. + // No widgets with the bounding box or the shape widgets hidden, with nothing selected, or on + // another shape. let p = paint(); + assert_eq!(PieWidget::for_tool(&cx(&d, &s, &p)).len(), 2); assert!(PieWidget::for_tool(&ToolContext { show_bbox: false, ..cx(&d, &s, &p) }).is_empty()); + let hidden = ToolContext { shape_widgets: false, ..cx(&d, &s, &p) }; + assert!(PieWidget::for_tool(&hidden).is_empty()); + assert!(!over_widget(&hidden, w[1].at) && double_click(&hidden, w[1].at).is_none()); assert!(PieWidget::of(&d, &Selection::default(), 1.0).is_empty()); let (d, id) = doc_with_rect(); let mut s = Selection::default(); diff --git a/crates/tools/src/repeat_grid.rs b/crates/tools/src/repeat_grid.rs index 07187a6a5a..eecc6ba0fe 100644 --- a/crates/tools/src/repeat_grid.rs +++ b/crates/tools/src/repeat_grid.rs @@ -392,4 +392,24 @@ mod tests { assert_eq!(cursor(&c, g.rows_at), Some(Cursor::ResizeV)); assert_eq!(cursor(&c, g.corner_at), Some(Cursor::ResizeNwSe)); } + + #[test] + fn a_tool_switch_cancels_a_grid_handle_drag() { + use crate::{PointerEvent, PointerKind, Tool}; + let (doc, selection) = grid(); + let paint = paint(); + let c = cx(&doc, &selection, &paint); + let g = GridHandles::of(&doc, &selection, crate::select::selection_box(&c), c.zoom).unwrap(); + let mut t = crate::select::SelectionTool::default(); + assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, g.rows_at.x, g.rows_at.y)).is_empty()); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, g.rows_at.x, g.rows_at.y + 150.0)); + assert!(preview(&a).is_some(), "{a:?}"); + assert_eq!(t.deactivate(&c), vec![Action::Cancel]); + assert!(!t.busy()); + // A press that has not changed the grid leaves nothing to cancel. + t.pointer(&c, &PointerEvent::new(PointerKind::Down, g.rows_at.x, g.rows_at.y)); + assert!(t.busy()); + assert!(t.deactivate(&c).is_empty()); + assert!(!t.busy()); + } } diff --git a/crates/tools/src/repeat_radial.rs b/crates/tools/src/repeat_radial.rs index 42a9f4395f..7304570404 100644 --- a/crates/tools/src/repeat_radial.rs +++ b/crates/tools/src/repeat_radial.rs @@ -681,4 +681,26 @@ mod tests { assert_eq!(preview(&d.drag(h.instances_at + Vec2::new(0.0, 32.0))), Some(&json!({"instances": 9}))); assert!(matches!(d.finish().as_slice(), [Action::Commit])); } + + #[test] + fn a_tool_switch_cancels_a_radial_handle_drag() { + use crate::{PointerEvent, PointerKind, Tool}; + let (doc, selection) = radial(); + let paint = paint(); + let c = cx(&doc, &selection, &paint); + let h = RadialHandles::of(&doc, &selection, crate::select::selection_box(&c), c.zoom).unwrap(); + let out = (h.radius_at - h.center) / 100.0; + let to = h.radius_at + out * 25.0; + let mut t = crate::select::SelectionTool::default(); + assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, h.radius_at.x, h.radius_at.y)).is_empty()); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, to.x, to.y)); + assert_eq!(preview(&a), Some(&json!({"radius": 125.0})), "{a:?}"); + assert_eq!(t.deactivate(&c), vec![Action::Cancel]); + assert!(!t.busy()); + // A press that has not changed the repeat leaves nothing to cancel. + t.pointer(&c, &PointerEvent::new(PointerKind::Down, h.radius_at.x, h.radius_at.y)); + assert!(t.busy()); + assert!(t.deactivate(&c).is_empty()); + assert!(!t.busy()); + } } diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index e9c3e2bb03..acfd13d3ae 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -81,6 +81,18 @@ fn marquee_enclosed(cx: &ToolContext, inverted: bool, directional_inside: bool) inside != inverted } +/// What a press took the selection by, which decides what that point snaps to. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Grip { + /// A center or the pressed point: it lands on anchors and centers, or the bounds line up. + Point, + /// One of its anchors: it also lands on paths and where they cross ([`MoveSnap::by_anchor`]). + Anchor, + /// A point of a path's stroke, outline or edge ([`hold_point`]): it also lands on paths and + /// where they cross, and along a straight path the bounds still line up ([`MoveSnap::by_edge`]). + Edge, +} + #[derive(Clone, Debug, Default)] enum State { #[default] @@ -94,9 +106,9 @@ enum State { /// The point that snaps, moving with the pointer: `start`, or where a press on a path's /// stroke or beside its edge took hold of the path ([`hold_point`]). hold: Point, - /// The press grabbed the selection by an anchor (`start`): it snaps as - /// [`MoveSnap::by_anchor`] says. - by_anchor: bool, + /// What the press took the selection by: an anchor (`start`), a point of a path's edge + /// (`hold`), or neither. + grip: Grip, began: bool, /// Shift-pressed on this selected object: released without a drag, it leaves the /// selection. @@ -153,6 +165,8 @@ enum State { GridRepeat(crate::repeat_grid::GridDrag), /// Drag a radial repeat's instances or radius handle. RadialRepeat(crate::repeat_radial::RadialDrag), + /// Drag the divider of an Image Trace object in the Split view. + TraceSplit(crate::trace_split::SplitDrag), /// Dragging a bracket of type on a path. Bracket(BracketDrag), /// Dragging a 9-slice guide of the symbol being edited. @@ -252,6 +266,8 @@ pub(crate) struct MoveSnap { /// onto (#1534), and lines the bounds up with (#5746), within the Snapping Tolerance as drawing /// does; `points` holds them with Smart Guides off. rulers: Option, + /// Held by a point of a path's edge ([`Self::by_edge`]). + by_edge: bool, } impl MoveSnap { @@ -266,6 +282,13 @@ impl MoveSnap { Self::gather(cx, Targets::for_move_by_anchor) } + /// [`Self::by_anchor`] for a selection held by a point of a path's stroke, outline or edge + /// (#8568): that point also lands on the other art's paths and where they cross, and on a + /// straight path the bounds still line up, sliding along it ([`Targets::snap_held_onto_path`]). + pub(crate) fn by_edge(cx: &ToolContext) -> Self { + Self { by_edge: true, ..Self::gather(cx, Targets::for_move_by_anchor) } + } + fn gather(cx: &ToolContext, for_move: fn(&ToolContext, &[NodeId]) -> Targets) -> Self { let guides = cx.smart_guides && !cx.snap_to_grid; let points = |exclude: &[NodeId]| if cx.snap_to_grid { None } else { Targets::snap_to_point(cx, exclude) }; @@ -276,13 +299,14 @@ impl MoveSnap { copy_targets: guides.then(|| for_move(cx, &[])), copy_points: points(&[]), rulers: (guides && cx.snap_to_point).then(|| Targets::rulers(cx)), + by_edge: false, } } /// Snap to Grid and Snap to Pixel alone, for a move whose box is `bounds`: the grid lands an /// edge of the box on a gridline, and pixels put its top-left on whole pixels. pub(crate) fn grid_only(bounds: Option) -> Self { - Self { bounds, targets: None, points: None, copy_targets: None, copy_points: None, rulers: None } + Self { bounds, targets: None, points: None, copy_targets: None, copy_points: None, rulers: None, by_edge: false } } /// The move (`copy`: the copy) by `d` of the selection grabbed at `start`, snapped, and its @@ -317,9 +341,14 @@ impl MoveSnap { d = q - start; guides = ov; taken = [true; 2]; - } else if let Some((q, ov)) = t.snap_onto_path(start + d, cx.snap_tol(), self.rulers.as_ref()) { + } else if let Some((q, ov)) = if self.by_edge { + t.snap_held_onto_path(start + d, b + d, cx.snap_tol(), self.rulers.as_ref()) + } else { + t.snap_onto_path(start + d, cx.snap_tol(), self.rulers.as_ref()) + } { // Grabbed by an anchor ([`Self::by_anchor`]), it lands on a path near it, or where - // the path crosses another or a ruler guide, instead of lining the bounds up. + // the path crosses another or a ruler guide, instead of lining the bounds up. Held + // by its edge ([`Self::by_edge`]), along a straight path the bounds still line up. d = q - start; guides = ov; taken = [true; 2]; @@ -649,8 +678,13 @@ const HOVER_REACH: f64 = 6.0; /// hit, when the press is on its stroke or outline or within [`HOVER_REACH`] of it, else `p` /// ([`hold_on_path`]). That point snaps, so the path itself lands on a ruler guide (#3701). pub(crate) fn hold_point(cx: &ToolContext, h: &Hit, p: Point) -> Point { + held_on_path(cx, h, p).unwrap_or(p) +} + +/// [`hold_point`]'s point of the path hit, None when the press holds no point of it. +fn held_on_path(cx: &ToolContext, h: &Hit, p: Point) -> Option { let reach = if matches!(h.kind, HitKind::Stroke | HitKind::Outline) { f64::INFINITY } else { cx.tol(HOVER_REACH) }; - cx.doc.node(h.leaf).and_then(|n| n.path_data()).and_then(|pd| hold_on_path(pd, p, reach)).unwrap_or(p) + cx.doc.node(h.leaf).and_then(|n| n.path_data()).and_then(|pd| hold_on_path(pd, p, reach)) } /// While an opacity mask or a pattern is edited, a Shaper double-click selects a Shaper Group's @@ -831,7 +865,7 @@ impl Tool for SelectionTool { /// E during a marquee drag switches the marquee between the objects it touches and only the /// objects inside it. Escape during a drag (a move or an Alt-drag copy, a bounding-box scale or /// rotation, a marquee, a corner widget, a pie widget, a polygon's side widget, a blend widget, the Rotate All, Space, Move All or Select/Move widget, the brackets of type on a path, a mirror - /// axis, a grid repeat's handles, a ruler guide) cancels it: what it changed goes back, no copy + /// axis, a grid repeat's handles, an Image Trace divider, a ruler guide) cancels it: what it changed goes back, no copy /// is left, and the tool waits for the next press. With the pointer loaded with text, Escape /// drops the text. fn key(&mut self, cx: &ToolContext, key: ToolKey, mods: Mods) -> Vec { @@ -905,14 +939,19 @@ impl Tool for SelectionTool { out } - /// Switching tools during a drag of a blend widget, a corner widget, a pie widget or a - /// polygon's side widget cancels it, as Escape does: its value goes back. + /// Switching tools during a drag of a blend widget, a corner widget, a pie widget, a + /// polygon's side widget, a mirror axis, a grid or radial repeat's handles or an Image Trace + /// divider cancels it, as Escape does: its value goes back. fn deactivate(&mut self, _cx: &ToolContext) -> Vec { match std::mem::take(&mut self.state) { State::BlendWidget(d) if d.adjusting() => vec![Action::Cancel], State::Corner(c) if c.adjusting() => vec![Action::Cancel], State::Pie(d) if d.adjusting() => vec![Action::Cancel], State::Sides(d) => d.cancel(), + State::Mirror(d) => d.cancel(), + State::GridRepeat(d) => d.cancel(), + State::RadialRepeat(d) => d.cancel(), + State::TraceSplit(d) => d.cancel(), State::BlendWidget(_) | State::Corner(_) | State::Pie(_) => vec![], other => { self.state = other; @@ -926,7 +965,9 @@ impl Tool for SelectionTool { State::Marquee { .. } => key == ToolKey::Letter('e'), State::Corner(_) => matches!(key, ToolKey::Up | ToolKey::Down), State::BlendWidget(_) => matches!(key, ToolKey::Up | ToolKey::Down | ToolKey::Left | ToolKey::Right), - State::Loaded { .. } | State::Mirror(_) | State::GridRepeat(_) | State::RadialRepeat(_) | State::NineSlice(_) => key == ToolKey::Escape, + State::Loaded { .. } | State::Mirror(_) | State::GridRepeat(_) | State::RadialRepeat(_) | State::TraceSplit(_) | State::NineSlice(_) => { + key == ToolKey::Escape + } _ => false, } } @@ -970,6 +1011,7 @@ impl Tool for SelectionTool { State::Mirror(d) => d.adjusting(), State::GridRepeat(d) => d.adjusting(), State::RadialRepeat(d) => d.adjusting(), + State::TraceSplit(d) => d.adjusting(), _ => false, } } @@ -1029,7 +1071,7 @@ impl Tool for SelectionTool { { let several = cx.selection.objects.len() > 1 || !cx.selection.guides.is_empty(); let (deselect, key) = if m.shift { (Some(id), None) } else { (None, (several && !m.alt).then_some(id)) }; - self.state = State::Moving { start: p, press: p, hold: center, by_anchor: false, began: false, deselect, key, exclude: None }; + self.state = State::Moving { start: p, press: p, hold: center, grip: Grip::Point, began: false, deselect, key, exclude: None }; return vec![]; } // 3. Objects: Cmd/Ctrl-click selects the one under the selected one (cycling). @@ -1038,7 +1080,7 @@ impl Tool for SelectionTool { && let Some(behind) = object_behind(cx, p) { self.state = - State::Moving { start: p, press: p, hold: p, by_anchor: false, began: false, deselect: None, key: None, exclude: None }; + State::Moving { start: p, press: p, hold: p, grip: Grip::Point, began: false, deselect: None, key: None, exclude: None }; return vec![Action::Exec("select.set".into(), json!({ "ids": [behind.0] }))]; } let (hit, scope) = match selected_source_hit(cx, p) { @@ -1060,9 +1102,13 @@ impl Tool for SelectionTool { out.push(Action::Exec("select.set".into(), json!({ "ids": [top.0] }))); } // Grabbed by no anchor or centre, a press on a path's stroke or beside its - // edge holds the path there, and that point of it snaps (#3701). - let hold = if grabbed.is_some() { grab } else { hold_point(cx, &h, p) }; - self.state = State::Moving { start: grab, press: p, hold, by_anchor, began: false, deselect, key, exclude }; + // edge holds the path there, and that point of it snaps (#3701). Like a + // grabbed anchor, that point also lands on the other art's paths (#8568). + let (hold, grip) = match grabbed { + Some(_) => (grab, if by_anchor { Grip::Anchor } else { Grip::Point }), + None => held_on_path(cx, &h, p).map_or((p, Grip::Point), |q| (q, Grip::Edge)), + }; + self.state = State::Moving { start: grab, press: p, hold, grip, began: false, deselect, key, exclude }; out } None => { @@ -1071,8 +1117,8 @@ impl Tool for SelectionTool { } } } - (PointerKind::Drag, State::Moving { start, press, hold, by_anchor, began, exclude, .. }) => { - self.drag_moving(cx, p, m, ev.backquote, (start, press, hold, by_anchor, began), exclude) + (PointerKind::Drag, State::Moving { start, press, hold, grip, began, exclude, .. }) => { + self.drag_moving(cx, p, m, ev.backquote, (start, press, hold, grip, began), exclude) } (PointerKind::Drag, State::Scaling { handle, bx, areas }) => { self.last_backquote = ev.backquote; @@ -1145,9 +1191,11 @@ impl Tool for SelectionTool { self.state = State::Sides(d); out } - (PointerKind::Up, State::Sides(d)) => { + (PointerKind::Up, State::Sides(mut d)) => { self.state = State::Idle; - d.finish() + let mut out = d.drag(cx, p); + out.extend(d.finish()); + out } (PointerKind::Drag, State::BlendWidget(mut d)) => { let out = d.drag(cx, p); @@ -1296,6 +1344,9 @@ impl Tool for SelectionTool { if let State::RadialRepeat(d) = &self.state { return d.cursor(cx); } + if let State::TraceSplit(d) = &self.state { + return d.cursor(cx); + } if matches!(self.state, State::NineSlice(_)) || (matches!(self.state, State::Idle) && crate::nineslice::over_guide(cx, p)) { return Cursor::Move; } @@ -1303,8 +1354,10 @@ impl Tool for SelectionTool { && !m.cmd && !m.ctrl && !m.alt - && let Some(cursor) = - crate::mirror::cursor(cx, p).or_else(|| crate::repeat_grid::cursor(cx, p)).or_else(|| crate::repeat_radial::cursor(cx, p)) + && let Some(cursor) = crate::mirror::cursor(cx, p) + .or_else(|| crate::repeat_grid::cursor(cx, p)) + .or_else(|| crate::repeat_radial::cursor(cx, p)) + .or_else(|| crate::trace_split::cursor(cx, p)) { return cursor; } @@ -1668,6 +1721,21 @@ impl SelectionTool { _ => return Some(vec![]), } } + if let State::TraceSplit(mut d) = self.state.clone() { + match ev.kind { + PointerKind::Drag | PointerKind::Up => { + let mut out = d.drag(cx, ev.pos); + if ev.kind == PointerKind::Up { + out.extend(d.finish()); + self.state = State::Idle; + } else { + self.state = State::TraceSplit(d); + } + return Some(out); + } + _ => return Some(vec![]), + } + } if matches!(self.state, State::Idle) && ev.kind == PointerKind::Down && let Some(d) = crate::mirror::MirrorDrag::hit(cx, ev.pos, ev.mods) @@ -1692,6 +1760,14 @@ impl SelectionTool { self.hover = None; return Some(vec![]); } + if matches!(self.state, State::Idle) + && ev.kind == PointerKind::Down + && let Some(d) = crate::trace_split::SplitDrag::hit(cx, ev.pos, ev.mods) + { + self.state = State::TraceSplit(d); + self.hover = None; + return Some(vec![]); + } None } @@ -1841,7 +1917,16 @@ impl SelectionTool { /// `by_anchor`: `grab` is an anchor of it. fn press_nothing(&mut self, cx: &ToolContext, p: Point, grab: Point, by_anchor: bool, m: Mods) { self.state = if !m.shift && selected_hidden_at(cx.doc, p, cx.selection_hit_options(), &cx.selection.objects).is_some() { - State::Moving { start: grab, press: p, hold: grab, by_anchor, began: false, deselect: None, key: None, exclude: None } + State::Moving { + start: grab, + press: p, + hold: grab, + grip: if by_anchor { Grip::Anchor } else { Grip::Point }, + began: false, + deselect: None, + key: None, + exclude: None, + } } else { State::Marquee { start: p, cur: p, toggle: m.shift, enclosed: false, directional_inside: false } }; @@ -1853,7 +1938,7 @@ impl SelectionTool { p: Point, m: Mods, backquote: bool, - (start, press, hold, by_anchor, began): (Point, Point, Point, bool, bool), + (start, press, hold, grip, began): (Point, Point, Point, Grip, bool), exclude: Option<(NodeId, NodeId)>, ) -> Vec { let mut out = vec![]; @@ -1861,7 +1946,11 @@ impl SelectionTool { if p.distance(press) < Self::drag_threshold(cx) { return out; } - let gather = if by_anchor { MoveSnap::by_anchor } else { MoveSnap::new }; + let gather = match grip { + Grip::Point => MoveSnap::new, + Grip::Anchor => MoveSnap::by_anchor, + Grip::Edge => MoveSnap::by_edge, + }; // A Shift-drag from a highlighted object of the Global Edit selects it and moves it // with the selection: its snap targets are gathered for the selection with it. self.moving = Some(match exclude { @@ -1882,7 +1971,7 @@ impl SelectionTool { } // Shift has already constrained `d`: any change is a snap. self.snapped = (d - unsnapped).hypot() > 1e-9; - self.state = State::Moving { start, press, hold, by_anchor, began: true, deselect: None, key: None, exclude: None }; + self.state = State::Moving { start, press, hold, grip, began: true, deselect: None, key: None, exclude: None }; self.measure = cx.measurement_labels.then(|| (p, cx.offset_label(d.x, d.y))); let mut params = json!({ "matrix": matrix_json(Affine::translate(d)), "copy": m.alt }); if backquote { diff --git a/crates/tools/src/select/tests.rs b/crates/tools/src/select/tests.rs index 5c52201a6f..82588992b7 100644 --- a/crates/tools/src/select/tests.rs +++ b/crates/tools/src/select/tests.rs @@ -247,10 +247,23 @@ fn doc_with_rect_and_lines(lines: &[(Point, Point)]) -> (vectorcraft_doc::Docume /// The rectangle of `d` grabbed at `(gx, gy)` (hovered first, so a press near an anchor grabs it) /// and dragged to `to`, with Smart Guides on or off (`smart`): the point it was grabbed at after the /// move, and the label shown. -fn grabbed_and_dragged(d: &vectorcraft_doc::Document, id: NodeId, smart: bool, (gx, gy): (f64, f64), to: (f64, f64)) -> (Point, Option) { +fn grabbed_and_dragged(d: &vectorcraft_doc::Document, id: NodeId, smart: bool, grab: (f64, f64), to: (f64, f64)) -> (Point, Option) { + grabbed_and_dragged_in(d, id, smart, false, grab, to) +} + +/// [`grabbed_and_dragged`] in Preview or, with `outline`, in Outline view. +fn grabbed_and_dragged_in( + d: &vectorcraft_doc::Document, + id: NodeId, + smart: bool, + outline: bool, + (gx, gy): (f64, f64), + to: (f64, f64), +) -> (Point, Option) { let (none, mut picked, p) = (Selection::default(), Selection::default(), paint()); picked.add(id); - let (before, after) = (ToolContext { smart_guides: smart, ..cx(d, &none, &p) }, ToolContext { smart_guides: smart, ..cx(d, &picked, &p) }); + let (before, after) = + (ToolContext { smart_guides: smart, outline, ..cx(d, &none, &p) }, ToolContext { smart_guides: smart, outline, ..cx(d, &picked, &p) }); let mut t = SelectionTool::default(); t.pointer(&before, &ev(PointerKind::Move, gx, gy)); t.pointer(&before, &ev(PointerKind::Down, gx, gy)); @@ -286,6 +299,199 @@ fn a_move_grabbed_by_an_anchor_lands_it_on_another_path() { assert!(off_line(corner) > 0.4, "the corner lands at {corner:?}"); } +/// #8568: a selection held by a point of its path's edge (pressed on the edge, or on the fill just +/// beside it) lands that point on another path ("path") with Smart Guides, in Preview and in +/// Outline view. +#[test] +fn a_move_held_by_a_paths_edge_lands_it_on_another_path() { + let (a, b) = (Point::new(300.0, 400.0), Point::new(500.0, 300.0)); + let (d, id) = doc_with_rect_and_lines(&[(a, b)]); + let off_line = |q: Point| ((b - a).cross(q - a) / (b - a).hypot()).abs(); + for outline in [false, true] { + // Hold the rectangle by its bottom edge at (150, 200), away from its corners and center, + // and drop that point half a point beside the line. + let (edge, label) = grabbed_and_dragged_in(&d, id, true, outline, (150.0, 200.0), (430.0, 335.5)); + assert!(off_line(edge) < 1e-9, "outline {outline}: the edge lands at {edge:?}, {} off the line", off_line(edge)); + assert!((edge.x - 430.0).abs() < 0.5, "outline {outline}: {edge:?}"); + assert_eq!(label.as_deref(), Some("path"), "outline {outline}"); + // With Smart Guides off, the edge stays where it was dragged. + let (edge, _) = grabbed_and_dragged_in(&d, id, false, outline, (150.0, 200.0), (430.0, 335.5)); + assert!(off_line(edge) > 0.4, "outline {outline}: the edge lands at {edge:?}"); + } + // Pressed on the fill 3 points inside the bottom edge, the press holds the edge at + // (150, 200), and that point lands on the line. + let (edge, label) = pressed_and_dragged(&d, id, (150.0, 197.0), Point::new(150.0, 200.0), (430.0, 332.5), false); + assert!(off_line(edge) < 1e-9, "the edge lands at {edge:?}, {} off the line", off_line(edge)); + assert_eq!(label.as_deref(), Some("path")); +} + +/// The rectangle of `d` pressed at `press` (not hovered first) and dragged to `to`, Alt held for a +/// copy with `alt`: where its point `at` goes, and the label shown. +fn pressed_and_dragged( + d: &vectorcraft_doc::Document, + id: NodeId, + press: (f64, f64), + at: Point, + to: (f64, f64), + alt: bool, +) -> (Point, Option) { + pressed_and_dragged_with(d, id, press, at, to, alt, true) +} + +/// [`pressed_and_dragged`] with Smart Guides › Alignment Guides on or off (`lines`). +fn pressed_and_dragged_with( + d: &vectorcraft_doc::Document, + id: NodeId, + press: (f64, f64), + at: Point, + to: (f64, f64), + alt: bool, + lines: bool, +) -> (Point, Option) { + let (none, mut picked, p) = (Selection::default(), Selection::default(), paint()); + picked.add(id); + let (before, after) = + (ToolContext { alignment_guides: lines, ..cx(d, &none, &p) }, ToolContext { alignment_guides: lines, ..cx(d, &picked, &p) }); + let mut t = SelectionTool::default(); + t.pointer(&before, &ev(PointerKind::Down, press.0, press.1)); + let a = t.pointer(&after, &ev(PointerKind::Drag, to.0, to.1).with_mods(Mods { alt, ..Mods::default() })); + let Some(Action::Preview(_, v)) = a.iter().find(|a| matches!(a, Action::Preview(..))) else { panic!("{a:?}") }; + let label = t.overlays(&after).iter().find_map(|o| match o { + Overlay::Label { text, .. } => Some(text.clone()), + _ => None, + }); + (at + Vec2::new(v["matrix"][4].as_f64().unwrap(), v["matrix"][5].as_f64().unwrap()), label) +} + +/// #8568: a selection held by its edge that lands on a straight path still lines its bounds up +/// along that path: on a level path the held point keeps the path's y, and the bounds line up on +/// x with the other art, else with a ruler guide. A press on the fill farther inside than 6 points +/// holds no edge and lines the bounds up as before, and so does an edge hold with no path in reach. +#[test] +fn a_move_held_by_an_edge_on_a_straight_path_still_lines_its_bounds_up_along_it() { + let (mut d, id) = doc_with_rect_and_lines(&[(Point::new(300.0, 300.0), Point::new(500.0, 300.0))]); + // Held by the top edge at (130, 100) and dropped at (331, 300.5): the point lands on the path, + // and the left side (at 301) lines up with the path's start at x 300. + let top = Point::new(130.0, 100.0); + let (edge, label) = pressed_and_dragged(&d, id, (130.0, 100.0), top, (331.0, 300.5), false); + assert!(edge.distance(Point::new(330.0, 300.0)) < 1e-9, "the edge lands at {edge:?}"); + assert_eq!(label.as_deref(), Some("path")); + // With Alignment Guides off, no line shows, and the bounds still line up. + let (edge, _) = pressed_and_dragged_with(&d, id, (130.0, 100.0), top, (331.0, 300.5), false, false); + assert!(edge.distance(Point::new(330.0, 300.0)) < 1e-9, "the edge lands at {edge:?}"); + // A fill press 3 points inside the edge holds it the same way. + let (edge, _) = pressed_and_dragged(&d, id, (130.0, 103.0), top, (331.0, 303.5), false); + assert!(edge.distance(Point::new(330.0, 300.0)) < 1e-9, "the edge lands at {edge:?}"); + // A fill press 10 points inside holds no edge: the bounds line up on x, and the pressed point + // does not land on the path. + let (grip, _) = pressed_and_dragged(&d, id, (130.0, 110.0), Point::new(130.0, 110.0), (331.0, 300.5), false); + assert!(grip.distance(Point::new(330.0, 300.5)) < 1e-9, "the grip lands at {grip:?}"); + // Held by the edge with no path in reach, the bounds line up on x. + let (edge, _) = pressed_and_dragged(&d, id, (130.0, 100.0), top, (331.0, 280.0), false); + assert!(edge.distance(Point::new(330.0, 280.0)) < 1e-9, "the edge lands at {edge:?}"); + // With a ruler guide at x 320 and nothing else in line, the left side (at 321) goes onto it + // while the point stays on the path. + d.add_ruler_guide(&vectorcraft_doc::Guide::new(true, 320.0)); + let (edge, label) = pressed_and_dragged(&d, id, (130.0, 100.0), top, (351.0, 300.5), false); + assert!(edge.distance(Point::new(350.0, 300.0)) < 1e-9, "the edge lands at {edge:?}"); + assert_eq!(label.as_deref(), Some("path")); +} + +/// #8568: near the end of a steep straight path, the bounds of a selection held by its edge line +/// up by the shortest slide that keeps the held point on the path, not by a shorter one that +/// would take it past the path's end. +#[test] +fn a_move_held_by_an_edge_slides_only_within_the_path() { + let (a, b) = (Point::new(300.0, 300.0), Point::new(310.0, 400.0)); + // Two upright paths far below: lining the left side up with the one at 269.95 slides the + // held point 6.5 back along the path, past its start, and with the one at 271.343 slides it + // 7.5 on. + let (d, id) = doc_with_rect_and_lines(&[ + (a, b), + (Point::new(269.95, 440.0), Point::new(269.95, 490.0)), + (Point::new(271.343, 440.0), Point::new(271.343, 490.0)), + ]); + let u = (b - a) / (b - a).hypot(); + // Dropped on the path 6 points from its start, the top edge's point at (130, 100) leaves the + // left side at 30 points before it. + let q = a + u * 6.0; + let (edge, label) = pressed_and_dragged(&d, id, (130.0, 100.0), Point::new(130.0, 100.0), (q.x, q.y), false); + let off_line = (b - a).cross(edge - a) / (b - a).hypot(); + assert!(off_line.abs() < 1e-9, "the edge lands at {edge:?}, {off_line} off the path"); + assert!((edge.x - 30.0 - 271.343).abs() < 1e-9, "the left side lands at {}", edge.x - 30.0); + assert_eq!(label.as_deref(), Some("path")); +} + +/// #8568: a straight path drawn with its handles pulled out along it counts as straight, also +/// with a handle reaching past the far end while the curve stays between its ends: a selection +/// held by its edge slides along it to line its bounds up, as along a plain line. +#[test] +fn a_move_held_by_an_edge_slides_along_a_straight_path_with_handles() { + use vectorcraft_geom::{Anchor, AnchorKind, PathData, SubPath}; + let (a, b) = (Point::new(300.0, 300.0), Point::new(500.0, 300.0)); + for (out, into) in [(350.0, 450.0), (520.0, 480.0)] { + let (mut d, id) = doc_with_rect(); + let l = d.layers[0].id; + let n = d.alloc_id(); + let anchors = vec![ + Anchor { p: a, h_in: a, h_out: Point::new(out, 300.0), kind: AnchorKind::Corner }, + Anchor { p: b, h_in: Point::new(into, 300.0), h_out: b, kind: AnchorKind::Corner }, + ]; + let path = PathData::single(SubPath::new(anchors, false)); + d.insert(Some(l), 1, vectorcraft_doc::Node::path(n, path, vectorcraft_doc::Appearance::default_art())).unwrap(); + let (edge, label) = pressed_and_dragged(&d, id, (130.0, 100.0), Point::new(130.0, 100.0), (331.0, 300.5), false); + assert!(edge.distance(Point::new(330.0, 300.0)) < 1e-9, "handles at {out} and {into}: the edge lands at {edge:?}"); + assert_eq!(label.as_deref(), Some("path")); + } +} + +/// #8568: an artboard's ruler guide ends at the artboard's edge. A selection held by its edge +/// slides along a shallow path onto such a guide when the slide brings its bounds within reach of +/// the guide's end, even though they start out beyond it. +#[test] +fn a_move_held_by_an_edge_slides_onto_an_artboard_guide_it_reaches() { + let (a, b) = (Point::new(640.0, 300.0), Point::new(440.0, 310.0)); + let (mut d, id) = doc_with_rect_and_lines(&[(a, b)]); + let u = (b - a) / (b - a).hypot(); + // Held by the left edge at (100, 130) and dropped on the path where x is 507: the top is 30 + // above the point, and the middle at x 557 is beyond the guide's end at 500 by more than half + // the width and the Snapping Tolerance. A slide of 6 along the path puts the top on the guide. + let q = a + u * ((a.x - 507.0) / -u.x); + let guide = q.y - 30.0 + u.y * 6.0; + let board = d.artboards[0].id; + d.add_ruler_guide(&vectorcraft_doc::Guide { artboard: Some(board), ..vectorcraft_doc::Guide::new(false, guide) }); + let (edge, label) = pressed_and_dragged(&d, id, (100.0, 130.0), Point::new(100.0, 130.0), (q.x, q.y), false); + assert!(edge.distance(q + u * 6.0) < 1e-9, "the edge lands at {edge:?}, not {:?}", q + u * 6.0); + assert_eq!(label.as_deref(), Some("path")); +} + +/// #8568: a selection held by its edge lands that point where two other paths cross, and where a +/// path crosses a ruler guide ("intersect"), as an anchor does. +#[test] +fn a_move_held_by_an_edge_lands_it_where_paths_cross() { + let bottom = Point::new(150.0, 200.0); + let (mut d, id) = + doc_with_rect_and_lines(&[(Point::new(300.0, 400.0), Point::new(500.0, 300.0)), (Point::new(460.0, 250.0), Point::new(460.0, 420.0))]); + let (edge, label) = pressed_and_dragged(&d, id, (150.0, 200.0), bottom, (460.4, 320.5), false); + assert!(edge.distance(Point::new(460.0, 320.0)) < 1e-9, "the edge lands at {edge:?}"); + assert_eq!(label.as_deref(), Some("intersect")); + d.add_ruler_guide(&vectorcraft_doc::Guide::new(true, 440.0)); + let (edge, label) = pressed_and_dragged(&d, id, (150.0, 200.0), bottom, (440.5, 330.5), false); + assert!(edge.distance(Point::new(440.0, 330.0)) < 1e-9, "the edge lands at {edge:?}"); + assert_eq!(label.as_deref(), Some("intersect")); +} + +/// #8568: an Alt copy held by its edge snaps to the original too: dragged along the original's +/// top edge, the held point stays on that edge and the copy's right side lines up with another +/// path. +#[test] +fn a_copy_held_by_an_edge_slides_along_the_originals_edge() { + let (d, id) = doc_with_rect_and_lines(&[(Point::new(230.0, 300.0), Point::new(230.0, 400.0))]); + let (edge, label) = pressed_and_dragged(&d, id, (130.0, 100.0), Point::new(130.0, 100.0), (161.0, 100.5), true); + assert!(edge.distance(Point::new(160.0, 100.0)) < 1e-9, "the edge lands at {edge:?}"); + assert_eq!(label.as_deref(), Some("path")); +} + /// #7411: a selection grabbed by an anchor lands it where two other paths cross ("intersect"), and /// on another object's anchor near the path rather than on the path. #[test] @@ -945,6 +1151,23 @@ fn a_shift_move_lands_the_edges_on_a_ruler_guide() { assert!(moved_by(m, (231.0, 0.0)), "{m:?}"); } +/// #4312: a diagonal Shift move reaches an artboard guide only where the move puts the bounds +/// within the guide's run: the middle at x 556 is beyond the guide's end at 500 by more than half +/// the width and the Snapping Tolerance, so the top (506) does not slide onto the guide at 503. +#[test] +fn a_diagonal_shift_move_reaches_an_artboard_guide_where_the_move_puts_it() { + let (mut d, id) = doc_with_rect(); + d.artboards[0].rect = Rect::new(0.0, 0.0, 500.0, 1600.0); + let board = d.artboards[0].id; + d.add_ruler_guide(&vectorcraft_doc::Guide { artboard: Some(board), ..vectorcraft_doc::Guide::new(false, 503.0) }); + let mut s = Selection::default(); + s.add(id); + let p = paint(); + let c = cx(&d, &s, &p); + let (m, _) = shift_moved(&c, (556.0, 556.0)); + assert!(moved_by(m, (406.0, 406.0)), "{m:?}"); +} + /// With Smart Guides on, a moved selection reaches a ruler guide within the Snapping Tolerance /// (4 px), as drawing and handle drags do; with Smart Guides off, Snap to Point reaches it within /// its own distance (2 px). diff --git a/crates/tools/src/settings.rs b/crates/tools/src/settings.rs index 97e980e3c0..a0800532b4 100644 --- a/crates/tools/src/settings.rs +++ b/crates/tools/src/settings.rs @@ -23,7 +23,27 @@ const ROWS: &[Row] = &[ // Global Brush Dimensions. (LIQUIFY, Some("liquify"), &["width", "height", "angle", "intensity", "usePressure", "showBrush"]), (LIQUIFY, None, &["detail", "simplify", "simplifyOn", "rate", "complexity", "horizontal", "vertical", "affectAnchors", "affectIn", "affectOut"]), - (SYMBOLISM, Some("symbolism"), &["diameter", "intensity", "density"]), + // Symbolism Tools Options: the general options, then the Symbol Sprayer's and the Symbol Sizer's. + ( + SYMBOLISM, + Some("symbolism"), + &[ + "diameter", + "intensity", + "density", + "usePressure", + "method", + "showBrush", + "sprayScrunch", + "spraySize", + "spraySpin", + "sprayScreen", + "sprayStain", + "sprayStyle", + "proportional", + "affectsDensity", + ], + ), (&["mirrorCut"], None, &["axis", "keep"]), (&["puppetWarp"], None, &["showMesh", "expand"]), (&["arc"], None, &["closed", "lengthX", "lengthY", "reference", "baseAlong", "slope", "fillArc"]), @@ -79,6 +99,7 @@ const ROWS: &[Row] = &[ (&[crate::addons::extend_path::ID], None, &["mode"]), (&[crate::addons::corner_tool::ID], None, &["radius", "kind"]), (&[crate::addons::shared_edge::ID], None, &["diameter", "tolerance", "together"]), + (&[crate::addons::tangent_circle::ID], None, &["radius"]), (&[crate::addons::smart_pen::ID], None, &["next"]), // The kind first: a new kind resets the values after it. (&[crate::addons::parametric_shape::ID], None, &["kind", "count", "a", "b", "radius", "width", "height", "rotation"]), diff --git a/crates/tools/src/shape.rs b/crates/tools/src/shape.rs index 6685dd20f2..2a723bd578 100644 --- a/crates/tools/src/shape.rs +++ b/crates/tools/src/shape.rs @@ -492,7 +492,11 @@ impl ShapeTool { PointerKind::Up => match self.widget.take() { Some(WidgetDrag::Corner(c)) => c.finish(), Some(WidgetDrag::Pie(d)) => d.finish(), - Some(WidgetDrag::Sides(d)) => d.finish(), + Some(WidgetDrag::Sides(mut d)) => { + let mut out = d.drag(cx, ev.pos); + out.extend(d.finish()); + out + } None => vec![], }, _ => vec![], diff --git a/crates/tools/src/shape/tests.rs b/crates/tools/src/shape/tests.rs index d52cf374d4..59ae1d8e83 100644 --- a/crates/tools/src/shape/tests.rs +++ b/crates/tools/src/shape/tests.rs @@ -1354,6 +1354,103 @@ fn a_shape_tool_drags_a_polygons_side_widget() { assert!(matches!(a.last(), Some(Action::Preview(cmd, _)) if cmd == "shape.line"), "{a:?}"); } +/// With a shape tool, the side widget's release is read where it happens, with or without a drag +/// event there first, and switching tools during the drag puts the count back, as Escape does. +#[test] +fn a_shape_tools_side_widget_drag_ends_at_the_release_and_cancels_on_a_tool_switch() { + use vectorcraft_doc::{Appearance, LiveShape, Node, NodeKind}; + let shape = + LiveShape::Polygon { radius: 80.0, sides: 5, xf: Affine::translate((250.0, 250.0)), radii: vec![], kinds: vec![], radii_relative: false }; + let mut d = vectorcraft_doc::Document::new(500.0, 500.0); + let (l, id) = (d.layers[0].id, d.alloc_id()); + let mut n = Node::path(id, shape.to_path(), Appearance::default_art()); + if let NodeKind::Path { live: slot, .. } = &mut n.kind { + *slot = Some(Box::new(shape)); + } + d.insert(Some(l), 0, n).unwrap(); + let mut s = Selection::default(); + s.add(id); + let p = paint(); + let c = cx(&d, &s, &p); + let (w, _) = crate::sidewidget::SideWidget::for_tool(&c).expect("a side widget"); + let at = |kind: PointerKind, px: f64| PointerEvent::new(kind, w.at.x, w.at.y + px); + let sides = |n: u32| Action::Preview("object.setLiveShape".into(), json!({ "id": id.0, "sides": n })); + let mut t = ShapeTool::new("polygon"); + t.pointer(&c, &at(PointerKind::Down, 0.0)); + assert_eq!(t.pointer(&c, &at(PointerKind::Drag, 12.0)), vec![Action::Begin("Live Shape".into()), sides(6)]); + assert_eq!(t.pointer(&c, &at(PointerKind::Up, 0.0)), vec![sides(5), Action::Cancel]); + assert!(!t.busy()); + t.pointer(&c, &at(PointerKind::Down, 0.0)); + t.pointer(&c, &at(PointerKind::Drag, 12.0)); + assert_eq!(t.pointer(&c, &at(PointerKind::Up, 24.0)), vec![sides(7), Action::Commit]); + t.pointer(&c, &at(PointerKind::Down, 0.0)); + t.pointer(&c, &at(PointerKind::Drag, 12.0)); + assert_eq!(t.deactivate(&c), vec![Action::Cancel]); + assert!(!t.busy() && !t.transforming()); + // A press that changed nothing sends nothing. + t.pointer(&c, &at(PointerKind::Down, 0.0)); + assert!(t.deactivate(&c).is_empty()); + assert!(!t.busy()); +} + +/// With Show Shape Widgets off, the shape tools neither show nor take a selected live rectangle's +/// corner widget, a live ellipse's pie widget or a live polygon's side widget: the pointer there is +/// the tool's own, a drag from there draws a new shape and a double-click asks for nothing. With it +/// on, the same drag adjusts the widget. +#[test] +fn hidden_shape_widgets_do_not_answer_a_shape_tool() { + use vectorcraft_doc::{Appearance, LiveShape, Node, NodeKind}; + let live = |shape: LiveShape| { + let mut d = vectorcraft_doc::Document::new(500.0, 500.0); + let (l, id) = (d.layers[0].id, d.alloc_id()); + let mut n = Node::path(id, shape.to_path(), Appearance::default_art()); + if let NodeKind::Path { live: slot, .. } = &mut n.kind { + *slot = Some(Box::new(shape)); + } + d.insert(Some(l), 0, n).unwrap(); + let mut s = Selection::default(); + s.add(id); + (d, s) + }; + let xf = Affine::translate((100.0, 100.0)); + let p = paint(); + let rect = live(LiveShape::Rectangle { w: 100.0, h: 100.0, radii: [0.0; 4], kinds: Default::default(), radii_relative: false, xf }); + let ellipse = live(LiveShape::Ellipse { w: 200.0, h: 100.0, pie: (0.0, 360.0), xf }); + let polygon = live(LiveShape::Polygon { + radius: 80.0, + sides: 5, + xf: Affine::translate((250.0, 250.0)), + radii: vec![], + kinds: vec![], + radii_relative: false, + }); + let side = crate::sidewidget::SideWidget::for_tool(&cx(&polygon.0, &polygon.1, &p)).expect("a side widget").0.at; + // The corner widget 10 px inside the box's top-left corner, the pie widgets 12 px right of the + // ellipse, and the side widget. + let (far, m) = (Point::new(480.0, 480.0), Mods::default()); + for ((d, s), at) in [(&rect, Point::new(110.0, 110.0)), (&ellipse, Point::new(312.0, 150.0)), (&polygon, side)] { + let shown = cx(d, s, &p); + let hidden = ToolContext { shape_widgets: false, ..cx(d, s, &p) }; + let drag = |t: &mut ShapeTool, c: &ToolContext| { + t.pointer(c, &PointerEvent::new(PointerKind::Down, at.x, at.y)); + let a = t.pointer(c, &PointerEvent::new(PointerKind::Drag, at.x + 20.0, at.y + 25.0)); + t.pointer(c, &PointerEvent::new(PointerKind::Up, at.x + 20.0, at.y + 25.0)); + a + }; + for id in ["rectangle", "roundedRectangle", "ellipse", "polygon", "star"] { + let mut t = ShapeTool::new(id); + assert_ne!(t.cursor(&shown, at, m), t.cursor(&shown, far, m), "{id} at {at:?}"); + assert_eq!(t.cursor(&hidden, at, m), t.cursor(&hidden, far, m), "{id} at {at:?}"); + let a = drag(&mut t, &shown); + assert!(matches!(a.last(), Some(Action::Preview(cmd, _)) if cmd == "object.setLiveShape"), "{id} at {at:?}: {a:?}"); + let a = drag(&mut t, &hidden); + assert!(matches!(a.last(), Some(Action::Preview(cmd, _)) if cmd.starts_with("shape.")), "{id} at {at:?}: {a:?}"); + assert!(t.pointer(&hidden, &PointerEvent::new(PointerKind::DoubleClick, at.x, at.y)).is_empty(), "{id} at {at:?}"); + assert!(!t.busy(), "{id}"); + } + } +} + /// Switching away from a shape tool or the Selection tool during a drag of a corner, pie or side /// widget cancels it, as Escape does: the shape goes back. After a press that has not moved there /// is nothing to put back. diff --git a/crates/tools/src/sidewidget.rs b/crates/tools/src/sidewidget.rs index 7928238d51..f026a41c35 100644 --- a/crates/tools/src/sidewidget.rs +++ b/crates/tools/src/sidewidget.rs @@ -54,10 +54,10 @@ impl SideWidget { (at.x.is_finite() && at.y.is_finite()).then_some(Self { id, at, sides: *sides }) } - /// The widget the tool can drag (its bounding box showing). + /// The widget the tool can drag (its bounding box and the shape widgets showing). pub fn for_tool(cx: &ToolContext) -> Option<(Self, OrientedBox)> { // One object or none: a larger selection's box is not measured. - if cx.selection.objects.len() != 1 { + if !cx.shape_widgets || cx.selection.objects.len() != 1 { return None; } let bx = shown_box(cx)?; @@ -276,8 +276,12 @@ mod tests { assert!(w.at.distance(want(1.0)) < 1e-9, "{w:?} {bx:?}"); assert!(SideWidget::of(&d, &s, &bx, 4.0).unwrap().at.distance(want(4.0)) < 1e-9); assert!(over_widget(&c, w.at) && !over_widget(&c, w.at + vectorcraft_geom::Vec2::new(0.0, 8.0))); - // Hidden with the bounding box hidden, with an anchor or segment selected, or with no zoom. + // Hidden with the bounding box or the shape widgets hidden, with an anchor or segment + // selected, or with no zoom. assert!(SideWidget::for_tool(&ToolContext { show_bbox: false, ..cx(&d, &s, &p) }).is_none()); + let hidden = ToolContext { shape_widgets: false, ..cx(&d, &s, &p) }; + assert!(SideWidget::for_tool(&hidden).is_none() && !over_widget(&hidden, w.at)); + assert!(SideDrag::hit(&hidden, &PointerEvent::new(PointerKind::Down, w.at.x, w.at.y)).is_none()); let mut part = s.clone(); part.segments.insert(id, Default::default()); assert!(SideWidget::of(&d, &part, &bx, 1.0).is_none()); @@ -429,4 +433,67 @@ mod tests { assert!(!t.overlays(&c).iter().any(|o| matches!(o, Overlay::Measure { .. }))); assert!(t.pointer(&c, &ev(PointerKind::Up, w.at)).is_empty()); } + + /// Switching tools during a drag puts the count back, as Escape does; a press that changed + /// nothing sends nothing. + #[test] + fn switching_tools_cancels_a_side_widget_drag() { + let (d, _, s) = polygon_doc(5, Affine::translate((300.0, 300.0))); + let p = paint(); + let c = cx(&d, &s, &p); + let (w, _) = SideWidget::for_tool(&c).unwrap(); + let mut t = SelectionTool::default(); + t.pointer(&c, &ev(PointerKind::Down, w.at)); + assert_eq!(sides_of(&t.pointer(&c, &ev(PointerKind::Drag, w.at + vectorcraft_geom::Vec2::new(0.0, 30.0)))), [7]); + assert_eq!(t.deactivate(&c), vec![Action::Cancel]); + assert!(!t.busy() && !t.transforming()); + t.pointer(&c, &ev(PointerKind::Down, w.at)); + assert!(t.pointer(&c, &ev(PointerKind::Drag, w.at + vectorcraft_geom::Vec2::new(0.0, 6.0))).is_empty()); + assert!(t.deactivate(&c).is_empty()); + assert!(!t.busy() && !t.transforming()); + } + + /// The release is read where it happens, with or without a drag event there first: back at the + /// start the polygon keeps its count with no undo step, and further down it takes the new count. + #[test] + fn the_release_position_sets_the_sides() { + let (d, id, s) = polygon_doc(5, Affine::translate((300.0, 300.0))); + let p = paint(); + let c = cx(&d, &s, &p); + let (w, _) = SideWidget::for_tool(&c).unwrap(); + let at = |px: f64| w.at + vectorcraft_geom::Vec2::new(0.0, px); + let mut t = SelectionTool::default(); + t.pointer(&c, &ev(PointerKind::Down, w.at)); + assert_eq!(sides_of(&t.pointer(&c, &ev(PointerKind::Drag, at(12.0)))), [6]); + assert_eq!( + t.pointer(&c, &ev(PointerKind::Up, w.at)), + vec![Action::Preview("object.setLiveShape".into(), json!({ "id": id.0, "sides": 5 })), Action::Cancel] + ); + assert!(!t.busy() && !t.transforming()); + t.pointer(&c, &ev(PointerKind::Down, w.at)); + assert_eq!(sides_of(&t.pointer(&c, &ev(PointerKind::Drag, at(12.0)))), [6]); + assert_eq!( + t.pointer(&c, &ev(PointerKind::Up, at(24.0))), + vec![Action::Preview("object.setLiveShape".into(), json!({ "id": id.0, "sides": 7 })), Action::Commit] + ); + } + + /// A double-click on the widget with the Selection tool does nothing to the artwork under it. + #[test] + fn a_double_click_on_the_widget_leaves_the_artwork_under_it_alone() { + let (mut d, _, s) = polygon_doc(5, Affine::translate((300.0, 300.0))); + let p = paint(); + let (w, _) = SideWidget::for_tool(&cx(&d, &s, &p)).unwrap(); + let l = d.layers[0].id; + let under = d.alloc_id(); + let at = d.layers[0].children().map_or(0, |c| c.len()); + let r = vectorcraft_geom::Rect::new(w.at.x - 20.0, w.at.y - 20.0, w.at.x + 20.0, w.at.y + 20.0); + d.insert(Some(l), at, Node::path(under, vectorcraft_geom::shapes::rectangle(r), Appearance::default_art())).unwrap(); + let c = cx(&d, &s, &p); + assert!(over_widget(&c, w.at)); + let mut t = SelectionTool::default(); + assert!(t.pointer(&c, &ev(PointerKind::DoubleClick, w.at)).is_empty()); + // Beside the widget, the double-click reaches the artwork. + assert!(!t.pointer(&c, &ev(PointerKind::DoubleClick, w.at + vectorcraft_geom::Vec2::new(0.0, 15.0))).is_empty()); + } } diff --git a/crates/tools/src/symbolism.rs b/crates/tools/src/symbolism.rs index b4dd9e631b..a4fc04e0cc 100644 --- a/crates/tools/src/symbolism.rs +++ b/crates/tools/src/symbolism.rs @@ -23,9 +23,26 @@ pub fn create(id: &str) -> Option> { }) } +/// The values of Method in the Symbolism Tools Options. +pub const METHODS: [&str; 3] = ["userDefined", "average", "random"]; + +/// The values of each Symbol Sprayer option in the Symbolism Tools Options. +pub const SPRAY_MODES: [&str; 2] = ["average", "userDefined"]; + +/// The Symbol Sprayer options: (tool option, key in `symbol.spray`'s `attributes`). +pub const SPRAY_ATTRIBUTES: [(&str, &str); 6] = [ + ("sprayScrunch", "scrunch"), + ("spraySize", "size"), + ("spraySpin", "spin"), + ("sprayScreen", "screen"), + ("sprayStain", "stain"), + ("sprayStyle", "style"), +]; + pub struct SymbolismTool { id: &'static str, - points: Vec, + /// The drag's points, each with its pen pressure (0..1). + points: Vec<(Point, f64)>, /// How many points the last preview had ([`previews_at`] thins previews of a long drag). previewed: usize, active: bool, @@ -41,6 +58,40 @@ pub struct SymbolismTool { pub symbol: Option, /// Graphic style for the Styler (None = the document's first non-default style). pub style: Option, + /// Use Pressure Pen: each point's pen pressure is the intensity there. + pub use_pressure: bool, + /// Method of the Scruncher, Sizer, Spinner, Stainer, Screener and Styler: one of [`METHODS`]. + pub method: &'static str, + /// Show Brush Size and Intensity: the brush outline follows the pointer. + pub show_brush: bool, + /// The Symbol Sprayer options, in the order of [`SPRAY_ATTRIBUTES`]: each one of [`SPRAY_MODES`]. + pub spray: [&'static str; 6], + /// Symbol Sizer: Proportional Resizing. + pub proportional: bool, + /// Symbol Sizer: Resizing Affects Density. + pub affects_density: bool, +} + +/// Checks the Symbolism Tools Options in `values` before `tool.setOption` sets any, when `tool` is +/// a symbolism tool, with the tool's own checks ([`Tool::check_option`]): a number out of its +/// range, `method` that is not one of [`METHODS`], a Symbol Sprayer option that is not one of +/// [`SPRAY_MODES`], and `usePressure`, `showBrush`, `proportional` or `affectsDensity` that is not +/// true or false are errors. Ok for every other tool, and for a key the tool does not report +/// (`tool.setOption` refuses that one as an unknown option). Saved settings go to the tool's +/// `set_option` instead, which skips a value it cannot read. +pub fn check_options(tool: &str, values: &serde_json::Map) -> Result<(), String> { + if !tool.starts_with("symbol") || create(tool).is_none() { + return Ok(()); + } + let tool = SymbolismTool::new(tool); + let known = tool.options(); + values.iter().filter(|(key, _)| known.get(key.as_str()).is_some()).try_for_each(|(key, v)| tool.check_option(key, v)) +} + +/// `v` as one of `allowed`, when it is one. +fn one_of(v: &Value, allowed: &[&'static str]) -> Option<&'static str> { + let s = v.as_str()?; + allowed.iter().copied().find(|a| *a == s) } impl SymbolismTool { @@ -67,6 +118,12 @@ impl SymbolismTool { density: 5.0, symbol: None, style: None, + use_pressure: false, + method: "userDefined", + show_brush: true, + spray: ["average"; 6], + proportional: true, + affects_density: false, } } @@ -86,14 +143,29 @@ impl SymbolismTool { /// The command + params for the gesture so far. pub fn command(&self, cx: &ToolContext) -> (String, Value) { let radius = self.diameter / 2.0; - let pts = points_json(&self.points); if self.id == "symbolSprayer" { - let mut v = json!({"points": pts, "radius": radius, "density": self.density, "alt": self.alt}); + let pts = points_json(&self.points.iter().map(|(p, _)| *p).collect::>()); + let attributes: serde_json::Map = + SPRAY_ATTRIBUTES.iter().zip(self.spray).map(|((_, key), mode)| (key.to_string(), json!(mode))).collect(); + let mut v = json!({"points": pts, "radius": radius, "density": self.density, "alt": self.alt, "attributes": attributes}); if let Some(s) = &self.symbol { v["name"] = json!(s); } + // Stain: User Defined stains the new instances with the fill color in its own model. + if self.spray[4] == "userDefined" + && let Some(c) = cx.paint.fill.color() + { + v["color"] = serde_json::to_value(c).unwrap_or(Value::Null); + v["keepModel"] = json!(true); + } + // A style the document no longer has (a deleted one) is left out: the default style applies. + if let Some(s) = self.style.as_ref().filter(|s| cx.doc.graphic_styles.iter().any(|g| g.name == **s)) { + v["style"] = json!(s); + } return ("symbol.spray".into(), v); } + let pressure = self.use_pressure; + let pts = Value::Array(self.points.iter().map(|(p, f)| if pressure { json!([p.x, p.y, f]) } else { json!([p.x, p.y]) }).collect()); let tool = match self.id { "symbolShifter" => "shift", "symbolScruncher" => "scrunch", @@ -113,6 +185,17 @@ impl SymbolismTool { if let Some(s) = &self.style { v["style"] = json!(s); } + if pressure { + v["usePressure"] = json!(true); + } + // The Symbol Shifter has no Method. + if tool != "shift" { + v["method"] = json!(self.method); + } + if tool == "size" { + v["proportional"] = json!(self.proportional); + v["affectsDensity"] = json!(self.affects_density); + } ("symbol.adjust".into(), v) } } @@ -140,9 +223,10 @@ impl Tool for SymbolismTool { fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { let p = ev.pos; self.hover = Some(p); + let sample = (p, f64::from(ev.pressure).clamp(0.0, 1.0)); match ev.kind { PointerKind::Down => { - self.points = vec![p]; + self.points = vec![sample]; self.previewed = 1; self.active = true; self.alt = ev.mods.alt; @@ -152,11 +236,15 @@ impl Tool for SymbolismTool { PointerKind::Drag if self.active => { // Sprayer: thin the samples to a fraction of the brush; others: every few pixels. let step = if self.id == "symbolSprayer" { (self.diameter * 0.15).max(cx.tol(3.0)) } else { cx.tol(3.0) }; + // With Use Pressure Pen a change of pressure of at least 0.05 is kept where the pen + // stays (the Sprayer does not use the pressure). + let pressed = self.use_pressure && self.id != "symbolSprayer"; + let thinned = self.points.last().is_some_and(|(l, f)| l.distance(p) < step && !(pressed && (sample.1 - f).abs() >= 0.05)); // Each preview carries every point so far: a long drag stops growing and previews less often. - if self.points.len() >= MAX_STROKE_SAMPLES || self.points.last().is_some_and(|l| l.distance(p) < step) { + if self.points.len() >= MAX_STROKE_SAMPLES || thinned { return vec![]; } - self.points.push(p); + self.points.push(sample); if !previews_at(self.points.len()) { return vec![]; } @@ -193,9 +281,16 @@ impl Tool for SymbolismTool { vec![] } fn overlays(&self, _cx: &ToolContext) -> Vec { - let Some(p) = self.hover else { return vec![] }; - let circle = kurbo::Circle::new(p, self.diameter / 2.0).to_path(0.1); - vec![Overlay::Path { path: circle, color: FEEDBACK, width: 1.0, dashed: false }] + let Some(p) = self.hover.filter(|_| self.show_brush) else { return vec![] }; + let ring = |radius: f64, dashed| Overlay::Path { path: kurbo::Circle::new(p, radius).to_path(0.1), color: FEEDBACK, width: 1.0, dashed }; + let mut v = vec![ring(self.diameter / 2.0, false)]; + // The intensity: a dashed ring that fills the brush at 10. A pen's pressure sets it instead + // with Use Pressure Pen, so no ring is drawn then. The Symbol Sprayer uses neither, so it + // draws no ring. + if self.id != "symbolSprayer" && !self.use_pressure && self.intensity < 10.0 { + v.push(ring(self.diameter / 2.0 * self.intensity / 10.0, true)); + } + v } fn cursor(&self, _cx: &ToolContext, _p: Point, _m: Mods) -> Cursor { match self.id { @@ -210,7 +305,22 @@ impl Tool for SymbolismTool { } } fn options(&self) -> Value { - json!({"diameter": self.diameter, "intensity": self.intensity, "density": self.density, "symbol": self.symbol, "style": self.style}) + let mut v = json!({ + "diameter": self.diameter, + "intensity": self.intensity, + "density": self.density, + "symbol": self.symbol, + "style": self.style, + "usePressure": self.use_pressure, + "method": self.method, + "showBrush": self.show_brush, + "proportional": self.proportional, + "affectsDensity": self.affects_density, + }); + for ((key, _), mode) in SPRAY_ATTRIBUTES.iter().zip(self.spray) { + v[*key] = json!(mode); + } + v } fn set_option(&mut self, key: &str, v: &Value) { match key { @@ -219,15 +329,28 @@ impl Tool for SymbolismTool { "density" => self.density = v.as_f64().unwrap_or(self.density).clamp(1.0, 10.0), "symbol" => self.symbol = v.as_str().map(str::to_string), "style" => self.style = v.as_str().map(str::to_string), - _ => {} + "usePressure" => self.use_pressure = v.as_bool().unwrap_or(self.use_pressure), + "method" => self.method = one_of(v, &METHODS).unwrap_or(self.method), + "showBrush" => self.show_brush = v.as_bool().unwrap_or(self.show_brush), + "proportional" => self.proportional = v.as_bool().unwrap_or(self.proportional), + "affectsDensity" => self.affects_density = v.as_bool().unwrap_or(self.affects_density), + _ => { + if let Some(i) = SPRAY_ATTRIBUTES.iter().position(|(k, _)| *k == key) { + self.spray[i] = one_of(v, &SPRAY_MODES).unwrap_or(self.spray[i]); + } + } } } fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { use crate::option_check as c; + let must_be = |names: &[&str]| format!("`{key}` must be one of {}", names.join(", ")); 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), + "usePressure" | "showBrush" | "proportional" | "affectsDensity" => c::boolean(key, v), + "method" => one_of(v, &METHODS).map(drop).ok_or_else(|| must_be(&METHODS)), + k if SPRAY_ATTRIBUTES.iter().any(|(a, _)| *a == k) => one_of(v, &SPRAY_MODES).map(drop).ok_or_else(|| must_be(&SPRAY_MODES)), _ => Err(c::unknown(key)), } } @@ -391,6 +514,159 @@ mod tests { assert!(matches!(&a[1], Action::Preview(_, v) if v["color"] == fill && v["keepModel"] == true), "{a:?}"); } + /// The Symbolism Tools Options the tools keep, with what each is before it is set. + #[test] + fn the_options_dialog_fields_are_tool_options() { + let mut t = SymbolismTool::new("symbolSizer"); + let o = t.options(); + assert_eq!((o["usePressure"].clone(), o["method"].clone(), o["showBrush"].clone()), (json!(false), json!("userDefined"), json!(true))); + assert_eq!((o["proportional"].clone(), o["affectsDensity"].clone()), (json!(true), json!(false))); + for (key, _) in SPRAY_ATTRIBUTES { + assert_eq!(o[key], "average", "{key}"); + } + for (key, v) in [ + ("usePressure", json!(true)), + ("method", json!("random")), + ("showBrush", json!(false)), + ("proportional", json!(false)), + ("affectsDensity", json!(true)), + ("sprayStain", json!("userDefined")), + ] { + t.set_option(key, &v); + assert_eq!(t.options()[key], v, "{key}"); + } + // A value that is none of an option's choices leaves it as it was. + for (key, v) in [("method", json!("smooth")), ("method", json!(2)), ("sprayStain", json!("random")), ("usePressure", json!("yes"))] { + let before = t.options(); + t.set_option(key, &v); + assert_eq!(t.options(), before, "{key}: {v}"); + } + } + + /// The adjusting tools send the Method (the Shifter has none), the Sizer its two options, and + /// with Use Pressure Pen each point's pen pressure. + #[test] + fn adjust_tools_send_the_method_the_sizer_options_and_the_pen_pressure() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let press = |t: &mut SymbolismTool| { + let down = PointerEvent { pressure: 0.25, ..PointerEvent::new(PointerKind::Down, 5.0, 5.0) }; + match t.pointer(&cx, &down).swap_remove(1) { + Action::Preview(_, v) => v, + other => panic!("{other:?}"), + } + }; + let mut sizer = SymbolismTool::new("symbolSizer"); + let v = press(&mut sizer); + assert_eq!((v["method"].clone(), v["proportional"].clone(), v["affectsDensity"].clone()), (json!("userDefined"), json!(true), json!(false))); + assert_eq!((v["points"].clone(), v.get("usePressure")), (json!([[5.0, 5.0]]), None)); + sizer.set_option("usePressure", &json!(true)); + sizer.set_option("method", &json!("average")); + sizer.set_option("affectsDensity", &json!(true)); + let v = press(&mut sizer); + assert_eq!((v["points"].clone(), v["usePressure"].clone()), (json!([[5.0, 5.0, 0.25]]), json!(true))); + assert_eq!((v["method"].clone(), v["affectsDensity"].clone()), (json!("average"), json!(true))); + let mut shifter = SymbolismTool::new("symbolShifter"); + shifter.set_option("method", &json!("random")); + let v = press(&mut shifter); + assert!(v.get("method").is_none() && v.get("proportional").is_none(), "{v}"); + let mut spinner = SymbolismTool::new("symbolSpinner"); + spinner.set_option("method", &json!("random")); + let v = press(&mut spinner); + assert!(v["method"] == "random" && v.get("proportional").is_none(), "{v}"); + } + + /// With Use Pressure Pen a drag sample where the pen stays is kept when the pressure changes; + /// without it, or with the same pressure, the drag keeps thinning the samples by distance. + #[test] + fn a_pressure_change_where_the_pen_stays_is_kept() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let stroke = |use_pressure: bool, pressures: [f32; 3]| { + let mut t = SymbolismTool::new("symbolSizer"); + t.set_option("usePressure", &json!(use_pressure)); + let at = |kind, pressure| PointerEvent { pressure, ..PointerEvent::new(kind, 5.0, 5.0) }; + let events = + [(PointerKind::Down, pressures[0]), (PointerKind::Drag, pressures[1]), (PointerKind::Drag, pressures[2]), (PointerKind::Up, 0.0)]; + // The points of the last preview, the one the drag commits. + let mut last = Value::Null; + for (kind, pressure) in events { + for a in t.pointer(&cx, &at(kind, pressure)) { + if let Action::Preview(_, v) = a { + last = v["points"].clone(); + } + } + } + last + }; + assert_eq!(stroke(true, [0.0, 1.0, 1.0]), json!([[5.0, 5.0, 0.0], [5.0, 5.0, 1.0]])); + assert_eq!(stroke(true, [0.5, 0.52, 0.5]), json!([[5.0, 5.0, 0.5]])); + assert_eq!(stroke(false, [0.0, 1.0, 1.0]), json!([[5.0, 5.0]])); + } + + /// The Sprayer sends its six options as `attributes`, and the fill color only while Stain is + /// User Defined. + #[test] + fn the_sprayer_sends_its_attributes() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let mut t = SymbolismTool::new("symbolSprayer"); + t.set_option("usePressure", &json!(true)); + let spray = |t: &mut SymbolismTool| match t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 5.0, 5.0)).swap_remove(1) { + Action::Preview(c, v) if c == "symbol.spray" => v, + other => panic!("{other:?}"), + }; + let v = spray(&mut t); + let average = + json!({"scrunch": "average", "size": "average", "spin": "average", "screen": "average", "stain": "average", "style": "average"}); + assert_eq!((v["attributes"].clone(), v.get("color"), v["points"].clone()), (average, None, json!([[5.0, 5.0]]))); + t.set_option("sprayStain", &json!("userDefined")); + t.set_option("spraySpin", &json!("userDefined")); + let v = spray(&mut t); + assert_eq!( + (v["attributes"]["stain"].clone(), v["attributes"]["spin"].clone(), v["attributes"]["size"].clone()), + (json!("userDefined"), json!("userDefined"), json!("average")) + ); + assert_eq!((v["color"].clone(), v["keepModel"].clone()), (serde_json::to_value(p.fill.color().unwrap()).unwrap(), json!(true))); + } + + /// Show Brush Size and Intensity: the brush's outline with a dashed ring for the intensity + /// inside it; no ring with Use Pressure Pen, at intensity 10 or for the Symbol Sprayer, and + /// nothing with it off. + #[test] + fn show_brush_size_and_intensity_draws_the_brush() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let mut t = SymbolismTool::new("symbolScruncher"); + assert!(t.overlays(&cx).is_empty(), "no pointer yet"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Move, 50.0, 50.0)); + let rings = |t: &SymbolismTool| { + t.overlays(&cx) + .into_iter() + .map(|o| match o { + Overlay::Path { path, dashed, .. } => (path.bounding_box().width().round(), dashed), + other => panic!("{other:?}"), + }) + .collect::>() + }; + assert_eq!(rings(&t), [(80.0, false), (40.0, true)]); + t.set_option("intensity", &json!(10)); + assert_eq!(rings(&t), [(80.0, false)]); + t.set_option("intensity", &json!(2)); + t.set_option("usePressure", &json!(true)); + assert_eq!(rings(&t), [(80.0, false)]); + t.set_option("showBrush", &json!(false)); + assert!(t.overlays(&cx).is_empty()); + // The Symbol Sprayer uses neither Intensity nor pen pressure: the outline only. + let mut t = SymbolismTool::new("symbolSprayer"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Move, 50.0, 50.0)); + assert_eq!(rings(&t), [(80.0, false)]); + } + #[test] fn brackets_change_diameter_and_intensity() { let (d, _) = doc_with_rect(); diff --git a/crates/tools/src/trace_split.rs b/crates/tools/src/trace_split.rs new file mode 100644 index 0000000000..f5949be2a4 --- /dev/null +++ b/crates/tools/src/trace_split.rs @@ -0,0 +1,284 @@ +//! The divider of an Image Trace object in the Split view: the source image shows on its left +//! (in the image's own pixels) and the tracing result on its right. Drawing and hit testing share +//! the document-space geometry here; a drag previews `imageTrace.setView` and commits it as one +//! undo step. +use serde_json::json; +use vectorcraft_doc::{Document, NodeId, NodeKind, Selection, TraceView}; +use vectorcraft_geom::{Affine, Point}; + +use crate::{Action, Cursor, Mods, ToolContext}; + +/// How near (screen points) the pointer must come to the divider to take it. +pub const HIT_PX: f64 = 5.0; + +/// The divider's half length past each end of its grip, in screen points. +pub const GRIP_HALF: f32 = 10.0; + +/// The Split view's divider of one selected Image Trace object, in document space. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct TraceDivider { + /// The Image Trace object. + pub id: NodeId, + /// The fraction of the source image's width, from its left edge, that shows the image. + pub split: f64, + /// Where the divider meets the image's top and bottom edges. + pub ends: [Point; 2], + /// The source image's pixel-to-document transform. + xf: Affine, + width: f64, +} + +impl TraceDivider { + /// The divider of the one Image Trace object selected whole, when it shows the Split view. + pub fn of(doc: &Document, selection: &Selection, zoom: f64) -> Option { + let [id] = selection.objects.as_slice() else { return None }; + if !selection.anchors.is_empty() || !selection.segments.is_empty() || !doc.is_editable(*id) || !zoom.is_finite() || zoom <= 0.0 { + return None; + } + let n = doc.node(*id)?; + if n.extras().trace.is_none() || n.trace_view() != TraceView::Split { + return None; + } + let NodeKind::Group { children, clip: false } = &n.kind else { return None }; + let NodeKind::Image(im) = &children.first()?.kind else { return None }; + let (width, height) = (f64::from(im.width), f64::from(im.height)); + let det = im.xf.determinant(); + if width <= 0.0 || height <= 0.0 || !det.is_finite() || det.abs() < 1e-12 || !im.xf.as_coeffs().iter().all(|c| c.is_finite()) { + return None; + } + let split = n.trace_split(); + let at = width * split; + let ends = [im.xf * Point::new(at, 0.0), im.xf * Point::new(at, height)]; + ends.iter().all(|p| finite(*p)).then_some(Self { id: *id, split, ends, xf: im.xf, width }) + } + + /// The divider position for document point `p`: the fraction of the image's width left of + /// it, from 0 to 1, rounded to a ten-thousandth. + pub fn split_at(&self, p: Point) -> Option { + let local = self.xf.inverse() * p; + let f = (local.x / self.width).clamp(0.0, 1.0); + f.is_finite().then(|| (f * 10_000.0).round() / 10_000.0) + } + + /// How far the image's left-to-right direction is turned (counter-clockwise degrees on the + /// page), for the resize cursor. + fn angle(&self) -> f64 { + let across = self.xf * Point::new(1.0, 0.0) - self.xf * Point::ZERO; + (-across.y).atan2(across.x).to_degrees() + } + + /// The divider under document point `p`. Nothing with the bounding box hidden or in Outline + /// mode, where the canvas draws neither the divider nor the split. + fn hit(cx: &ToolContext, p: Point) -> Option { + if !cx.show_bbox || cx.outline || !finite(p) { + return None; + } + let d = Self::of(cx.doc, cx.selection, cx.zoom)?; + let [a, b] = d.ends; + let v = b - a; + let length = v.hypot(); + if !length.is_finite() || length <= 0.0 { + return None; + } + let unit = v / length; + let along = (p - a).dot(unit).clamp(0.0, length); + // A bounding-box handle or a shown center point under the pointer keeps its own drag. + ((a + unit * along).distance(p) <= cx.tol(HIT_PX) + && !crate::select::bbox_handle_at(cx, p) + && crate::select::hit_center(cx, p, cx.point_tol()).is_none()) + .then_some(d) + } +} + +fn finite(p: Point) -> bool { + p.x.is_finite() && p.y.is_finite() +} + +fn resize_cursor(d: &TraceDivider, cx: &ToolContext) -> Cursor { + crate::select::handle_cursor(crate::bbox::Handle::Right, d.angle() - cx.view_angle()) +} + +/// The resize cursor over the divider at `p`, turned with the image and the view. +pub fn cursor(cx: &ToolContext, p: Point) -> Option { + TraceDivider::hit(cx, p).map(|d| resize_cursor(&d, cx)) +} + +/// A drag of the divider: it previews `imageTrace.setView` while the pointer moves and commits +/// it as one undo step. +#[derive(Clone, Debug)] +pub struct SplitDrag { + divider: TraceDivider, + start: Point, + began: bool, +} + +impl SplitDrag { + pub fn hit(cx: &ToolContext, p: Point, mods: Mods) -> Option { + if mods.cmd || mods.ctrl || mods.alt { + return None; + } + let divider = TraceDivider::hit(cx, p)?; + Some(Self { divider, start: p, began: false }) + } + + pub fn adjusting(&self) -> bool { + self.began + } + + pub fn cursor(&self, cx: &ToolContext) -> Cursor { + resize_cursor(&self.divider, cx) + } + + pub fn drag(&mut self, cx: &ToolContext, p: Point) -> Vec { + if !finite(p) || (!self.began && p.distance(self.start) < cx.tol(3.0)) { + return vec![]; + } + let Some(split) = self.divider.split_at(p) else { return vec![] }; + let mut out = vec![]; + if !self.began { + self.began = true; + out.push(Action::Begin("Image Trace View".into())); + } + out.push(Action::Preview("imageTrace.setView".into(), json!({"id": self.divider.id.0, "view": TraceView::Split.id(), "split": split}))); + out + } + + pub fn finish(self) -> Vec { + if self.began { vec![Action::Commit] } else { vec![] } + } + + pub fn cancel(self) -> Vec { + if self.began { vec![Action::Cancel] } else { vec![] } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::testutil::{cx, paint}; + use std::sync::Arc; + use vectorcraft_doc::{ImageObject, Node}; + + /// A document with an Image Trace object over a 100 × 50 image placed by `xf`, in `view`. + fn traced(xf: Affine, view: &str, split: f64) -> (Document, NodeId) { + let mut doc = Document::new(400.0, 400.0); + let im = ImageObject { key: "k".into(), width: 100, height: 50, xf, link: None, placement: Default::default(), pixels: None }; + let mut source = Node::new(doc.alloc_id(), NodeKind::Image(Box::new(im))); + source.visible = false; + let mut g = Node::group(doc.alloc_id(), vec![Arc::new(source)]); + g.extras_mut().trace = Some(Box::new(json!({"view": view, "split": split}))); + let id = g.id; + let layer = doc.layers[0].id; + doc.insert(Some(layer), 0, g).unwrap(); + (doc, id) + } + + #[test] + fn the_divider_shows_only_for_one_selected_split_view_and_follows_the_image() { + let paint = paint(); + let mut selection = Selection::default(); + let (doc, id) = traced(Affine::translate((10.0, 20.0)), "split", 0.25); + assert!(TraceDivider::of(&doc, &selection, 1.0).is_none(), "nothing selected"); + selection.set([id]); + let d = TraceDivider::of(&doc, &selection, 1.0).unwrap(); + assert_eq!((d.split, d.ends), (0.25, [Point::new(35.0, 20.0), Point::new(35.0, 70.0)])); + for zoom in [0.0, -1.0, f64::NAN] { + assert!(TraceDivider::of(&doc, &selection, zoom).is_none()); + } + let (other, id) = traced(Affine::IDENTITY, "sourceImage", 0.25); + selection.set([id]); + assert!(TraceDivider::of(&other, &selection, 1.0).is_none(), "another view"); + // A turned and scaled image: the divider runs along the image's own height. + let xf = Affine::translate((200.0, 100.0)) * Affine::rotate(std::f64::consts::FRAC_PI_2) * Affine::scale(2.0); + let (doc, id) = traced(xf, "split", 0.5); + selection.set([id]); + let d = TraceDivider::of(&doc, &selection, 1.0).unwrap(); + assert!(d.ends[0].distance(Point::new(200.0, 200.0)) < 1e-9 && d.ends[1].distance(Point::new(100.0, 200.0)) < 1e-9, "{:?}", d.ends); + assert_eq!(d.split_at(Point::new(150.0, 150.0)), Some(0.25)); + assert_eq!(d.split_at(Point::new(150.0, 900.0)), Some(1.0), "clamped"); + let c = cx(&doc, &selection, &paint); + assert_eq!(cursor(&c, Point::new(150.0, 200.0)), Some(Cursor::ResizeV)); + assert_eq!(cursor(&c, Point::new(150.0, 210.0)), None, "past the hit distance"); + let mut c = cx(&doc, &selection, &paint); + c.show_bbox = false; + assert_eq!(cursor(&c, Point::new(150.0, 200.0)), None, "bounding box hidden"); + assert!(SplitDrag::hit(&c, Point::new(150.0, 200.0), Mods::default()).is_none(), "bounding box hidden"); + let mut c = cx(&doc, &selection, &paint); + c.outline = true; + assert!(SplitDrag::hit(&c, Point::new(150.0, 200.0), Mods::default()).is_none(), "Outline mode"); + } + + #[test] + fn dragging_the_divider_previews_the_view_and_commits_once() { + let paint = paint(); + let mut selection = Selection::default(); + let (doc, id) = traced(Affine::translate((10.0, 20.0)), "split", 0.5); + selection.set([id]); + for zoom in [0.5, 1.0, 4.0] { + let mut c = cx(&doc, &selection, &paint); + c.zoom = zoom; + let on = Point::new(60.0 + 4.0 / zoom, 40.0); + assert_eq!(cursor(&c, on), Some(Cursor::ResizeH), "zoom {zoom}"); + assert!(SplitDrag::hit(&c, Point::new(60.0 + 6.0 / zoom, 40.0), Mods::default()).is_none(), "zoom {zoom}"); + assert!(SplitDrag::hit(&c, on, Mods { alt: true, ..Default::default() }).is_none()); + let mut drag = SplitDrag::hit(&c, on, Mods::default()).unwrap(); + assert!(drag.drag(&c, on + vectorcraft_geom::Vec2::new(1.0 / zoom, 0.0)).is_empty(), "under the drag threshold"); + assert!(drag.drag(&c, Point::new(f64::NAN, 0.0)).is_empty()); + let out = drag.drag(&c, Point::new(85.0, 300.0)); + assert!( + matches!(&out[..], [Action::Begin(_), Action::Preview(id, p)] + if id == "imageTrace.setView" && p["split"] == json!(0.75) && p["view"] == "split"), + "{out:?}" + ); + let out = drag.drag(&c, Point::new(-50.0, 30.0)); + assert!(matches!(&out[..], [Action::Preview(_, p)] if p["split"] == json!(0.0)), "{out:?}"); + assert!(drag.adjusting()); + assert!(matches!(drag.clone().finish()[..], [Action::Commit])); + assert!(matches!(drag.cancel()[..], [Action::Cancel])); + } + } + + /// With Show Center on, a press on the center point where the divider crosses it moves the + /// object; the rest of the divider still takes a press. + #[test] + fn the_center_point_keeps_its_drag_on_the_divider() { + use vectorcraft_doc::{Appearance, LiveShape}; + let paint = paint(); + let mut selection = Selection::default(); + let (mut doc, id) = traced(Affine::translate((10.0, 20.0)), "split", 0.5); + let xf = Affine::translate((10.0, 20.0)); + let shape = LiveShape::Rectangle { w: 100.0, h: 50.0, radii: [0.0; 4], kinds: Default::default(), radii_relative: false, xf }; + let path = Node::path(doc.alloc_id(), shape.to_path(), Appearance::default_art()); + doc.insert(Some(id), 1, path).unwrap(); + doc.node_mut(id).unwrap().edit_attrs(|a| a.show_center = Some(true)); + selection.set([id]); + let c = cx(&doc, &selection, &paint); + assert_eq!(crate::select::hit_center(&c, Point::new(60.0, 45.0), c.point_tol()).map(|(i, _)| i), Some(id)); + assert_eq!(cursor(&c, Point::new(60.0, 45.0)), None, "the center point"); + assert!(SplitDrag::hit(&c, Point::new(60.0, 45.0), Mods::default()).is_none(), "the center point"); + assert_eq!(cursor(&c, Point::new(60.0, 33.0)), Some(Cursor::ResizeH)); + } + + /// Switching away from the Selection tool during a divider drag cancels it, as Escape does: + /// the view goes back. After a press that has not moved there is nothing to put back. + #[test] + fn a_tool_switch_cancels_a_divider_drag() { + use crate::{PointerEvent, PointerKind, Tool}; + let paint = paint(); + let mut selection = Selection::default(); + let (doc, id) = traced(Affine::translate((10.0, 20.0)), "split", 0.5); + selection.set([id]); + let c = cx(&doc, &selection, &paint); + let mut t = crate::select::SelectionTool::default(); + assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 60.0, 40.0)).is_empty()); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 85.0, 40.0)); + assert!(matches!(a.first(), Some(Action::Begin(_))), "{a:?}"); + assert_eq!(t.deactivate(&c), vec![Action::Cancel]); + assert!(!t.busy() && !t.transforming()); + assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, 85.0, 40.0)).is_empty()); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, 60.0, 40.0)); + assert!(t.busy()); + assert!(t.deactivate(&c).is_empty()); + assert!(!t.busy()); + } +} diff --git a/crates/tools/src/xform/transform.rs b/crates/tools/src/xform/transform.rs index 339984e9a1..d0ff487af8 100644 --- a/crates/tools/src/xform/transform.rs +++ b/crates/tools/src/xform/transform.rs @@ -11,9 +11,14 @@ //! onto another object's anchor scales exactly onto it. Scale stretches along the bounding box's //! own width and height, turned with rotated objects until Reset Bounding Box; Reflect's default //! axis is the box's vertical one, and Shift constrains a drawn axis to 45° steps from the box. +//! With the Reflect tool, a click also sets the first point of an axis, and a second click +//! reflects the selection across the line through both points (Alt on it reflects a copy); a +//! drag from there draws the axis from that first point. + +use std::collections::{BTreeMap, BTreeSet}; use serde_json::{Value, json}; -use vectorcraft_doc::{NodeId, OrientedBox}; +use vectorcraft_doc::{AnchorRef, NodeId, OrientedBox}; use vectorcraft_geom::{Affine, Point, Rect, Vec2}; use super::target_overlays; @@ -82,6 +87,9 @@ struct Drag { pointer: Point, shift: bool, last: Affine, + /// The document revision at the press: a press whose document or selection changes before it + /// becomes a drag is dropped, so its reference point is never applied to other objects. + revision: (u64, u64), } impl Drag { @@ -92,10 +100,24 @@ impl Drag { } } +/// The first point of a Reflect axis set by a click, waiting for the second point, with the +/// selection and the document revision it was set for. +#[derive(Clone, Debug)] +struct Axis { + first: Point, + objects: Vec, + anchors: BTreeMap>, + revision: (u64, u64), +} + pub struct TransformTool { kind: TransformKind, /// Custom reference point and the selection it was set for. origin: Option<(Point, Vec)>, + /// Reflect: the axis whose second point the next click sets. + axis: Option, + /// The snapped pointer while hovering with an axis waiting, where its dashed line ends. + axis_to: Option, drag: Option, measure: Option<(Point, String)>, /// What the Info panel shows for the drag in progress. @@ -128,7 +150,23 @@ pub fn reflect_matrix(o: Point, theta: f64) -> Affine { impl TransformTool { pub fn new(kind: TransformKind) -> Self { - Self { kind, origin: None, drag: None, measure: None, readout: None, hover: vec![], snap: None } + Self { kind, origin: None, axis: None, axis_to: None, drag: None, measure: None, readout: None, hover: vec![], snap: None } + } + + /// The first point of the Reflect axis waiting for its second point, when it was set for the + /// current selection (objects and anchors) and nothing in the document or the selection has + /// changed since, so a selection changed and then changed back does not bring it back. + fn axis_first(&self, cx: &ToolContext) -> Option { + self.axis + .as_ref() + .filter(|a| !a.objects.is_empty() && a.revision == cx.revision && a.objects == cx.selection.objects && a.anchors == cx.selection.anchors) + .map(|a| a.first) + } + + /// Drops the Reflect axis waiting for its second point. + fn drop_axis(&mut self) { + self.axis = None; + self.axis_to = None; } /// The effective reference point: the custom one if it belongs to the current selection, @@ -297,8 +335,10 @@ impl Tool for TransformTool { self.hover.clear(); let (pick, _) = snap_pick(cx, p); // Alt: decided on release. A click sets the point and opens the dialog; a drag - // transforms a copy about the reference point as it was. - let origin = self.reference_point(cx).unwrap_or(bounds.center()); + // transforms a copy about the reference point as it was. With a Reflect axis waiting + // for its second point, a drag draws the axis from its first point. + self.axis_to = None; + let origin = self.axis_first(cx).or_else(|| self.reference_point(cx)).unwrap_or(bounds.center()); let anchors = vectorcraft_effects::preview::anchor_bounds_with(cx.selection, cx.doc, cx.bounds_measure()).is_some(); let angle = selection_box(cx).map_or(0.0, |b| b.angle); self.drag = Some(Drag { @@ -313,6 +353,7 @@ impl Tool for TransformTool { pointer: p, shift: false, last: Affine::IDENTITY, + revision: cx.revision, }); vec![] } @@ -323,6 +364,12 @@ impl Tool for TransformTool { if p.distance(d.start) < cx.tol(3.0) { return out; } + // The document or the selection changed since the press: its reference point + // (or Reflect axis) belongs to the selection as it was, so the press is dropped. + if d.revision != cx.revision { + self.end_drag(); + return out; + } d.began = true; // The selection moves, so only the other objects are targets. The Scale tool's // drag scales; the others move the art about the reference point. @@ -352,15 +399,49 @@ impl Tool for TransformTool { } else { d.last }; + // A drag draws a Reflect axis to its end, so it uses up an axis waiting for + // its second point. + self.drop_axis(); vec![preview(m, ev.mods.alt, ev.backquote), Action::Commit] + } else if d.revision != cx.revision { + // The document or the selection changed since the press, as for a drag: the + // release sets no reference point or Reflect axis. + vec![] + } else if let (TransformKind::Reflect, Some(first)) = (self.kind, self.axis_first(cx)) { + // The second point of a Reflect axis: the selection (with Alt at the release, as + // for a drag, a copy) reflects across the line through both points, as one undo + // step. A click on the first point does not define a line, so the axis keeps + // waiting. + if d.pick.distance(first) < cx.tol(3.0) { + return vec![]; + } + self.drop_axis(); + let copy = ev.mods.alt; + let (m, _, _) = self.solve(d.angle_for(copy, ev.backquote), first, first, d.pick, false, d.bounds); + vec![Action::Begin(self.kind.label().into()), preview(m, copy, ev.backquote), Action::Commit] } else { - // A click sets the reference point; with Alt, it opens the dialog too. + // A click sets the reference point; with Alt, it opens the dialog too. With the + // Reflect tool, a plain click also sets the first point of an axis. self.origin = Some((d.pick, cx.selection.objects.clone())); - if d.alt { vec![self.dialog(d.pick)] } else { vec![] } + self.drop_axis(); + if d.alt { + vec![self.dialog(d.pick)] + } else { + if self.kind == TransformKind::Reflect { + self.axis = Some(Axis { + first: d.pick, + objects: cx.selection.objects.clone(), + anchors: cx.selection.anchors.clone(), + revision: cx.revision, + }); + } + vec![] + } } } PointerKind::DoubleClick => { self.end_drag(); + self.drop_axis(); match self.reference_point(cx) { Some(o) => vec![self.dialog(o)], None => vec![], @@ -369,7 +450,9 @@ impl Tool for TransformTool { PointerKind::TripleClick => vec![], PointerKind::Move => { if self.drag.is_none() { - self.hover = if cx.selection.is_empty() { vec![] } else { snap_pick(cx, p).1 }; + let (pick, hover) = if cx.selection.is_empty() { (p, vec![]) } else { snap_pick(cx, p) }; + self.hover = hover; + self.axis_to = self.axis_first(cx).map(|_| pick); } vec![] } @@ -378,15 +461,40 @@ impl Tool for TransformTool { fn key(&mut self, cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { match key { + // Escape cancels a drag, and drops the Reflect axis the drag was drawing from too. ToolKey::Escape if self.busy() => { self.end_drag(); + self.drop_axis(); vec![Action::Cancel] } - ToolKey::Enter => self.reference_point(cx).map(|o| vec![self.dialog(o)]).unwrap_or_default(), + // Escape drops a Reflect axis waiting for its second point, and a press not yet + // released with it, so the release sets no point; the reference point stays. + ToolKey::Escape if self.axis.is_some() => { + self.end_drag(); + self.drop_axis(); + vec![] + } + // Enter opens the dialog. A press not yet a drag ends with it, so its release sets no + // reference point or Reflect axis behind the dialog. + ToolKey::Enter => { + if !self.busy() { + self.end_drag(); + } + self.drop_axis(); + self.reference_point(cx).map(|o| vec![self.dialog(o)]).unwrap_or_default() + } _ => vec![], } } + /// A dropped press ends whether or not it became a drag, so the release the engine sends after + /// it sets no reference point or Reflect axis; a Reflect axis waiting for its second point is + /// dropped too, as with Escape. + fn drop_press(&mut self, _cx: &ToolContext) -> Vec { + self.drop_axis(); + if self.end_drag().is_some_and(|d| d.began) { vec![Action::Cancel] } else { vec![] } + } + fn overlays(&self, cx: &ToolContext) -> Vec { let mut o = vec![]; let reference = match self.drag { @@ -403,6 +511,13 @@ impl Tool for TransformTool { { o.push(Overlay::Line { a: d.origin, b: *p, color: super::CYAN, dashed: true }); } + // A Reflect axis waiting for its second point: a dashed line from its first point to the + // pointer. + if self.drag.is_none() + && let (Some(a), Some(b)) = (self.axis_first(cx), self.axis_to) + { + o.push(Overlay::Line { a, b, color: super::CYAN, dashed: true }); + } if let (Some((p, t)), true) = (&self.measure, cx.transform_tools_guides) { o.push(Overlay::Measure { p: *p + Vec2::new(cx.tol(12.0), cx.tol(12.0)), text: t.clone() }); } @@ -429,9 +544,20 @@ impl Tool for TransformTool { fn set_option(&mut self, key: &str, value: &Value) { if key == "origin" { self.origin = value.as_array().and_then(|a| Some((Point::new(a.first()?.as_f64()?, a.get(1)?.as_f64()?), vec![]))); + self.drop_axis(); } } + fn ends_on_escape(&self, cx: &ToolContext) -> bool { + self.axis_first(cx).is_some() + } + + /// An edit, Undo or Redo made outside the tool, or another document, drops a Reflect axis + /// waiting for its second point. + fn history_moved(&mut self) { + self.drop_axis(); + } + /// `origin` is `[x, y]`, or null to clear it. fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { if key != "origin" { @@ -442,6 +568,7 @@ impl Tool for TransformTool { } fn deactivate(&mut self, _cx: &ToolContext) -> Vec { + self.drop_axis(); if self.end_drag().is_some_and(|d| d.began) { vec![Action::Cancel] } else { vec![] } } } @@ -674,6 +801,353 @@ mod tests { assert!((matrix(&a[1]) * Point::new(200.0, 200.0)).distance(Point::new(302.0, 262.0)) < 1e-9); } + /// Sends a click (a press and a release, with `mods`) at `(x, y)` and returns the release's actions. + fn click(t: &mut TransformTool, cx: &ToolContext, x: f64, y: f64, mods: Mods) -> Vec { + assert!(t.pointer(cx, &ev(PointerKind::Down, x, y).with_mods(mods)).is_empty()); + t.pointer(cx, &ev(PointerKind::Up, x, y).with_mods(mods)) + } + + /// Returns the matrix of a two-click reflection: a Begin, one `object.transform` preview with + /// `copy`, and a Commit. + fn reflected(a: &[Action], copy: bool) -> Affine { + assert!( + matches!(a, [Action::Begin(l), Action::Preview(c, v), Action::Commit] if l == "Reflect" && c == "object.transform" && v["copy"] == copy), + "{a:?}" + ); + matrix(&a[1]) + } + + /// The Reflect tool: a click sets the first point of an axis, and a second click reflects the + /// selection across the line through both points, as one interaction. The next click starts a + /// new axis. + #[test] + fn a_second_reflect_click_reflects_across_the_line_through_both_points() { + let (d, id) = doc_with_rect(); + let mut s = Selection::default(); + s.add(id); + let p = paint(); + let mut c = cx(&d, &s, &p); + (c.smart_guides, c.snap_to_point) = (false, false); + let none = Mods::default(); + let mut t = TransformTool::new(TransformKind::Reflect); + assert!(click(&mut t, &c, 100.0, 100.0, none).is_empty()); + assert_eq!(t.reference_point(&c), Some(Point::new(100.0, 100.0))); + assert!(t.ends_on_escape(&c)); + // Hovering draws the axis from the first point to the pointer. + t.pointer(&c, &ev(PointerKind::Move, 200.0, 260.0)); + let line = Overlay::Line { a: Point::new(100.0, 100.0), b: Point::new(200.0, 260.0), color: super::super::CYAN, dashed: true }; + assert!(t.overlays(&c).contains(&line), "{:?}", t.overlays(&c)); + let m = reflected(&click(&mut t, &c, 200.0, 200.0, none), false); + for fixed in [Point::new(100.0, 100.0), Point::new(200.0, 200.0), Point::new(300.0, 300.0)] { + assert!((m * fixed).distance(fixed) < 1e-9, "{m:?}"); + } + assert!((m * Point::new(200.0, 100.0)).distance(Point::new(100.0, 200.0)) < 1e-9, "{m:?}"); + // The axis is used up; the first point stays the reference point. + assert!(!t.ends_on_escape(&c)); + assert!(!t.overlays(&c).contains(&line)); + assert_eq!(t.reference_point(&c), Some(Point::new(100.0, 100.0))); + // The next click starts a new axis, and the one after it reflects across a vertical line. + assert!(click(&mut t, &c, 120.0, 50.0, none).is_empty()); + let m = reflected(&click(&mut t, &c, 120.0, 250.0, none), false); + assert!((m * Point::new(150.0, 130.0)).distance(Point::new(90.0, 130.0)) < 1e-9, "{m:?}"); + // Shift on a plain second click does not constrain the line. + assert!(click(&mut t, &c, 100.0, 100.0, none).is_empty()); + let shift = Mods { shift: true, ..Default::default() }; + let m = reflected(&click(&mut t, &c, 210.0, 190.0, shift), false); + assert!((m * Point::new(210.0, 190.0)).distance(Point::new(210.0, 190.0)) < 1e-9, "{m:?}"); + } + + /// Alt on the second click reflects a copy and opens no dialog; Alt on a first click still opens + /// the dialog and starts no axis. + #[test] + fn alt_on_the_second_reflect_click_reflects_a_copy() { + let (d, id) = doc_with_rect(); + let mut s = Selection::default(); + s.add(id); + let p = paint(); + let mut c = cx(&d, &s, &p); + (c.smart_guides, c.snap_to_point) = (false, false); + let mut t = TransformTool::new(TransformKind::Reflect); + assert!(click(&mut t, &c, 250.0, 100.0, Mods::default()).is_empty()); + let m = reflected(&click(&mut t, &c, 250.0, 200.0, alt()), true); + assert!((m * Point::new(150.0, 150.0)).distance(Point::new(350.0, 150.0)) < 1e-9, "{m:?}"); + // As for a drag, Alt at the release decides: held only at the press, the original reflects; + // pressed during the click, a copy does. + for (press, release) in [(alt(), Mods::default()), (Mods::default(), alt())] { + assert!(click(&mut t, &c, 250.0, 100.0, Mods::default()).is_empty()); + assert!(t.pointer(&c, &ev(PointerKind::Down, 250.0, 200.0).with_mods(press)).is_empty()); + reflected(&t.pointer(&c, &ev(PointerKind::Up, 250.0, 200.0).with_mods(release)), release.alt); + } + // Alt on a first click: the dialog, and the click after it is a first click again. + assert_eq!( + click(&mut t, &c, 120.0, 130.0, alt()), + vec![Action::Dialog("reflect".into(), json!({"axis": "vertical", "origin": [120.0, 130.0]}))] + ); + assert!(!t.ends_on_escape(&c)); + assert!(click(&mut t, &c, 130.0, 160.0, Mods::default()).is_empty()); + assert!(t.ends_on_escape(&c)); + } + + /// A second click on the first point does not define a line: nothing happens and the axis keeps + /// waiting. Escape, Enter, a double-click, a changed selection, an edit made outside the tool, + /// a new reference point and switching tools drop the axis, so the next click starts a new one. + #[test] + fn a_reflect_axis_waits_through_a_click_on_its_first_point_and_drops_on_escape_or_a_new_selection() { + let (mut d, id) = doc_with_rect(); + let l = d.layers[0].id; + let other = d.alloc_id(); + d.insert( + Some(l), + 1, + vectorcraft_doc::Node::path( + other, + vectorcraft_geom::shapes::rectangle(Rect::new(300.0, 300.0, 340.0, 340.0)), + vectorcraft_doc::Appearance::default_art(), + ), + ) + .unwrap(); + let mut s = Selection::default(); + s.add(id); + let p = paint(); + let mut c = cx(&d, &s, &p); + (c.smart_guides, c.snap_to_point) = (false, false); + let none = Mods::default(); + let mut t = TransformTool::new(TransformKind::Reflect); + click(&mut t, &c, 100.0, 100.0, none); + assert!(click(&mut t, &c, 100.0, 100.0, none).is_empty()); + assert!(click(&mut t, &c, 101.0, 102.0, none).is_empty()); + assert!(t.ends_on_escape(&c)); + reflected(&click(&mut t, &c, 100.0, 200.0, none), false); + + // Each way of dropping the axis, then a click that only starts a new one. + type DropAxis = fn(&mut TransformTool, &ToolContext); + let drops: [(&str, DropAxis); 6] = [ + ("escape", |t, c| assert!(t.key(c, ToolKey::Escape, Mods::default()).is_empty())), + ("enter", |t, c| assert!(matches!(t.key(c, ToolKey::Enter, Mods::default()).as_slice(), [Action::Dialog(..)]))), + ("double-click", |t, c| assert!(matches!(t.pointer(c, &ev(PointerKind::DoubleClick, 100.0, 100.0)).as_slice(), [Action::Dialog(..)]))), + ("history", |t, _| t.history_moved()), + ("origin", |t, _| t.set_option("origin", &json!([10.0, 10.0]))), + ("deactivate", |t, c| assert!(t.deactivate(c).is_empty())), + ]; + for (name, drop) in drops { + click(&mut t, &c, 100.0, 100.0, none); + assert!(t.ends_on_escape(&c), "{name}"); + drop(&mut t, &c); + assert!(!t.ends_on_escape(&c), "{name}"); + assert!(click(&mut t, &c, 100.0, 200.0, none).is_empty(), "{name}"); + assert!(t.ends_on_escape(&c), "{name}"); + t.key(&c, ToolKey::Escape, Mods::default()); + } + + // A double-click elsewhere arrives as two clicks and then the double-click: its first click + // sets the second point and reflects, its second click starts a new axis, and the + // double-click drops that axis and opens the dialog there. + click(&mut t, &c, 100.0, 100.0, none); + reflected(&click(&mut t, &c, 100.0, 200.0, none), false); + assert!(click(&mut t, &c, 100.0, 200.0, none).is_empty()); + let a = t.pointer(&c, &ev(PointerKind::DoubleClick, 100.0, 200.0)); + assert_eq!(a, vec![Action::Dialog("reflect".into(), json!({"axis": "vertical", "origin": [100.0, 200.0]}))]); + assert!(!t.ends_on_escape(&c)); + + // The selection changed and changed back (or the document edited) moves the revision: the + // axis set before it does not come back. + click(&mut t, &c, 100.0, 100.0, none); + let mut moved = cx(&d, &s, &p); + (moved.smart_guides, moved.snap_to_point) = (false, false); + moved.revision = (c.revision.0, c.revision.1 + 1); + assert!(!t.ends_on_escape(&moved)); + assert!(click(&mut t, &moved, 100.0, 200.0, none).is_empty()); + reflected(&click(&mut t, &moved, 200.0, 200.0, none), false); + + // Another object selected, then nothing selected: the axis set for the first selection + // does not reflect them. + click(&mut t, &c, 100.0, 100.0, none); + let mut s2 = Selection::default(); + s2.add(other); + let mut c2 = cx(&d, &s2, &p); + (c2.smart_guides, c2.snap_to_point) = (false, false); + assert!(!t.ends_on_escape(&c2)); + assert!(click(&mut t, &c2, 100.0, 200.0, none).is_empty()); + let empty = Selection::default(); + let c3 = cx(&d, &empty, &p); + assert!(t.pointer(&c3, &ev(PointerKind::Down, 100.0, 300.0)).is_empty()); + assert!(t.pointer(&c3, &ev(PointerKind::Up, 100.0, 300.0)).is_empty()); + // Anchors selected with Direct Selection make a different selection too. + let mut s4 = s.clone(); + s4.anchors.insert(id, [(0, 0), (0, 1)].into()); + let mut c4 = cx(&d, &s4, &p); + (c4.smart_guides, c4.snap_to_point) = (false, false); + click(&mut t, &c, 100.0, 100.0, none); + assert!(!t.ends_on_escape(&c4)); + assert!(click(&mut t, &c4, 100.0, 200.0, none).is_empty()); + // With those anchors selected, the second click reflects them, across the line y = 200. + let m = reflected(&click(&mut t, &c4, 200.0, 200.0, none), false); + assert!((m * Point::new(150.0, 150.0)).distance(Point::new(150.0, 250.0)) < 1e-9, "{m:?}"); + + // The other transform tools only move the reference point on a second click. + for kind in [TransformKind::Rotate, TransformKind::Scale, TransformKind::Shear] { + let mut t = TransformTool::new(kind); + assert!(click(&mut t, &c, 100.0, 100.0, none).is_empty(), "{kind:?}"); + assert!(click(&mut t, &c, 100.0, 200.0, none).is_empty(), "{kind:?}"); + assert!(!t.ends_on_escape(&c), "{kind:?}"); + assert_eq!(t.reference_point(&c), Some(Point::new(100.0, 200.0)), "{kind:?}"); + } + } + + /// Escape pressed between the press and the release of the second click drops the axis and the + /// press with it: the release starts no new axis and moves no reference point, so the click + /// after it starts an axis and reflects nothing. Escape during a drag from the first point + /// cancels the drag and drops the axis too. + #[test] + fn escape_during_the_second_reflect_click_cancels_that_click() { + let (d, id) = doc_with_rect(); + let mut s = Selection::default(); + s.add(id); + let p = paint(); + let mut c = cx(&d, &s, &p); + (c.smart_guides, c.snap_to_point) = (false, false); + let none = Mods::default(); + let mut t = TransformTool::new(TransformKind::Reflect); + assert!(click(&mut t, &c, 100.0, 100.0, none).is_empty()); + assert!(t.pointer(&c, &ev(PointerKind::Down, 200.0, 200.0)).is_empty()); + assert!(t.key(&c, ToolKey::Escape, none).is_empty()); + assert!(t.pointer(&c, &ev(PointerKind::Up, 200.0, 200.0)).is_empty()); + assert!(!t.ends_on_escape(&c)); + assert_eq!(t.reference_point(&c), Some(Point::new(100.0, 100.0))); + assert!(click(&mut t, &c, 150.0, 300.0, none).is_empty()); + assert!(t.ends_on_escape(&c)); + // A drag from the first point, then Escape. + assert!(t.pointer(&c, &ev(PointerKind::Down, 300.0, 300.0)).is_empty()); + assert_eq!(t.pointer(&c, &ev(PointerKind::Drag, 100.0, 250.0))[0], Action::Begin("Reflect".into())); + assert_eq!(t.key(&c, ToolKey::Escape, none), vec![Action::Cancel]); + assert!(!t.ends_on_escape(&c)); + assert!(t.pointer(&c, &ev(PointerKind::Up, 100.0, 250.0)).is_empty()); + assert!(click(&mut t, &c, 200.0, 200.0, none).is_empty()); + } + + /// Enter between the press and the release of the second click opens the dialog at the first + /// point and ends the press: the release sets no point and starts no axis. A press the engine + /// drops ends the same way, with or without an axis waiting, and a dropped drag is canceled. A + /// press whose document or selection changes before it becomes a drag is dropped. + #[test] + fn enter_or_a_dropped_press_during_a_reflect_click_ends_that_press() { + let (d, id) = doc_with_rect(); + let mut s = Selection::default(); + s.add(id); + let p = paint(); + let mut c = cx(&d, &s, &p); + (c.smart_guides, c.snap_to_point) = (false, false); + let none = Mods::default(); + let first = Point::new(100.0, 100.0); + let mut t = TransformTool::new(TransformKind::Reflect); + assert!(click(&mut t, &c, 100.0, 100.0, none).is_empty()); + assert!(t.pointer(&c, &ev(PointerKind::Down, 200.0, 200.0)).is_empty()); + assert_eq!(t.key(&c, ToolKey::Enter, none), vec![Action::Dialog("reflect".into(), json!({"axis": "vertical", "origin": [100.0, 100.0]}))]); + assert!(t.pointer(&c, &ev(PointerKind::Up, 200.0, 200.0)).is_empty()); + assert!(!t.ends_on_escape(&c)); + assert_eq!(t.reference_point(&c), Some(first)); + + // A dropped first press: its release sets no point and starts no axis. + assert!(t.pointer(&c, &ev(PointerKind::Down, 200.0, 200.0)).is_empty()); + assert!(t.drop_press(&c).is_empty()); + assert!(t.pointer(&c, &ev(PointerKind::Up, 200.0, 200.0)).is_empty()); + assert!(!t.ends_on_escape(&c)); + assert_eq!(t.reference_point(&c), Some(first)); + // A dropped second press drops the axis too, so the next click is a first click. + assert!(click(&mut t, &c, 100.0, 100.0, none).is_empty()); + assert!(t.pointer(&c, &ev(PointerKind::Down, 200.0, 200.0)).is_empty()); + assert!(t.drop_press(&c).is_empty()); + assert!(t.pointer(&c, &ev(PointerKind::Up, 200.0, 200.0)).is_empty()); + assert!(!t.ends_on_escape(&c)); + assert!(click(&mut t, &c, 150.0, 300.0, none).is_empty()); + // A dropped drag is canceled, and its release commits nothing. + assert!(t.pointer(&c, &ev(PointerKind::Down, 300.0, 300.0)).is_empty()); + assert_eq!(t.pointer(&c, &ev(PointerKind::Drag, 100.0, 250.0))[0], Action::Begin("Reflect".into())); + assert_eq!(t.drop_press(&c), vec![Action::Cancel]); + assert!(t.pointer(&c, &ev(PointerKind::Up, 100.0, 250.0)).is_empty()); + assert!(!t.ends_on_escape(&c)); + + // The selection changes between the press and the first drag event: the press is dropped, + // and neither the drag nor its release transforms anything. + assert!(click(&mut t, &c, 100.0, 100.0, none).is_empty()); + assert!(t.pointer(&c, &ev(PointerKind::Down, 200.0, 200.0)).is_empty()); + let mut moved = cx(&d, &s, &p); + (moved.smart_guides, moved.snap_to_point) = (false, false); + moved.revision = (c.revision.0, c.revision.1 + 1); + assert!(t.pointer(&moved, &ev(PointerKind::Drag, 100.0, 250.0)).is_empty()); + assert!(!t.busy()); + assert!(t.pointer(&moved, &ev(PointerKind::Up, 100.0, 250.0)).is_empty()); + } + + /// A press whose document or selection changes before a release that is not a drag sets no + /// reference point and starts no Reflect axis, so the next click is a first click. + #[test] + fn a_reflect_press_released_after_the_document_changed_sets_nothing() { + let (d, id) = doc_with_rect(); + let mut s = Selection::default(); + s.add(id); + let p = paint(); + let mut c = cx(&d, &s, &p); + (c.smart_guides, c.snap_to_point) = (false, false); + let none = Mods::default(); + let mut moved = cx(&d, &s, &p); + (moved.smart_guides, moved.snap_to_point) = (false, false); + moved.revision = (c.revision.0, c.revision.1 + 1); + let mut t = TransformTool::new(TransformKind::Reflect); + assert!(t.pointer(&c, &ev(PointerKind::Down, 200.0, 200.0)).is_empty()); + assert!(t.pointer(&moved, &ev(PointerKind::Up, 200.0, 200.0)).is_empty()); + assert!(!t.ends_on_escape(&moved)); + assert_ne!(t.reference_point(&moved), Some(Point::new(200.0, 200.0))); + assert!(click(&mut t, &moved, 150.0, 300.0, none).is_empty()); + // The other transform tools set no reference point either. + let mut t = TransformTool::new(TransformKind::Rotate); + assert!(t.pointer(&c, &ev(PointerKind::Down, 200.0, 200.0)).is_empty()); + assert!(t.pointer(&moved, &ev(PointerKind::Up, 200.0, 200.0)).is_empty()); + assert_ne!(t.reference_point(&moved), Some(Point::new(200.0, 200.0))); + } + + /// After a click sets the first point, a drag draws the axis from it (Shift in 45° steps from a + /// turned box), and its release uses the axis up. With the selection turned, two clicks still + /// reflect across the line through the clicked points on the page. + #[test] + fn a_drag_after_a_reflect_click_draws_the_axis_from_the_first_point() { + let (mut d, id) = doc_with_rect(); + let c0 = Point::new(150.0, 150.0); + d.node_mut(id).unwrap().transform(about(c0, Affine::rotate(-30f64.to_radians())), false); + let mut s = Selection::default(); + s.add(id); + let p = paint(); + let mut c = cx(&d, &s, &p); + (c.smart_guides, c.snap_to_point) = (false, false); + let none = Mods::default(); + let mut t = TransformTool::new(TransformKind::Reflect); + click(&mut t, &c, 100.0, 100.0, none); + t.pointer(&c, &ev(PointerKind::Down, 300.0, 300.0)); + let a = t.pointer(&c, &ev(PointerKind::Drag, 100.0, 250.0)); + assert_eq!(a[0], Action::Begin("Reflect".into())); + let m = matrix(&a[1]); + assert!((m * Point::new(100.0, 180.0)).distance(Point::new(100.0, 180.0)) < 1e-9, "{m:?}"); + assert!((m * Point::new(150.0, 150.0)).distance(Point::new(50.0, 150.0)) < 1e-9, "{m:?}"); + // Shift: a pointer a few degrees off the box's vertical axis steps onto it. + let frame = OrientedBox { angle: 30.0, rect: Rect::ZERO }; + let along = |x: f64, y: f64| Point::new(100.0, 100.0) + (frame.to_doc() * Point::new(x, y)).to_vec2(); + let to = along(3.0, 50.0); + let a = t.pointer(&c, &ev(PointerKind::Drag, to.x, to.y).with_mods(Mods { shift: true, ..Default::default() })); + assert!((matrix(&a[0]) * along(0.0, 50.0)).distance(along(0.0, 50.0)) < 1e-9, "{a:?}"); + let up = t.pointer(&c, &ev(PointerKind::Up, to.x, to.y)); + assert_eq!(up.last(), Some(&Action::Commit)); + assert!(!t.ends_on_escape(&c)); + assert!(click(&mut t, &c, 100.0, 300.0, none).is_empty()); + // Two clicks with the box turned: the line through the clicked points on the page. + let m = reflected(&click(&mut t, &c, 300.0, 300.0, none), false); + assert!((m * Point::new(200.0, 250.0)).distance(Point::new(200.0, 350.0)) < 1e-9, "{m:?}"); + // A drag with no axis waiting still draws it from the reference point. + let mut t = TransformTool::new(TransformKind::Reflect); + t.pointer(&c, &ev(PointerKind::Down, 150.0, 50.0)); + let a = t.pointer(&c, &ev(PointerKind::Drag, 150.0, 20.0)); + assert!((matrix(&a[1]) * Point::new(100.0, 120.0)).distance(Point::new(200.0, 120.0)) < 1e-9); + } + #[test] fn reflect_vertical_axis_mirrors_x() { let t = TransformTool::new(TransformKind::Reflect); diff --git a/crates/ui-egui/src/addons/pathtools.rs b/crates/ui-egui/src/addons/pathtools.rs index 8a1666b260..3e7b864c05 100644 --- a/crates/ui-egui/src/addons/pathtools.rs +++ b/crates/ui-egui/src/addons/pathtools.rs @@ -1,6 +1,6 @@ //! 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, Smooth Bridge ([`bridge`]), 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, Tangent Circle… ([`tangent_circle`]), Add Bounding Rectangle… and Add Bounding 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 @@ -17,6 +17,7 @@ pub mod tangent_circle; use egui::Ui; use serde_json::{Map, Value, json}; use vectorcraft_geom::Point; +use vectorcraft_tools::addons::tangent_circle as tangent_circle_tool; use vectorcraft_tools::addons::{anchor_eraser, extend_path, measure_inspect, parametric_shape, slide_anchor, trim}; use crate::VectorcraftApp; @@ -36,6 +37,10 @@ pub const KIND: &str = "pathToolOptions"; pub const COMMON_TANGENTS: &str = "addon.pathtools.commonTangents"; /// The kinds of tangent Common Tangents' `tangents` picks, and their labels. pub const TANGENT_KINDS: &[(&str, &str)] = &[("All", "all"), ("External", "external"), ("Internal", "internal")]; +/// Add Bounding Rectangle's and Add Bounding Circle's commands, whose menu items open the command +/// dialog (Offset, One per Object) with a Preview. +pub const BOUNDING_RECTANGLE: &str = "addon.pathtools.boundingRectangle"; +pub const BOUNDING_CIRCLE: &str = "addon.pathtools.boundingCircle"; /// The close modes, as `addon.pathtools.close` names them, and their labels. const CLOSE_MODES: [(&str, &str); 3] = [("handles", "Keep Handles"), ("straight", "Straight"), ("smooth", "Smooth")]; const LABEL_W: f32 = 64.0; @@ -66,6 +71,7 @@ pub fn menu() -> Vec { Item::Cmd("Set Corners…", set_corners::COMMAND, Value::Null), tool("Slide Anchor Along Path", slide_anchor::ID), Item::Cmd("Shared Edge Merge Tool", shared_edge::COMMAND, json!({})), + tool("Tangent Circle Tool", tangent_circle_tool::ID), tool("Trim at Crossings Tool", trim::ID), Item::Sep, Item::Cmd("Anchor Inspector", "window.panel", json!({ "panel": ID })), @@ -79,6 +85,8 @@ pub fn menu() -> Vec { 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 })), + Item::Cmd("Add Bounding Rectangle…", BOUNDING_RECTANGLE, json!({ "offset": 0, "each": false })), + Item::Cmd("Add Bounding Circle…", BOUNDING_CIRCLE, json!({ "offset": 0, "each": false })), ] } @@ -199,7 +207,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { /// Tools whose options the dialog edits. pub fn has_options(tool: &str) -> bool { - [anchor_eraser::ID, extend_path::ID].contains(&tool) + [anchor_eraser::ID, extend_path::ID, tangent_circle_tool::ID].contains(&tool) } /// Open the options of add-on tool `tool` with its current values. @@ -229,6 +237,16 @@ fn body(_app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { }); return false; } + if d.str("__tool") == tangent_circle_tool::ID { + let (lo, hi) = tangent_circle_tool::RADIUS_RANGE; + let r = d.f64("radius", tangent_circle_tool::RADIUS); + widgets::label_row(ui, tl!("Radius:"), LABEL_W, |ui| { + if let Some(x) = widgets::range_field(ui, "tangent-circle-radius", r, lo..=hi, " pt", 2, 96.0) { + d.fields.insert("radius".into(), json!(x)); + } + }); + return false; + } let rows = [ ("size", "Size:", anchor_eraser::SIZE_RANGE, "px", anchor_eraser::SIZE), ("tolerance", "Tolerance:", anchor_eraser::TOLERANCE_RANGE, "", anchor_eraser::TOLERANCE), diff --git a/crates/ui-egui/src/addons/pathtools/tests.rs b/crates/ui-egui/src/addons/pathtools/tests.rs index e714b85aa2..2c49c661fe 100644 --- a/crates/ui-egui/src/addons/pathtools/tests.rs +++ b/crates/ui-egui/src/addons/pathtools/tests.rs @@ -22,6 +22,7 @@ fn the_plugins_submenu_selects_the_tools_and_opens_the_anchor_inspector() { ("Measure & Inspect Tool", "measureInspect"), ("Parametric Shape Tool", "parametricShape"), ("Slide Anchor Along Path", "slideAnchor"), + ("Tangent Circle Tool", "tangentCircle"), ("Trim at Crossings Tool", "trimAtCrossings"), ] { let e = under(label).expect(label); @@ -98,6 +99,14 @@ fn double_clicking_the_brush_opens_its_options_and_ok_sets_them() { app.ui.dialog.as_mut().unwrap().fields.insert("mode".into(), json!("arc")); crate::dialogs::confirm(&mut app).unwrap(); assert_eq!(app.session.tool_options_of("extendPath")["mode"], json!("arc")); + // The Tangent Circle tool's radius for Shift. + app.run("tool.options", json!({"tool": "tangentCircle"})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().f64("radius", 0.0), 36.0); + let text = painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + assert!(text.contains("Tangent Circle Tool Options") && text.contains("Radius:"), "{text}"); + app.ui.dialog.as_mut().unwrap().fields.insert("radius".into(), json!(12.5)); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(app.session.tool_options_of("tangentCircle")["radius"], json!(12.5)); assert!(app.run("tool.options", json!({"tool": "measureInspect"})).is_err()); } @@ -343,7 +352,25 @@ fn common_tangents_on_a_point_gives_the_same_lines_for_every_choice() { app.run("select.set", json!({"ids": [oval, dot]})).unwrap(); let steps = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len(); let count = |app: &VectorcraftApp| app.session.doc().unwrap().doc.node_count(); - let (n, nodes) = (steps(&app), count(&app)); + // The end points of every two-anchor path in the document, rounded and sorted. + let lines = |app: &VectorcraftApp| { + let mut ends = Vec::new(); + app.session.doc().unwrap().doc.walk(|node| { + if let Some(path) = node.path_data() { + for sub in &path.subpaths { + if sub.anchors.len() == 2 { + let mut pair: Vec<(i64, i64)> = + sub.anchors.iter().map(|a| ((a.p.x * 1e6).round() as i64, (a.p.y * 1e6).round() as i64)).collect(); + pair.sort(); + ends.push(pair); + } + } + } + }); + ends.sort(); + ends + }; + let (start, n, nodes) = (app.session.doc().unwrap().doc.clone(), steps(&app), count(&app)); let open = |app: &mut VectorcraftApp| { let entries = menus::menu_entries(app); let item = entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Path Precision Tools"] && e.label == "Common Tangents…").unwrap(); @@ -352,15 +379,43 @@ fn common_tangents_on_a_point_gives_the_same_lines_for_every_choice() { menus::invoke(app, &cmd, p); }; - open(&mut app); - crate::dialogs::set_field(app.ui.dialog.as_mut().unwrap(), "preview".into(), json!(true)); + // Each choice previews the same two lines, and OK with that choice keeps them as one step; + // undo puts the document back as it was. + let mut first: Option>> = None; for (_, kind) in super::TANGENT_KINDS { - crate::dialogs::set_field(app.ui.dialog.as_mut().unwrap(), "tangents".into(), json!(kind)); + open(&mut app); + let d = app.ui.dialog.as_mut().unwrap(); + crate::dialogs::set_field(d, "preview".into(), json!(true)); + crate::dialogs::set_field(d, "tangents".into(), json!(kind)); painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); assert_eq!(count(&app), nodes + 2, "{kind}: the two lines from the point"); + let previewed = lines(&app); + assert_eq!(previewed.len(), 2, "{kind}"); + let first = first.get_or_insert_with(|| previewed.clone()); + assert_eq!(&previewed, first, "{kind}: the same lines as the first choice"); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!((steps(&app), count(&app)), (n + 1, nodes + 2), "{kind}: one undo step"); + assert_eq!(&lines(&app), first, "{kind}: OK keeps the previewed lines"); + app.run("edit.undo", json!({})).unwrap(); + app.run("select.set", json!({"ids": [oval, dot]})).unwrap(); + assert_eq!((steps(&app), count(&app)), (n, nodes), "{kind}: undone"); + assert_eq!(app.session.doc().unwrap().doc, start, "{kind}: undo restores the document"); } - crate::dialogs::confirm(&mut app).unwrap(); - assert_eq!((steps(&app), count(&app)), (n + 1, nodes + 2), "one undo step"); + let first = first.unwrap(); + + // Switching the choice while the preview is on keeps the same two lines on the canvas. + open(&mut app); + crate::dialogs::set_field(app.ui.dialog.as_mut().unwrap(), "preview".into(), json!(true)); + painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + for (_, kind) in super::TANGENT_KINDS.iter().rev() { + crate::dialogs::set_field(app.ui.dialog.as_mut().unwrap(), "tangents".into(), json!(kind)); + painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + assert_eq!(count(&app), nodes + 2, "{kind}: switched in place"); + assert_eq!(lines(&app), first, "{kind}: the same lines after the switch"); + } + crate::dialogs::cancel(&mut app); + assert_eq!(app.session.doc().unwrap().doc, start, "Cancel takes the preview away"); + assert_eq!(steps(&app), n, "and adds no undo step"); // A point inside the ellipse: nothing changes, and a message says why. let inside = point(&mut app, 220.0, 150.0); @@ -371,3 +426,107 @@ fn common_tangents_on_a_point_gives_the_same_lines_for_every_choice() { assert_eq!((steps(&app), count(&app)), (n, nodes)); assert!(app.ui.status.contains("The point lies inside the path"), "{}", app.ui.status); } + +/// Object › Plug-ins › Path Precision Tools › Add Bounding Rectangle… and Add Bounding Circle… are +/// dimmed with nothing selected and open the command dialog with Offset 0, One per Object off and +/// Preview off. With Preview on the shape shows on the canvas; Cancel takes it away with no step of +/// history. OK with the defaults draws one shape around the whole selection; OK with an Offset and +/// One per Object draws a larger shape around each object, as one undo step. An Offset that takes +/// the shape past the canvas edge leaves the dialog open, the document unchanged and an error. +#[test] +fn add_bounding_rectangle_and_circle_open_a_dialog_with_offset_and_one_per_object() { + let mut app = app(); + let items = [("Add Bounding Rectangle…", super::BOUNDING_RECTANGLE), ("Add Bounding Circle…", super::BOUNDING_CIRCLE)]; + let find = |app: &VectorcraftApp, label: &str| { + let entries = menus::menu_entries(app); + entries.into_iter().find(|e| e.path == ["Object", "Plug-ins", "Path Precision Tools"] && e.label == label).expect(label) + }; + for (label, command) in items { + let item = find(&app, label); + assert_eq!((item.command.as_deref(), &item.params), (Some(command), &json!({"offset": 0, "each": false}))); + assert!(!item.enabled, "{label} with nothing selected"); + } + let a = app.run("shape.rectangle", json!({"x": 10, "y": 20, "width": 30, "height": 40})).unwrap()["id"].as_u64().unwrap(); + let b = app.run("shape.rectangle", json!({"x": 100, "y": 20, "width": 20, "height": 40})).unwrap()["id"].as_u64().unwrap(); + let steps = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len(); + let count = |app: &VectorcraftApp| app.session.doc().unwrap().doc.node_count(); + let made = |app: &VectorcraftApp| { + let st = app.session.doc().unwrap(); + st.selection.objects.iter().map(|id| st.doc.bounds_of(&[*id], false).unwrap()).collect::>() + }; + let open = |app: &mut VectorcraftApp, label: &str| { + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + let item = find(app, label); + assert!(item.enabled, "{label}"); + let (cmd, p) = menus::click_target(&item.label, item.command.as_deref().unwrap(), &item.params); + menus::invoke(app, &cmd, p); + }; + let near = |r: vectorcraft_geom::Rect, want: [f64; 4]| [r.x0, r.y0, r.x1, r.y1].iter().zip(want).all(|(v, w)| (v - w).abs() < 1e-6); + for (label, command) in items { + let (start, n, nodes) = (app.session.doc().unwrap().doc.clone(), steps(&app), count(&app)); + open(&mut app, label); + let d = app.ui.dialog.as_ref().unwrap_or_else(|| panic!("{label}: a dialog opens")); + assert_eq!((d.str("__command"), d.str("__label")), (command.to_string(), label.trim_end_matches('…').to_string())); + assert_eq!((d.f64("offset", -1.0), d.bool("each"), d.bool("preview")), (0.0, false, false), "{label}"); + let shown = painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + for s in [label.trim_end_matches('…'), "Offset", "One per Object", "Preview"] { + assert!(shown.contains(s), "{label}: {s} in {shown}"); + } + assert_eq!(count(&app), nodes, "{label}: no preview without the checkbox"); + + // Preview on: the shape is on the canvas. Cancel: as it was, with no step of history. + crate::dialogs::set_field(app.ui.dialog.as_mut().unwrap(), "preview".into(), json!(true)); + painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + assert_eq!(count(&app), nodes + 1, "{label}: previewed"); + crate::dialogs::cancel(&mut app); + assert_eq!(app.session.doc().unwrap().doc, start, "{label}: Cancel takes the preview away"); + assert_eq!(steps(&app), n, "{label}: and adds no undo step"); + + // OK with the defaults: one shape around the whole selection, from (10, 20) to (120, 60). + open(&mut app, label); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!((steps(&app), count(&app)), (n + 1, nodes + 1), "{label}: one shape, one undo step"); + let whole = made(&app); + if command == super::BOUNDING_RECTANGLE { + assert!(near(whole[0], [10.0, 20.0, 120.0, 60.0]), "{label}: {:?}", whole[0]); + } else { + // The circle on the diagonal, with the 0.01 pt allowance. + let r = 110.0f64.hypot(40.0) / 2.0 + 0.01; + assert!(near(whole[0], [65.0 - r, 40.0 - r, 65.0 + r, 40.0 + r]), "{label}: {:?}", whole[0]); + } + + // OK with an Offset of 5 pt and One per Object: a shape around each object, one undo step. + open(&mut app, label); + let d = app.ui.dialog.as_mut().unwrap(); + crate::dialogs::set_field(d, "offset".into(), json!(5)); + crate::dialogs::set_field(d, "each".into(), json!(true)); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!((steps(&app), count(&app)), (n + 2, nodes + 3), "{label}: two shapes, one more undo step"); + let each = made(&app); + if command == super::BOUNDING_RECTANGLE { + assert!(near(each[0], [5.0, 15.0, 45.0, 65.0]) && near(each[1], [95.0, 15.0, 125.0, 65.0]), "{label}: {each:?}"); + } else { + let (ra, rb) = (30.0f64.hypot(40.0) / 2.0 + 5.01, 20.0f64.hypot(40.0) / 2.0 + 5.01); + let want = [[25.0 - ra, 40.0 - ra, 25.0 + ra, 40.0 + ra], [110.0 - rb, 40.0 - rb, 110.0 + rb, 40.0 + rb]]; + assert!(near(each[0], want[0]) && near(each[1], want[1]), "{label}: {each:?}"); + } + + // An Offset past the canvas edge: the dialog stays open, nothing is drawn, and the error + // says why. + let (n, nodes) = (steps(&app), count(&app)); + open(&mut app, label); + crate::dialogs::set_field(app.ui.dialog.as_mut().unwrap(), "offset".into(), json!(5_000_000)); + let e = crate::dialogs::confirm(&mut app).unwrap_err(); + assert!(e.contains("the shape would reach past the edge of the canvas"), "{label}: {e}"); + assert!(app.ui.dialog.is_some(), "{label}: the dialog stays open"); + crate::dialogs::cancel(&mut app); + assert_eq!((steps(&app), count(&app)), (n, nodes), "{label}: nothing drawn"); + } + // Every language with complete menus has the menu items, the dialog's headings and its labels. + for lang in crate::i18n::Lang::all().filter(|l| l.complete_menus()) { + for s in ["Add Bounding Rectangle…", "Add Bounding Circle…", "Offset", "One per Object"] { + assert!(crate::i18n::has(lang, s), "{}: {s}", lang.code()); + } + } +} diff --git a/crates/ui-egui/src/addons/shapes.rs b/crates/ui-egui/src/addons/shapes.rs index b856f15603..bdf8763927 100644 --- a/crates/ui-egui/src/addons/shapes.rs +++ b/crates/ui-egui/src/addons/shapes.rs @@ -48,6 +48,12 @@ pub fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui, reserve: f32) -> bool } fit.separator(ui); } + // The tools with live shape widgets: Hide/Show Shape Widgets first, so a narrow bar leaves out + // the shape's fields before it. + if vectorcraft_tools::shape::shows_shape_widgets(&tool) { + shape_widgets_button(app, ui, fit); + fit.separator(ui); + } match active_shape.as_str() { "ellipse" => draw_ellipse_controls(app, ui, fit, &opts, selected_custom), @@ -60,6 +66,15 @@ pub fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui, reserve: f32) -> bool true } +/// Hide Shape Widgets, or Show Shape Widgets while they are hidden (`view.shapeWidgets`), at least 52 +/// points wide and wider for a longer translated label, while `fit` has room for it. +fn shape_widgets_button(app: &mut VectorcraftApp, ui: &mut Ui, fit: &mut Fit) { + let label = if app.ui.view.shape_widgets { tl!("Hide Shape Widgets") } else { tl!("Show Shape Widgets") }; + if fit.room(ui, &[widgets::flat_button_fit_width(ui, label, 52.0)]) && widgets::flat_button_fit(ui, label, 52.0).clicked() { + app.run("view.shapeWidgets", json!({})).ok(); + } +} + /// Whether `fit` has room in the row `ui` for the label `text` with a field `field` wide after it. fn field_room(ui: &Ui, fit: &mut Fit, text: &egui::RichText, field: f32) -> bool { fit.room(ui, &[widgets::text_width(ui, text.clone()), field]) diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 11c87d07ac..0aa63d16cf 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -152,6 +152,7 @@ impl VectorcraftApp { system_paste_at: f64::NEG_INFINITY, clipboard_probe: None, picks: picks::Picks::default(), + original_editor: Default::default(), screen_sampler: None, font_check: None, #[cfg(not(target_arch = "wasm32"))] @@ -171,6 +172,8 @@ impl VectorcraftApp { forwarded_modifiers: None, forwarded_modifiers_held: false, forwarded_frame: false, + forwarded_clipboard: false, + forwarded_presses: vec![], synthetic_modifiers: false, ime_marked: None, ime_context: Default::default(), @@ -186,6 +189,8 @@ impl VectorcraftApp { automation_roots: None, synthetic_frame: false, pending_plugin_install: None, + pending_profile_open: None, + queued_profile_opens: Default::default(), script_picked: Vec::new(), script_picked_left_out: false, pen_end: Default::default(), @@ -640,6 +645,9 @@ impl VectorcraftApp { // 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); + // A shape drawn on the canvas, in a dialog or by a command in this pass shows the Transform + // panel (Show on Shape Creation). + panels::transform::show_on_shape_creation(self, &ctx); crate::toasts::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/app/clipboard.rs b/crates/ui-egui/src/app/clipboard.rs index 5efe2db308..9e7263aee5 100644 --- a/crates/ui-egui/src/app/clipboard.rs +++ b/crates/ui-egui/src/app/clipboard.rs @@ -3,8 +3,9 @@ use super::VectorcraftApp; impl VectorcraftApp { /// Hand a queued text copy to egui. Called after `tick`, after the UI phase's input and at the /// end of the pass; the later calls are what an input- or menu-driven fallback Copy needs, and - /// `take` keeps it single-shot. - pub(super) fn flush_clipboard_out(&mut self, ctx: &egui::Context) { + /// `take` keeps it single-shot. A Copy or Cut that labels left to the next pass hands its text + /// over as soon as it runs ([`crate::shortcuts::handle`]). + pub(crate) fn flush_clipboard_out(&mut self, ctx: &egui::Context) { if let Some(t) = self.clipboard_out.take() { ctx.copy_text(t); } diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 701c0f5ffc..05218f91bf 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -214,10 +214,20 @@ impl VectorcraftApp { Ok(Some(started)) => return Ok(started), Ok(None) => {} } + // Edit › Color Settings' Ask When Pasting, then any swatch conflict. + if let Some(r) = dialogs::profile_mismatch::ask_paste(self, id, ¶ms) { + return r; + } if let Some(r) = dialogs::swatch_conflict::ask(self, id, ¶ms) { return r; } } + // A drag from another document asks as Paste does (its swatches are always added). + if id == dialogs::profile_mismatch::DROP + && let Some(r) = dialogs::profile_mismatch::ask_paste(self, id, ¶ms) + { + return r; + } // Native files carry the view they reopen at. if fileio::SaveMode::of(id).is_some() { io::remember_view(self); @@ -265,6 +275,10 @@ impl VectorcraftApp { } // A renamed spot color swatch stays the Color Guide's base; a deleted one ends the link. panels::color_guide::after_command(self, id, ¶ms, v, spot_base); + // A renamed color group stays selected in the Swatches panel. + if let Some(ctx) = self.ui_ctx.clone() { + panels::swatches::after_command(&ctx, id, ¶ms, v); + } if id == "file.new" { self.status(""); // New Document's Pixel preview mode (Overprint Preview is the engine's). diff --git a/crates/ui-egui/src/app/input.rs b/crates/ui-egui/src/app/input.rs index 95f719d08b..1a170a3f11 100644 --- a/crates/ui-egui/src/app/input.rs +++ b/crates/ui-egui/src/app/input.rs @@ -214,6 +214,8 @@ impl VectorcraftApp { raw.events.insert(0, egui::Event::ModifiersChanged(self.host_modifiers)); } self.forwarded_frame = !self.forwarded.is_empty(); + self.forwarded_clipboard = self.forwarded.iter().any(|e| matches!(e, egui::Event::Copy | egui::Event::Cut)); + self.forwarded_presses = self.forwarded.iter().filter(|e| matches!(e, egui::Event::Key { pressed: true, .. })).cloned().collect(); if !self.forwarded.is_empty() { if let Some(m) = self.forwarded_modifiers.take() { raw.events.push(egui::Event::ModifiersChanged(m)); diff --git a/crates/ui-egui/src/app/view.rs b/crates/ui-egui/src/app/view.rs index 0949b9290f..a1c2af21ff 100644 --- a/crates/ui-egui/src/app/view.rs +++ b/crates/ui-egui/src/app/view.rs @@ -132,6 +132,7 @@ impl VectorcraftApp { snap_to_point: self.ui.view.snap_to_point, snap_to_glyph: self.ui.view.snap_to_glyph, corner_widgets: self.ui.view.corner_widgets && self.ui.view.edges, + shape_widgets: self.ui.view.shape_widgets, screen: self.screen_frame(), artboard: self.view().map_or(0, |v| v.artboard), } diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 02833a7c09..b9d9816a10 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -81,6 +81,7 @@ pub use tool_overlays::{HiddenChars, SpellingMarks}; use tool_overlays::{ grid_repeat_overlay, hidden_chars_overlay, live_paint_gap_overlays, mirror_axis_overlay, nine_slice_overlay, original_path_overlay, print_tiling_overlay, radial_repeat_overlay, rotate_view_dial, shaper_widget_overlay, slice_overlay, spelling_overlay, thread_overlays, + trace_split_overlay, }; pub(crate) use view::animated_zoom; pub(crate) use view::drag_rotation; @@ -426,7 +427,11 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { draw_overlays(&painter, &xf, &overlays, &t, HandleLook::of(&app.session.prefs), &mut shared_paths); app.canvas.shared_paths = shared_paths; crate::panels::tabs::paint_stop_guide(app, &painter, &xf); - overlay_hover_text(ui, &xf, &overlays, ui.data(|d| d.get_temp::(drag_id())).is_some()); + // The tooltips say what a click does, so none shows where the click does something else: + // while Space lends a view tool, or over an artboard's name. + let space = ui.input(|i| drag::space_lends_view_tools(app, i.modifiers, i.key_down(egui::Key::Space))); + let quiet = space || ui.data(|d| d.get_temp::(drag_id())).is_some(); + overlay_hover_text(ui, &xf, &overlays, quiet, |p| artboards::artboard_name_at(app, ui, &xf, p).is_some()); if !revolve_edit { shaper_widget_overlay(app, &painter, &xf); crate::panels::three_d::paint_graphic_handles(app, &painter, &xf); @@ -1352,6 +1357,7 @@ fn selection_visuals( mirror_axis_overlay(app, painter, xf); grid_repeat_overlay(app, painter, xf); radial_repeat_overlay(app, painter, xf); + trace_split_overlay(app, painter, xf); if app.ui.view.text_threads { // Under the tools' overlays: a selected frame's own ports are drawn over its thread's. let mut threads = thread_overlays(app, xf.zoom); diff --git a/crates/ui-egui/src/canvas/overlays.rs b/crates/ui-egui/src/canvas/overlays.rs index de05367568..b4d2d44aac 100644 --- a/crates/ui-egui/src/canvas/overlays.rs +++ b/crates/ui-egui/src/canvas/overlays.rs @@ -216,15 +216,16 @@ pub(super) fn selection_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: anchor_square(p, xf.to_screen(a.p), color, false, anchor(direct)); } } - // Live Corners widgets (Selection and the shape tools on a live rectangle or polygon, Direct - // Selection on any path). + // Live Corners widgets (Selection and the shape tools on a live rectangle or polygon while Show + // Shape Widgets is on, Direct Selection on any path). + let shape_widgets = app.ui.view.shape_widgets; if (matches!(tool, "selection" | "directSelection") || (shape_tool && !drawing)) && let Some(w) = vectorcraft_tools::corners::CornerWidgets::showing( &st.doc, &st.selection, xf.zoom, tool == "directSelection", - app.ui.view.corner_widgets, + app.ui.view.corner_widgets && (tool == "directSelection" || shape_widgets), app.session.prefs.hide_corner_widget_above, ) { @@ -256,16 +257,21 @@ pub(super) fn selection_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: p.circle_stroke(c, r, Stroke::new(1.0, color)); } // A live polygon's side widget: a diamond beside the middle of the box's right side, drawn - // only while the box is drawn (the box hides during a turn and during a drag of the widget). - if !drawing_boxed && let Some(w) = vectorcraft_tools::sidewidget::SideWidget::of(&st.doc, &st.selection, &b, xf.zoom) { + // only while the box and the shape widgets are drawn (the box hides during a turn and during + // a drag of the widget). + if !drawing_boxed + && shape_widgets + && let Some(w) = vectorcraft_tools::sidewidget::SideWidget::of(&st.doc, &st.selection, &b, xf.zoom) + { let (c, r) = (xf.to_screen(w.at), vectorcraft_tools::sidewidget::RADIUS_PX); let diamond = vec![c + vec2(0.0, -r), c + vec2(r, 0.0), c + vec2(0.0, r), c + vec2(-r, 0.0)]; p.add(Shape::convex_polygon(diamond, Color32::WHITE, Stroke::new(1.0, color))); } } - // Pie widgets (Selection tool, with View › Show Bounding Box, on live ellipses): each joined - // by a line to the outline's point at its angle. They stay while one is dragged. - if (tool == "selection" || (shape_tool && !drawing)) && app.ui.view.bounding_box { + // Pie widgets (Selection tool, with View › Show Bounding Box and Show Shape Widgets, on live + // ellipses): each joined by a line to the outline's point at its angle. They stay while one is + // dragged. + if (tool == "selection" || (shape_tool && !drawing)) && app.ui.view.bounding_box && shape_widgets { for w in vectorcraft_tools::pie::PieWidget::of(&st.doc, &st.selection, xf.zoom) { let (on, c, r, color) = (xf.to_screen(w.on), xf.to_screen(w.at), vectorcraft_tools::pie::RADIUS_PX, c32(st.doc.layer_color(w.id))); p.line_segment([on, c], Stroke::new(1.0, color)); @@ -611,9 +617,11 @@ pub(super) fn draw_overlays(p: &egui::Painter, xf: &Xf, overlays: &[Overlay], t: /// The tooltips of the tool's [`Overlay::HoverText`] regions. Each region is a hover-only widget /// over the canvas, which keeps the clicks and drags; while the pointer rests inside a region's -/// disc, egui shows its text, translated, after its usual tooltip delay. No tooltip shows during a -/// canvas drag (`dragging`) or while a pointer button is down. -pub(super) fn overlay_hover_text(ui: &egui::Ui, xf: &Xf, overlays: &[Overlay], dragging: bool) { +/// disc, egui shows its text, translated, after its usual tooltip delay. Only the part of a disc +/// inside the canvas (`xf.rect`) has a tooltip, not the part under the rulers or scroll bars. No +/// tooltip shows while `quiet` (a canvas drag, or Space lending a view tool), while a pointer +/// button is down, or where `taken` says a press goes elsewhere (an artboard's name). +pub(super) fn overlay_hover_text(ui: &egui::Ui, xf: &Xf, overlays: &[Overlay], quiet: bool, taken: impl Fn(Pos2) -> bool) { let pressed = ui.input(|i| i.pointer.any_down()); for (i, o) in overlays.iter().enumerate() { let Overlay::HoverText { center, radius, text } = o else { continue }; @@ -622,9 +630,13 @@ pub(super) fn overlay_hover_text(ui: &egui::Ui, xf: &Xf, overlays: &[Overlay], d if !(r.is_finite() && r > 0.0 && c.is_finite()) { continue; } + let area = egui::Rect::from_center_size(c, vec2(2.0 * r, 2.0 * r)).intersect(xf.rect); + if !area.is_positive() { + continue; + } let id = egui::Id::unique("canvas-hover-text").with(i); - let resp = ui.interact(egui::Rect::from_center_size(c, vec2(2.0 * r, 2.0 * r)), id, egui::Sense::hover()); - if !dragging && !pressed && resp.hover_pos().is_some_and(|p| p.distance(c) <= r) { + let resp = ui.interact(area, id, egui::Sense::hover()); + if !quiet && !pressed && resp.hover_pos().is_some_and(|p| p.distance(c) <= r && xf.rect.contains(p) && !taken(p)) { resp.on_hover_text(crate::i18n::t(text)); } } diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 3adab31ffa..700f88df66 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -1249,6 +1249,127 @@ fn an_artboard_add_button_shows_its_tooltip_while_the_pointer_rests_on_it() { } } +/// The screen centers and radii of the Artboard tool's add-button tooltips (`tip`) in the view `xf`. +fn add_button_tips(app: &mut VectorcraftApp, xf: &Xf, tip: &str) -> Vec<(Pos2, f32)> { + let view = app.view_info(); + app.session + .overlays(view) + .into_iter() + .filter_map(|o| match o { + Overlay::HoverText { center, radius, text } if text == tip => Some((xf.to_screen(center), (radius * xf.zoom) as f32)), + _ => None, + }) + .collect() +} + +/// Whether `tip` shows while the pointer rests at `at` for two seconds from `*t`, which moves on. +fn rests_with_tooltip(app: &mut VectorcraftApp, ctx: &egui::Context, t: &mut f64, at: Pos2, tip: &str) -> bool { + texts_at(app, ctx, *t, vec![egui::Event::PointerMoved(at)]); + let mut seen = false; + for _ in 0..20 { + *t += 0.1; + seen |= texts_at(app, ctx, *t, vec![]).iter().any(|s| s == tip); + } + seen +} + +/// While Space lends a view tool, a press on an add button pans the view instead of adding an +/// artboard: the button shows no tooltip until Space is up. +#[test] +fn an_artboard_add_button_has_no_tooltip_while_space_is_held() { + use egui::{Event, Modifiers}; + let tip = vectorcraft_tools::xform::EDGE_BUTTON_TIP; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + app.select_tool("artboard"); + let ctx = egui::Context::default(); + texts_at(&mut app, &ctx, 0.0, vec![]); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let (at, _) = add_button_tips(&mut app, &xf, tip).into_iter().max_by(|a, b| a.0.y.total_cmp(&b.0.y)).unwrap(); + let space = |pressed| Event::Key { key: egui::Key::Space, physical_key: None, pressed, repeat: false, modifiers: Modifiers::NONE }; + let mut t = 1.0; + texts_at(&mut app, &ctx, t, vec![Event::PointerMoved(at), space(true)]); + for _ in 0..20 { + t += 0.1; + assert!(!texts_at(&mut app, &ctx, t, vec![]).iter().any(|s| s == tip), "no tooltip while Space is held"); + } + t += 0.1; + texts_at(&mut app, &ctx, t, vec![space(false)]); + assert!(rests_with_tooltip(&mut app, &ctx, &mut t, at, tip), "the tooltip shows again once Space is up"); +} + +/// On a narrow artboard with a long name, the name can cover part of the top add button, and a +/// press there selects the named artboard: that part shows no tooltip, and the rest of the button +/// keeps it. +#[test] +fn an_artboard_add_button_has_no_tooltip_where_the_artboard_name_covers_it() { + let tip = vectorcraft_tools::xform::EDGE_BUTTON_TIP; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 20, "height": 100})).unwrap(); + let name = "An artboard name long enough to run past the middle of its top edge"; + app.session.execute("artboard.setProps", &json!({"artboards": [{"index": 0, "name": name}]})).unwrap(); + app.select_tool("artboard"); + let ctx = egui::Context::default(); + texts_at(&mut app, &ctx, 0.0, vec![]); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let (at, r) = add_button_tips(&mut app, &xf, tip).into_iter().min_by(|a, b| a.0.y.total_cmp(&b.0.y)).unwrap(); + // The points of the button's disc, split by whether the canvas's name hit test takes them. + let probe = egui::Context::default(); + let named = |p: Pos2| { + let mut hit = false; + let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), ..Default::default() }; + let mut out = probe.run_ui(raw, |ui| hit = super::artboards::artboard_name_at(&app, ui, &xf, p).is_some()); + out.textures_delta.clear(); + hit + }; + let steps = || (-6i8..=6).map(f32::from); + let disc: Vec = steps().flat_map(|dx| steps().map(move |dy| at + vec2(dx, dy))).filter(|p| p.distance(at) <= r - 0.5).collect(); + let covered = disc.iter().copied().find(|p| named(*p)).expect("the name covers part of the button"); + let clear = disc.iter().copied().rev().find(|p| !named(*p)).expect("part of the button is clear of the name"); + let mut t = 1.0; + assert!(!rests_with_tooltip(&mut app, &ctx, &mut t, covered, tip), "no tooltip where the name takes the press"); + assert!(rests_with_tooltip(&mut app, &ctx, &mut t, clear, tip), "the tooltip shows on the rest of the button"); +} + +/// An add button panned under the scroll bars is not drawn and takes no press: none of it shows a +/// tooltip, in the square where the scroll bars meet or over a scroll bar, while the part of a +/// button still on the canvas keeps its tooltip. +#[test] +fn an_artboard_add_button_has_no_tooltip_outside_the_canvas() { + let tip = vectorcraft_tools::xform::EDGE_BUTTON_TIP; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + app.select_tool("artboard"); + let ctx = egui::Context::default(); + texts_at(&mut app, &ctx, 0.0, vec![]); + let rect = app.canvas_rect.unwrap(); + // Pan the view so the right button's center lands on `to`, and return the button. + let pan_right_button_to = |app: &mut VectorcraftApp, t: f64, to: Pos2| { + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let (at, _) = add_button_tips(app, &xf, tip).into_iter().max_by(|a, b| a.0.x.total_cmp(&b.0.x)).unwrap(); + let d = to - at; + if let Some(v) = app.view_mut() { + v.center = Point::new(v.center.x - f64::from(d.x) / v.zoom, v.center.y - f64::from(d.y) / v.zoom); + v.fitted = true; + } + texts_at(app, &ctx, t, vec![]); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let (at, r) = add_button_tips(app, &xf, tip).into_iter().max_by(|a, b| a.0.x.total_cmp(&b.0.x)).unwrap(); + assert!(at.distance(to) < 0.5, "the button moved to {to:?}: {at:?}"); + (at, r) + }; + // The middle of the square where the scroll bars meet, right of and below the canvas. + let corner = rect.max + vec2(SCROLL_BAR / 2.0, SCROLL_BAR / 2.0); + let mut t = 1.0; + let (at, _) = pan_right_button_to(&mut app, t, corner); + assert!(!rect.contains(at)); + assert!(!rests_with_tooltip(&mut app, &ctx, &mut t, at, tip), "no tooltip in the corner between the scroll bars"); + // Half on the canvas, half over the vertical scroll bar. + let (at, r) = pan_right_button_to(&mut app, t, pos2(rect.max.x, rect.center().y)); + assert!(!rests_with_tooltip(&mut app, &ctx, &mut t, at + vec2(r - 2.0, 0.0), tip), "no tooltip over the scroll bar"); + assert!(rests_with_tooltip(&mut app, &ctx, &mut t, at - vec2(r - 2.0, 0.0), tip), "the tooltip shows on the part on the canvas"); +} + #[test] fn shift_clicking_canvas_artboard_label_toggles_multi_selection() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); @@ -4938,6 +5059,91 @@ fn mirror_axis_drag_uses_canvas_coordinates_in_a_zoomed_rotated_view() { } } +/// The Split view's divider of a selected Image Trace object is drawn where the Selection tool +/// takes it in a zoomed, turned view. Dragging its middle across the image previews the divider, +/// commits one undo step and leaves the traced art where it was; Undo puts the divider back. +#[test] +fn trace_split_divider_drag_in_a_zoomed_rotated_view_is_one_undo_step() { + use vectorcraft_tools::trace_split::TraceDivider; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let data = vectorcraft_format::base64_encode(&crate::tests_sysclip::blue_png()); + app.run("file.place", json!({"name": "blue.png", "dataBase64": data, "link": false, "at": [200, 150]})).unwrap(); + app.run("imageTrace.make", json!({"preset": "Default"})).unwrap(); + app.run("imageTrace.setView", json!({"view": "split"})).unwrap(); + app.select_tool("selection"); + app.ui.task_bar = false; + app.ui.view.rulers = false; + let divider = |app: &VectorcraftApp| { + let st = app.session.active().unwrap(); + TraceDivider::of(&st.doc, &st.selection, app.view().unwrap().zoom).unwrap() + }; + let initial = divider(&app); + assert_eq!(initial.split, 0.5); + let middle = initial.ends[0].midpoint(initial.ends[1]); + { + let v = app.view_mut().unwrap(); + (v.zoom, v.rotation, v.center, v.fitted) = (30.0, 30.0, middle, true); + } + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let art = |app: &VectorcraftApp| { + let st = app.session.active().unwrap(); + st.doc.node(initial.id).unwrap().geometric_bounds() + }; + let before = (art(&app), app.session.active().unwrap().history.undo.len()); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + // The divider is drawn between its ends on screen. + let ends = initial.ends.map(|q| xf.to_screen(q)); + let drawn = shapes(&mut app, &ctx); + assert!( + drawn.iter().any(|s| matches!(s, Shape::LineSegment { points, .. } + if points.iter().zip(ends).all(|(a, b)| a.distance(b) < 0.5) || points.iter().rev().zip(ends).all(|(a, b)| a.distance(b) < 0.5))), + "the divider is drawn from {:?} to {:?}", + ends[0], + ends[1] + ); + // A quarter of the image's width to the right, in the image's own direction. + let from = xf.to_screen(middle); + let st = app.session.active().unwrap(); + let NodeKind::Image(im) = &st.doc.node(initial.id).unwrap().children().unwrap()[0].kind else { panic!("no source image") }; + let to = xf.to_screen(im.xf * vectorcraft_geom::Point::new(f64::from(im.width) * 0.75, f64::from(im.height) * 0.5)); + let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from), button(from, true)]); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(to)]); + assert!((divider(&app).split - 0.75).abs() < 0.01, "the divider previews during the drag: {}", divider(&app).split); + frame(&mut app, &ctx, vec![button(to, false)]); + assert!((divider(&app).split - 0.75).abs() < 0.01); + assert_eq!((art(&app), app.session.active().unwrap().history.undo.len()), (before.0, before.1 + 1), "one undo step, the art unmoved"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(divider(&app).split, 0.5); + // Escape during a drag puts the divider back with no undo step. + let steps = app.session.active().unwrap().history.undo.len(); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from), button(from, true)]); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(to)]); + assert!((divider(&app).split - 0.75).abs() < 0.01); + let escape = egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; + let raw = + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), events: vec![escape], ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| { + crate::shortcuts::handle(&mut app, ui.ctx()); + show(&mut app, ui) + }); + out.textures_delta.clear(); + assert!(!app.session.tool_busy(), "Escape ends the drag"); + assert_eq!(divider(&app).split, 0.5, "Escape puts the divider back"); + frame(&mut app, &ctx, vec![button(to, false)]); + assert_eq!(divider(&app).split, 0.5, "Escape cancels the drag"); + assert_eq!(app.session.active().unwrap().history.undo.len(), steps, "no undo step"); + // With the bounding box hidden, the divider is not drawn. + app.ui.view.bounding_box = false; + let drawn = shapes(&mut app, &ctx); + assert!( + !drawn.iter().any(|s| matches!(s, Shape::LineSegment { points, .. } if points.iter().zip(ends).all(|(a, b)| a.distance(b) < 0.5))), + "no divider with the bounding box hidden" + ); +} + /// A selected grid repeat draws its row handle below the grid and a slider between its first /// two columns (none with the bounding box hidden). Dragging the row handle down two tiles in /// a zoomed view makes five rows without scaling the source, as one undo step, and the slider @@ -6779,6 +6985,75 @@ fn a_selected_polygon_shows_its_side_widget() { assert_eq!(widgets(&mut app), 0, "an ellipse has none"); } +/// Hide Shape Widgets (`view.shapeWidgets`) hides a selected live rectangle's and polygon's corner +/// widgets, a polygon's side widget and an ellipse's pie widgets with the Selection tool and the +/// shape tools, and leaves the bounding box and its eight handles; the Selection tool then shows no +/// corner cursor over a hidden widget. Direct Selection keeps its corner widgets, which follow View › +/// Hide Corner Widget alone. Show Shape Widgets brings them back, neither adds an undo step, and a +/// tool switch keeps the setting. +#[test] +fn hidden_shape_widgets_leave_the_bounding_box() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let id = |v: serde_json::Value| v["id"].as_u64().unwrap(); + let rect = id(app.session.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 80, "height": 80})).unwrap()); + let polygon = id(app.session.execute("shape.polygon", &json!({"cx": 200, "cy": 150, "radius": 50, "sides": 5})).unwrap()); + let ellipse = id(app.session.execute("shape.ellipse", &json!({"x": 280, "y": 100, "width": 100, "height": 60})).unwrap()); + let ctx = egui::Context::default(); + let side = 2.0 * vectorcraft_tools::sidewidget::RADIUS_PX; + let diamond = |ps: &egui::epaint::PathShape| { + let span = |f: fn(&egui::Pos2) -> f32| { + let v: Vec = ps.points.iter().map(f).collect(); + v.iter().copied().fold(f32::MIN, f32::max) - v.iter().copied().fold(f32::MAX, f32::min) + }; + ps.closed && ps.points.len() == 4 && ps.fill == Color32::WHITE && (span(|p| p.x) - side).abs() < 0.01 && (span(|p| p.y) - side).abs() < 0.01 + }; + // The selection's corner, pie and side widgets drawn, and the bounding box's handles. + let drawn = |app: &mut VectorcraftApp, id: u64| { + app.session.execute("select.set", &json!({"ids": [id]})).unwrap(); + let (_, handles) = bounding_box_drawn(app, &ctx); + let all = shapes(app, &ctx); + let circles = |r: f32| all.iter().filter(|s| matches!(s, Shape::Circle(c) if c.radius == r && c.fill == Color32::WHITE)).count(); + let diamonds = all.iter().filter(|s| matches!(s, Shape::Path(ps) if diamond(ps))).count(); + (circles(3.0), circles(vectorcraft_tools::pie::RADIUS_PX), diamonds, handles) + }; + let steps = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len(); + for tool in ["selection", "polygon", "rectangle"] { + app.select_tool(tool); + assert_eq!(drawn(&mut app, rect), (4, 0, 0, 8), "{tool}"); + assert_eq!(drawn(&mut app, polygon), (5, 0, 1, 8), "{tool}"); + assert_eq!(drawn(&mut app, ellipse), (0, 2, 0, 8), "{tool}"); + let before = steps(&app); + assert_eq!(app.run("view.shapeWidgets", json!({})).unwrap(), json!(false)); + assert_eq!(steps(&app), before, "{tool}: the setting adds no undo step"); + assert_eq!(drawn(&mut app, rect), (0, 0, 0, 8), "{tool}"); + assert_eq!(drawn(&mut app, polygon), (0, 0, 0, 8), "{tool}"); + assert_eq!(drawn(&mut app, ellipse), (0, 0, 0, 8), "{tool}"); + assert_eq!(app.run("view.shapeWidgets", json!({})).unwrap(), json!(true)); + } + // Direct Selection: the corner widgets stay until View › Hide Corner Widget. + app.run("view.shapeWidgets", json!({"on": false})).unwrap(); + app.select_tool("directSelection"); + assert_eq!(drawn(&mut app, rect).0, 4); + app.run("view.cornerWidget", json!({})).unwrap(); + assert_eq!(drawn(&mut app, rect).0, 0); + app.run("view.cornerWidget", json!({})).unwrap(); + // The Selection tool shows no corner cursor over a hidden widget, and the tool switches kept the + // setting. + app.select_tool("selection"); + assert!(!app.ui.view.shape_widgets); + drawn(&mut app, rect); + let at = { + let st = app.session.active().unwrap(); + vectorcraft_tools::corners::CornerWidgets::of(&st.doc, &st.selection, app.view_info().zoom, false).unwrap().visible().next().unwrap() + }; + let view = app.view_info(); + assert_ne!(app.session.cursor(at, Mods::default(), view), Cursor::CornerRadius); + app.run("view.shapeWidgets", json!({"on": true})).unwrap(); + let view = app.view_info(); + assert_eq!(app.session.cursor(at, Mods::default(), view), Cursor::CornerRadius); +} + /// A selected Objects on Path group shows its Rotate All widget with the Selection and Objects on /// Path tools. #[test] @@ -10985,8 +11260,8 @@ fn frame_moves_stop_at_the_button_up() { let up = egui::Event::PointerButton { pos: b, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }; let events = vec![egui::Event::PointerMoved(a), egui::Event::PointerMoved(b), up, egui::Event::PointerMoved(c), egui::Event::PointerMoved(d)]; let feed = StylusFeed::default(); - let at_b = PenPose { tilt: Some([20.0, 0.0]), rotation: None }; - let after = PenPose { tilt: Some([50.0, 0.0]), rotation: None }; + let at_b = PenPose { tilt: Some([20.0, 0.0]), ..PenPose::default() }; + let after = PenPose { tilt: Some([50.0, 0.0]), ..PenPose::default() }; for (p, pose) in [(0.4, PenPose::default()), (0.6, at_b), (0.7, after), (0.8, after)] { feed.set_move(crate::stylus::PenSample { pressure: p, pose, ..Default::default() }); } @@ -11011,7 +11286,7 @@ fn frame_moves_keep_the_last_move_when_the_button_went_up_elsewhere() { let up = egui::Event::PointerButton { pos: up_at, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }; let events = vec![egui::Event::PointerMoved(a), egui::Event::PointerMoved(b), up, egui::Event::PointerMoved(c)]; let feed = StylusFeed::default(); - let at_b = PenPose { tilt: Some([20.0, 0.0]), rotation: None }; + let at_b = PenPose { tilt: Some([20.0, 0.0]), ..PenPose::default() }; for (p, pose) in [(0.4, PenPose::default()), (0.6, at_b), (0.7, PenPose::default())] { feed.set_move(crate::stylus::PenSample { pressure: p, pose, ..Default::default() }); } @@ -11037,7 +11312,7 @@ fn frame_moves_keeps_touch_feed_and_mouse_samples_with_their_pressure() { assert_eq!(mouse, [(a, None, None), (b, None, None)], "the last move follows the normal pointer path"); // A macOS pen: the feed kept a pressure and a pose for each move, the last for the last. let feed = StylusFeed::default(); - let leaning = PenPose { tilt: Some([30.0, 0.0]), rotation: None }; + let leaning = PenPose { tilt: Some([30.0, 0.0]), ..PenPose::default() }; for (p, pose) in [(0.9, leaning), (0.3, leaning), (0.0, PenPose::default()), (0.5, leaning)] { feed.set_move(crate::stylus::PenSample { pressure: p, pose, ..Default::default() }); } @@ -11556,7 +11831,7 @@ fn the_hosts_pen_tilt_and_rotation_reach_the_paintbrush() { assert_eq!(cmd, "path.freehand"); p["points"].as_array().unwrap().iter().map(|s| [3, 4, 5].map(|i| s.get(i).and_then(serde_json::Value::as_f64))).collect() }; - let leaning = PenPose { tilt: Some([30.0, 0.0]), rotation: Some(45.0) }; + let leaning = PenPose { tilt: Some([30.0, 0.0]), rotation: Some(45.0), wheel: None }; let points = stroke(&mut app, 260.0, Some(leaning)); assert!(!points.is_empty() && points.iter().all(|p| *p == [Some(30.0), Some(0.0), Some(45.0)]), "{points:?}"); // With the view rotated 90° clockwise, a pen leaning to the right of the screen leans up the @@ -11587,7 +11862,7 @@ fn moves_in_the_release_frame_reach_the_paintbrush_with_their_tilt() { let moved = |tilt: f32| { feed.set_move(crate::stylus::PenSample { pressure: 0.5, - pose: PenPose { tilt: Some([tilt, 0.0]), rotation: Some(0.0) }, + pose: PenPose { tilt: Some([tilt, 0.0]), rotation: Some(0.0), wheel: None }, ..Default::default() }) }; @@ -11630,8 +11905,11 @@ fn the_last_move_of_a_frame_keeps_its_own_tilt() { let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); let at = |x: f64| xf.to_screen(Point::new(x, 300.0)); let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; - let sample = - |tilt: f32| crate::stylus::PenSample { pressure: 0.5, pose: PenPose { tilt: Some([tilt, 0.0]), rotation: Some(0.0) }, ..Default::default() }; + let sample = |tilt: f32| crate::stylus::PenSample { + pressure: 0.5, + pose: PenPose { tilt: Some([tilt, 0.0]), rotation: Some(0.0), wheel: None }, + ..Default::default() + }; feed.set_move(sample(10.0)); frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at(300.0)), button(at(300.0), true)]); feed.set_move(sample(20.0)); @@ -13123,6 +13401,168 @@ fn text_threads_run_from_each_out_port_to_the_next_in_port() { assert!(thread_overlays(&app, zoom).is_empty()); } +#[test] +fn text_thread_overlays_keep_document_order_with_mixed_selection() { + use vectorcraft_doc::NodeId; + use vectorcraft_tools::text::{Port, port_centre}; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 600, "height": 400})).unwrap(); + let text = "Words that fill more than the frame holds. ".repeat(10); + let id = |value: serde_json::Value| NodeId(value["id"].as_u64().unwrap()); + let first = id(app.run("text.create", json!({"x": 20, "y": 20, "text": text, "area": {"width": 150, "height": 60}})).unwrap()); + let first_next = id(app.run("text.thread.add", json!({"from": first.0, "at": [300, 20]})).unwrap()); + let second = id(app + .run( + "text.create", + json!({"x": 20, "y": 200, "text": "Words that fill more than the frame holds. ".repeat(10), "area": {"width": 150, "height": 60}}), + ) + .unwrap()); + let second_next = id(app.run("text.thread.add", json!({"from": second.0, "at": [300, 200]})).unwrap()); + let unselected = id(app + .run("text.create", json!({"x": 20, "y": 100, "text": "An unselected story. ".repeat(20), "area": {"width": 150, "height": 60}})) + .unwrap()); + let unselected_next = id(app.run("text.thread.add", json!({"from": unselected.0, "at": [300, 100]})).unwrap()); + let unrelated_a = id(app.run("shape.rectangle", json!({"x": 450, "y": 300, "width": 20, "height": 20})).unwrap()); + let unrelated_b = id(app.run("shape.rectangle", json!({"x": 480, "y": 300, "width": 20, "height": 20})).unwrap()); + app.run("select.set", json!({"ids": [unrelated_a.0, unrelated_b.0, second_next.0, first.0]})).unwrap(); + + let state = app.session.active().unwrap(); + assert_eq!(state.selection.objects, [unrelated_a, unrelated_b, second_next, first]); + assert_eq!(state.doc.text_threads, [vec![first, first_next], vec![second, second_next], vec![unselected, unselected_next]]); + let frame = |id| match &state.doc.node(id).unwrap().kind { + NodeKind::Text(text) => (**text).clone(), + _ => panic!("thread member is text"), + }; + let px = 1.0; + let expected = [ + (port_centre(&frame(first), Port::Out, px).unwrap(), port_centre(&frame(first_next), Port::In, px).unwrap()), + (port_centre(&frame(second), Port::Out, px).unwrap(), port_centre(&frame(second_next), Port::In, px).unwrap()), + ]; + let overlays = thread_overlays(&app, 1.0); + let lines: Vec<_> = overlays + .iter() + .filter_map(|overlay| match overlay { + Overlay::Line { a, b, .. } if expected.iter().any(|(from, to)| *a == *from && *b == *to) => Some((*a, *b)), + _ => None, + }) + .collect(); + assert_eq!(lines, expected, "thread lines follow document order, not selection order"); + assert_eq!(overlays.iter().filter(|overlay| matches!(overlay, Overlay::Line { .. })).count(), 14, "two thread links and their port arrows only"); + let ports: Vec<_> = overlays + .iter() + .filter_map(|overlay| match overlay { + Overlay::Highlight { quad, .. } => Some(quad[0].midpoint(quad[2])), + _ => None, + }) + .collect(); + assert_eq!(ports, expected.into_iter().flat_map(|(from, to)| [from, to]).collect::>()); +} + +/// Two document-order threads hit the first two selected IDs among 512 unrelated paths. +/// Their real port geometry and document-order output remain unchanged. +#[test] +fn text_thread_overlays_keep_two_early_hits_with_many_unrelated_paths() { + use std::sync::Arc; + use vectorcraft_doc::NodeId; + use vectorcraft_tools::text::{Port, port_centre, ports_shown}; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 600, "height": 400})).unwrap(); + let text = "Words that fill more than the frame holds. ".repeat(10); + let id = |value: serde_json::Value| NodeId(value["id"].as_u64().unwrap()); + let mut threads = vec![]; + for y in [20, 200] { + let first = id(app.run("text.create", json!({"x": 20, "y": y, "text": text, "area": {"width": 150, "height": 60}})).unwrap()); + let next = id(app.run("text.thread.add", json!({"from": first.0, "at": [300, y]})).unwrap()); + threads.push([first, next]); + } + let path = id(app.run("shape.rectangle", json!({"x": 450, "y": 300, "width": 20, "height": 20})).unwrap()); + let mut selected = vec![threads[0][0], threads[1][0], path]; + { + let st = app.session.active_mut().unwrap(); + let doc = Arc::make_mut(&mut st.doc); + let template = doc.node(path).unwrap().clone(); + let mut additions = Vec::with_capacity(511); + for _ in 1..512 { + let mut p = template.clone(); + p.id = doc.alloc_id(); + selected.push(p.id); + additions.push(Arc::new(p)); + } + Arc::make_mut(&mut doc.layers[0]).children_mut().unwrap().extend(additions); + doc.drop_lookup_cache(); + } + app.run("select.set", json!({"ids": selected.iter().map(|id| id.0).collect::>()})).unwrap(); + let st = app.session.active().unwrap(); + assert_eq!(st.doc.text_threads, threads.iter().map(|t| t.to_vec()).collect::>()); + assert_eq!(st.selection.objects, selected); + assert_eq!(st.selection.objects.len(), 514); + assert!(ports_shown(&st.doc, &st.selection.objects)); + let frame = |id| match &st.doc.node(id).unwrap().kind { + NodeKind::Text(t) => (**t).clone(), + _ => panic!("thread member is text"), + }; + let expected: Vec<_> = + threads.iter().map(|[a, b]| (port_centre(&frame(*a), Port::Out, 1.0).unwrap(), port_centre(&frame(*b), Port::In, 1.0).unwrap())).collect(); + let overlays = thread_overlays(&app, 1.0); + let links: Vec<_> = overlays + .iter() + .filter_map(|o| match o { + Overlay::Line { a, b, .. } if expected.contains(&(*a, *b)) => Some((*a, *b)), + _ => None, + }) + .collect(); + assert_eq!(links, expected, "the two thread links stay in document order"); + assert_eq!(overlays.iter().filter(|o| matches!(o, Overlay::Line { .. })).count(), 14, "two links and their port arrows only"); + let ports: Vec<_> = overlays + .iter() + .filter_map(|o| match o { + Overlay::Highlight { quad, .. } => Some(quad[0].midpoint(quad[2])), + _ => None, + }) + .collect(); + assert_eq!(ports, expected.into_iter().flat_map(|(a, b)| [a, b]).collect::>()); +} + +/// One two-frame thread misses a selection of 512 unrelated paths. +/// This checks ordinary empty output, not elapsed time or allocation. +#[test] +fn text_thread_overlays_skip_one_unselected_thread_with_many_unrelated_paths() { + use std::sync::Arc; + use vectorcraft_doc::NodeId; + use vectorcraft_tools::text::{ported, ports_shown}; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 600, "height": 400})).unwrap(); + let text = "Words that fill more than the frame holds. ".repeat(10); + let id = |value: serde_json::Value| NodeId(value["id"].as_u64().unwrap()); + let first = id(app.run("text.create", json!({"x": 20, "y": 20, "text": text, "area": {"width": 150, "height": 60}})).unwrap()); + let next = id(app.run("text.thread.add", json!({"from": first.0, "at": [300, 20]})).unwrap()); + let path = id(app.run("shape.rectangle", json!({"x": 450, "y": 300, "width": 20, "height": 20})).unwrap()); + let mut selected = vec![path]; + { + let st = app.session.active_mut().unwrap(); + let doc = Arc::make_mut(&mut st.doc); + let template = doc.node(path).unwrap().clone(); + let mut additions = Vec::with_capacity(511); + for _ in 1..512 { + let mut p = template.clone(); + p.id = doc.alloc_id(); + selected.push(p.id); + additions.push(Arc::new(p)); + } + Arc::make_mut(&mut doc.layers[0]).children_mut().unwrap().extend(additions); + doc.drop_lookup_cache(); + } + app.run("select.set", json!({"ids": selected.iter().map(|id| id.0).collect::>()})).unwrap(); + let st = app.session.active().unwrap(); + assert_eq!(st.doc.text_threads, [vec![first, next]]); + assert_eq!(st.selection.objects, selected); + assert_eq!(st.selection.objects.len(), 512); + assert!(selected.iter().all(|id| *id != first && *id != next)); + assert!([first, next].into_iter().all(|id| ported(&st.doc, id).is_some()), "both thread frames have ports"); + assert!(ports_shown(&st.doc, &st.selection.objects)); + assert!(thread_overlays(&app, 1.0).is_empty()); +} + /// A double-click with the Selection tool on the out port of a threaded frame breaks the /// thread there: no new frame is threaded on, and the story flows back into the first frame. #[test] @@ -13173,6 +13613,103 @@ fn text_threads_of_a_huge_selection_have_lines_but_no_ports() { assert!(!o.iter().any(|x| matches!(x, Overlay::Highlight { .. } | Overlay::Path { .. })), "no port boxes"); } +/// An ignored diagnostic for the miss-heavy selection-membership work in `thread_overlays`. +/// Construct the document and selection before timing: T unrelated threads of F frames each miss +/// in a selection of S ordinary paths. There is deliberately no timing threshold; run on an idle +/// machine and compare the printed cases. +#[test] +#[ignore = "manual performance diagnostic; no stable timing threshold"] +fn thread_overlays_miss_heavy_selection_membership_diagnostic() { + use std::sync::Arc; + use std::time::Instant; + use vectorcraft_doc::NodeId; + use vectorcraft_tools::text::ported; + + fn fixture(threads: usize, frames_per_thread: usize, selected: usize) -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 600, "height": 400})).unwrap(); + let text = "Words that fill more than the frame holds. ".repeat(10); + let first = NodeId( + app.run("text.create", json!({"x": 20, "y": 20, "text": text, "area": {"width": 150, "height": 60}})).unwrap()["id"].as_u64().unwrap(), + ); + let second = NodeId(app.run("text.thread.add", json!({"from": first.0, "at": [300, 200]})).unwrap()["id"].as_u64().unwrap()); + let path = NodeId(app.run("shape.rectangle", json!({"x": 10, "y": 300, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap()); + let (thread_ids, selected_ids) = { + let st = app.session.active_mut().unwrap(); + let doc = Arc::make_mut(&mut st.doc); + let first_template = doc.node(first).unwrap().clone(); + let second_template = doc.node(second).unwrap().clone(); + let path_template = doc.node(path).unwrap().clone(); + let mut thread_ids = vec![vec![first, second]]; + let mut additions = Vec::with_capacity( + (threads.saturating_sub(1) * frames_per_thread) + frames_per_thread.saturating_sub(2) + selected.saturating_sub(1), + ); + + for _ in 2..frames_per_thread { + let mut next = second_template.clone(); + next.id = doc.alloc_id(); + thread_ids[0].push(next.id); + additions.push(Arc::new(next)); + } + + for _ in 1..threads { + let mut a = first_template.clone(); + a.id = doc.alloc_id(); + let mut b = second_template.clone(); + b.id = doc.alloc_id(); + let mut thread = vec![a.id, b.id]; + additions.push(Arc::new(a)); + additions.push(Arc::new(b)); + for _ in 2..frames_per_thread { + let mut next = second_template.clone(); + next.id = doc.alloc_id(); + thread.push(next.id); + additions.push(Arc::new(next)); + } + thread_ids.push(thread); + } + + let mut selected_ids = vec![path]; + for _ in 1..selected { + let mut p = path_template.clone(); + p.id = doc.alloc_id(); + selected_ids.push(p.id); + additions.push(Arc::new(p)); + } + + doc.text_threads = thread_ids.clone(); + Arc::make_mut(&mut doc.layers[0]).children_mut().unwrap().extend(additions); + doc.drop_lookup_cache(); + (thread_ids, selected_ids) + }; + app.run("select.set", json!({"ids": selected_ids.iter().map(|id| id.0).collect::>()})).unwrap(); + + let st = app.session.active().unwrap(); + assert_eq!(st.doc.text_threads, thread_ids); + assert!(thread_ids.iter().all(|thread| thread.len() == frames_per_thread)); + assert_eq!(st.selection.objects, selected_ids); + assert!(thread_ids.iter().flatten().all(|id| ported(&st.doc, *id).is_some()), "all thread frames have ports"); + assert!(selected_ids.iter().all(|id| thread_ids.iter().flatten().all(|frame| frame != id)), "selection misses every thread"); + app + } + + const REPEATS: usize = 2_000; + for (threads, frames_per_thread, selected) in [(256, 2, 256), (256, 2, 512), (512, 2, 256), (512, 2, 512), (512, 2, 1), (1, 1024, 512)] { + let app = fixture(threads, frames_per_thread, selected); + let st = app.session.active().unwrap(); + assert!(vectorcraft_tools::text::ports_shown(&st.doc, &st.selection.objects)); + + // Warm Document's id index and verify the negative output before timing. + assert!(thread_overlays(&app, 1.0).is_empty()); + let started = Instant::now(); + for _ in 0..REPEATS { + let overlays = thread_overlays(std::hint::black_box(&app), 1.0); + assert!(overlays.is_empty()); + } + println!("thread_overlays diagnostic T={threads} F={frames_per_thread} S={selected} repeats={REPEATS} elapsed={:?}", started.elapsed()); + } +} + /// A frame of a thread in perspective has no ports: Show Text Threads draws no port box on it /// and no line to or from it; the links between frames with ports keep theirs. #[test] diff --git a/crates/ui-egui/src/canvas/tool_overlays.rs b/crates/ui-egui/src/canvas/tool_overlays.rs index 5ccf5e4b9a..958872d6b0 100644 --- a/crates/ui-egui/src/canvas/tool_overlays.rs +++ b/crates/ui-egui/src/canvas/tool_overlays.rs @@ -446,13 +446,37 @@ pub(super) type Underlines = std::sync::Arc>; /// [`vectorcraft_tools::text::PORTS_MAX`] such frames selected the tools draw no ports, and only /// the lines are drawn here. `zoom`: screen pixels to the document unit. pub(super) fn thread_overlays(app: &VectorcraftApp, zoom: f64) -> Vec { + use std::collections::HashSet; + use vectorcraft_doc::NodeId; use vectorcraft_tools::text::{Port, PortState, port_centre, ported, ports_shown, push_port}; let Some(st) = app.session.active() else { return vec![] }; let px = 1.0 / zoom.max(1e-9); let boxes = ports_shown(&st.doc, &st.selection.objects); + let selection = &st.selection.objects; + let mut selected: Option> = None; + // The first two full searches need no index. + let mut full_searches = 0; + let mut is_selected = |id: &NodeId| { + if selection.len() <= 1 { + return selection.contains(id); + } + if full_searches == 0 { + full_searches = 1; + return selection.contains(id); + } + // Two early selection hits need no index. + if selected.is_none() && selection[..2].contains(id) { + return true; + } + if selected.is_none() && full_searches < 2 { + full_searches += 1; + return selection.contains(id); + } + selected.get_or_insert_with(|| selection.iter().copied().collect::>()).contains(id) + }; let mut o = vec![]; for thread in &st.doc.text_threads { - if !thread.iter().any(|id| st.selection.objects.contains(id)) { + if !thread.iter().any(&mut is_selected) { continue; } let color = st.doc.layer_color(thread[0]); @@ -637,6 +661,35 @@ pub(super) fn mirror_axis_overlay(app: &VectorcraftApp, p: &egui::Painter, xf: & p.rect_stroke(handle, 2.0, Stroke::new(2.0, t.measure_bg), StrokeKind::Outside); } +/// The Split view's divider of the selected Image Trace object, where the Selection tool's hit +/// testing finds it: a line across the source image with a grip in its middle, at its place in the +/// zoomed, scrolled or turned view. Hidden with the bounding box and in Outline mode, as the hit +/// testing is. +pub(super) fn trace_split_overlay(app: &VectorcraftApp, p: &egui::Painter, xf: &Xf) { + if app.session.tool_id() != "selection" || !app.ui.view.bounding_box || app.outline_view() { + return; + } + let Some(st) = app.session.active() else { return }; + let Some(d) = vectorcraft_tools::trace_split::TraceDivider::of(&st.doc, &st.selection, xf.zoom) else { return }; + let ends = d.ends.map(|q| xf.to_screen(q)); + if !ends.iter().all(|q| q.is_finite()) { + return; + } + let t = Tokens::get(p.ctx()); + if let Some((a, b)) = clip_segment(ends[0], ends[1], xf.rect) { + p.line_segment([a, b], Stroke::new(4.0, t.measure_bg)); + p.line_segment([a, b], Stroke::new(1.5, t.selection)); + } + let along = ends[1] - ends[0]; + let length = along.length(); + if length > 1.0 { + let mid = ends[0] + along * 0.5; + let half = along / length * vectorcraft_tools::trace_split::GRIP_HALF.min(length * 0.5); + p.line_segment([mid - half, mid + half], Stroke::new(7.0, t.measure_bg)); + p.line_segment([mid - half, mid + half], Stroke::new(4.0, t.selection)); + } +} + /// A selected grid repeat's row, column and corner handles and its spacing sliders (#2691), at /// the places the Selection tool's hit testing finds them. pub(super) fn grid_repeat_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: &Xf) { diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index 43b9f5b69c..ab0bc8ee1c 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -27,6 +27,7 @@ use control_bar::{CONTROL_BAR_FLOAT_AT, ISOLATION_BUTTON}; pub(crate) use control_bar::{Fit, group_separator, left_out, link_reserve}; #[cfg(test)] use hints::hint_segments; +pub(crate) use hints::tool_hint; pub use hints::{hint_bar, hint_strings}; pub use status_bar::{StatusBarShow, deserialize_status_bar_show, set_status_bar_show, status_bar}; #[cfg(test)] diff --git a/crates/ui-egui/src/chrome/control_bar.rs b/crates/ui-egui/src/chrome/control_bar.rs index e68f821261..ab5c9b121c 100644 --- a/crates/ui-egui/src/chrome/control_bar.rs +++ b/crates/ui-egui/src/chrome/control_bar.rs @@ -1039,26 +1039,26 @@ fn contents(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens, bar: egui::Rect, snapping_menu(app, ui); } let Some(st) = app.session.active() else { return }; - let sel = st.selection.objects.clone(); + let count = st.selection.objects.len(); let units = app.session.general_unit(); - let first = sel.first().and_then(|id| st.doc.node(*id)); + let first = st.selection.objects.first().and_then(|id| st.doc.node(*id)); let anchors = anchor_controls(app); let label = match first { _ if app.session.tool_id() == "artboard" => tl!("Artboard"), - Some(_) if sel.len() == 1 && anchors != AnchorControls::None => { + Some(_) if count == 1 && anchors != AnchorControls::None => { tl!("Anchor Point") } - Some(vectorcraft_doc::Node { kind: NodeKind::Image(im), .. }) if sel.len() == 1 => { + Some(vectorcraft_doc::Node { kind: NodeKind::Image(im), .. }) if count == 1 => { if im.link.is_some() { tl!("Linked File") } else { tl!("Embedded") } } - Some(n) if sel.len() == 1 && crate::panels::image_trace::is_trace(n) => { + Some(n) if count == 1 && crate::panels::image_trace::is_trace(n) => { tl!("Image Tracing") } - _ => tl!(crate::panels::appearance::object_label(app)), + _ => tl!(crate::panels::appearance::summary(app, ui.ctx()).map_or("No Selection", |s| s.label)), }; let has_first = first.is_some(); let label = egui::RichText::new(label).font(theme::semibold(12.0)).color(t.text); @@ -1077,7 +1077,7 @@ fn contents(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens, bar: egui::Rect, } if anchors != AnchorControls::None && group_on(app, "anchors") { anchor_buttons(app, ui, anchors); - let reserve = transform_reserve(app, ui, !sel.is_empty()); + let reserve = transform_reserve(app, ui, count > 0); corner_radius(app, ui, t, reserve); } let object_options = group_on(app, "objectOptions"); @@ -1087,7 +1087,7 @@ fn contents(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens, bar: egui::Rect, if ui.available_width() >= 6.0 { ui.add_space(6.0); } - let reserve = transform_reserve(app, ui, !sel.is_empty()); + let reserve = transform_reserve(app, ui, count > 0); // An image or an Image Trace object shows its own controls in place of Fill and Stroke, // and leaves Fill and Stroke out while the Image Options group is off too. These groups, // the tool options, the envelope's and the symbol instances' each show a control only while @@ -1108,11 +1108,11 @@ fn contents(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens, bar: egui::Rect, if !image && group_on(app, "fillStroke") { fill_and_stroke(app, ui, reserve); } - opacity_and_style(app, ui, t, opacity, !sel.is_empty(), reserve); + opacity_and_style(app, ui, t, opacity, count > 0, reserve); // The Character group shows whole, with the Transform link's room left after it, or not at // all; left out, it leaves out the groups between it and the link too. let room = !group_on(app, "character") || crate::panels::character::control_bar(app, ui, reserve); - if !groups_before_transform(app, ui, sel.len(), room) { + if !groups_before_transform(app, ui, count, room) { // With the Transform group off, its link and X/Y/W/H fields take no room. trailing_select_similar(app, ui); erase_trailing(ui); diff --git a/crates/ui-egui/src/chrome/hints.rs b/crates/ui-egui/src/chrome/hints.rs index 02f34438a6..2c679c72a1 100644 --- a/crates/ui-egui/src/chrome/hints.rs +++ b/crates/ui-egui/src/chrome/hints.rs @@ -206,6 +206,17 @@ pub(super) fn hint_segments(tool: &str) -> Vec<(Cow<'static, str>, bool)> { &search } }; + shown_segments(segments) +} + +/// The hint bar's segments for `tool` as [`hint_segments`] shows them, the Zoom tool's for animated +/// zoom when `animated_zoom` is on; none for a tool without a hint of its own. +pub(crate) fn tool_hint(tool: &str, animated_zoom: bool) -> Option, bool)>> { + let tool = if tool == "zoom" && animated_zoom { ANIMATED_ZOOM_HINT } else { tool }; + hint_for(tool).map(shown_segments) +} + +fn shown_segments(segments: &[(&'static str, bool)]) -> Vec<(Cow<'static, str>, bool)> { segments .iter() .map(|&(text, bold)| { diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 4c9506b13c..305b139391 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -2959,6 +2959,71 @@ fn full_screen_modes_fill_the_screen_and_normal_mode_restores_the_window() { assert!(sent(&mut app, true).is_empty(), "still full screen, as the user had it"); } +/// The Rectangle, Rounded Rectangle, Ellipse, Polygon and Star tools show Hide Shape Widgets in the +/// Control bar, with a selection and without one; a click hides the widgets and the button then reads +/// Show Shape Widgets, and a second click shows them again. The button comes before the shape's own +/// fields, so a window too narrow for the Polygon tool's Reset button still shows it. The Selection, +/// Spiral and Line Segment tools show no such button. +#[test] +fn the_shape_tools_control_bar_hides_and_shows_the_shape_widgets() { + struct RestoreLanguage(crate::i18n::Lang); + impl Drop for RestoreLanguage { + fn drop(&mut self) { + crate::i18n::set_current(self.0); + } + } + let _language = RestoreLanguage(crate::i18n::current()); + 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 ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + let frame_in = |app: &mut crate::VectorcraftApp, width: f32, events: Vec| { + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(width, 400.0)); + let mut out = ctx.run_ui(egui::RawInput { events, screen_rect: Some(screen), ..Default::default() }, |ui| super::control_bar(app, ui)); + out.textures_delta.clear(); + out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default() + }; + let frame = |app: &mut crate::VectorcraftApp, events: Vec| frame_in(app, 1600.0, events); + let button_in = |app: &mut crate::VectorcraftApp, width: f32, name: &str| { + frame_in(app, width, vec![]); + frame_in(app, width, vec![]).into_iter().find(|(_, n)| n.label() == Some(name)).and_then(|(_, n)| n.bounds()) + }; + let button = |app: &mut crate::VectorcraftApp, name: &str| button_in(app, 1600.0, name); + let click = |app: &mut crate::VectorcraftApp, name: &str| { + let b = button(app, name).unwrap_or_else(|| panic!("no {name}")); + let at = egui::pos2(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32); + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(app, vec![egui::Event::PointerMoved(at), press(true)]); + frame(app, vec![press(false)]); + }; + let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap()["id"].clone(); + for ids in [json!([id]), json!([])] { + app.run("select.set", json!({ "ids": ids })).unwrap(); + for tool in ["rectangle", "roundedRectangle", "ellipse", "polygon", "star"] { + app.select_tool(tool); + assert!(button(&mut app, "Hide Shape Widgets").is_some(), "{tool} {ids}"); + click(&mut app, "Hide Shape Widgets"); + assert!(!app.ui.view.shape_widgets, "{tool} {ids}"); + assert!(button(&mut app, "Hide Shape Widgets").is_none(), "{tool} {ids}"); + click(&mut app, "Show Shape Widgets"); + assert!(app.ui.view.shape_widgets, "{tool} {ids}"); + } + } + // Narrower and narrower: once the Polygon tool's Reset button is left out, the toggle still shows. + app.select_tool("polygon"); + let reset = button(&mut app, "Reset").expect("Reset in a wide window"); + let toggle = button(&mut app, "Hide Shape Widgets").expect("the toggle in a wide window"); + assert!(toggle.x1 <= reset.x0, "the toggle comes first: {toggle:?} {reset:?}"); + let narrow = (400..1600).step_by(10).rev().map(|w| w as f32).find(|w| button_in(&mut app, *w, "Reset").is_none()).expect("a width without Reset"); + assert!(button_in(&mut app, narrow, "Hide Shape Widgets").is_some(), "{narrow} wide"); + for tool in ["selection", "spiral", "lineSegment"] { + app.select_tool(tool); + assert!(button(&mut app, "Hide Shape Widgets").is_none(), "{tool}"); + } +} + /// Snapping quick access includes the existing glyph and alignment settings. Pointer clicks use /// their commands, and reopening reads the same state as View and Preferences (#6164). #[test] @@ -3645,6 +3710,30 @@ fn the_control_bar_keeps_its_label_and_menu_with_every_group_off() { assert!(!has(&bar, "Document Setup") && !has(&bar, "Preferences"), "{bar:?}"); } +/// The Control bar's selection label follows a selection whose middle object changes while its +/// length, first and last object stay the same, and a target circle with the selection unchanged. +#[test] +fn the_control_bar_label_follows_every_selected_object() { + use crate::tests_removeanchors::{control_frame, has}; + 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": 200})).unwrap(); + let id = |v: serde_json::Value| vectorcraft_doc::NodeId(v["id"].as_u64().unwrap()); + let r: Vec<_> = (0..3).map(|i| id(app.run("shape.rectangle", json!({"x": i * 30, "y": 10, "width": 20, "height": 20})).unwrap())).collect(); + let t = id(app.run("text.create", json!({"x": 10, "y": 100, "text": "Hi"})).unwrap()); + app.run("select.set", json!({ "ids": r })).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let alike = crate::panels::appearance::object_label(&app); + assert!(has(&control_frame(&mut app, &ctx, vec![]), alike), "{alike}"); + app.session.active_mut().unwrap().selection.objects[1] = t; + let bar = control_frame(&mut app, &ctx, vec![]); + assert!(has(&bar, "Mixed Objects"), "{bar:?}"); + let layer = app.session.active().unwrap().doc.default_layer().unwrap(); + app.session.active_mut().unwrap().selection.target = Some(layer); + assert!(has(&control_frame(&mut app, &ctx, vec![]), "Layer"), "the targeted layer"); +} + /// `window.control.options {group, visible?}` turns a group of the Control bar's options on or /// off, or toggles it, and the panel menu's item shows it; an unknown or missing group, or a /// `visible` that is not true or false, is an error and changes nothing. diff --git a/crates/ui-egui/src/custom_toolbars.rs b/crates/ui-egui/src/custom_toolbars.rs index fcbee2132a..11b8bbe145 100644 --- a/crates/ui-egui/src/custom_toolbars.rs +++ b/crates/ui-egui/src/custom_toolbars.rs @@ -1352,7 +1352,7 @@ fn slot_button(ui: &mut egui::Ui, t: &Tokens, p: &Press, slot: &[String], action } let tip = crate::toolbar::tip(shown); resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, ui.is_enabled(), is_active, &tip)); - resp.on_hover_text(tip); + crate::toolbar::card::hover(resp, shown, crate::toolbar::card::Side::Beside, Some(tip)); Some((rect, shown.id)) } diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 9e9c4e6816..f71f19e772 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -25,6 +25,7 @@ pub mod bullets_numbering; pub mod char_style_options; pub mod check_spelling; pub mod color_balance; +pub mod color_group_options; pub mod color_guide_options; pub(crate) mod color_picker; mod command; @@ -62,11 +63,13 @@ pub mod graph_design; pub mod graph_type; pub mod graphic_style_options; pub mod halftone; +pub mod hpgl_options; pub mod hyphenation; pub mod import_pdf; pub mod indexed_color; pub mod javascript_files; pub mod justification; +pub mod kinsoku_sets; pub mod layer_options; pub mod layers_panel_options; pub mod liquify; @@ -101,6 +104,7 @@ pub mod plugin; mod png_options; pub mod print; pub mod print_presets; +pub mod profile_mismatch; pub mod psd_import; mod psd_options; pub mod raster_effects; @@ -174,6 +178,7 @@ pub(crate) use form::{humanize, number_list_text, plugin_color_button, ppi_suffi pub use new_document::{create_without_dialog as new_document_without_dialog, open as open_new_document, preset_card}; pub(crate) use new_document::{popup_open as new_document_popup_open, preset_name}; pub use png_options::open as open_raster_options; +pub(crate) use save_pdf::{SAVE_SUMMARY as SAVE_PDF_SUMMARY, save_summary as save_pdf_summary, summary_open as pdf_summary_open}; pub use save_pdf::{open as open_save_pdf, open_preset as open_pdf_preset}; pub use tools::open_tool_dialog; @@ -349,6 +354,7 @@ registry! { MissingFontEdit: [confirm::MISSING_FONT_EDIT] => confirm::MISSING_FONT_EDIT_SPEC, NewSwatch: [new_swatch::KIND] => new_swatch::SPEC, NewColorGroup: [new_color_group::KIND] => new_color_group::SPEC, + ColorGroupOptions: [color_group_options::KIND] => color_group_options::SPEC, GraphData: [graph_data::KIND] => graph_data::SPEC, GraphDesign: [graph_design::DESIGN] => graph_design::DESIGN_SPEC, GraphColumn: [graph_design::COLUMN] => graph_design::COLUMN_SPEC, @@ -385,6 +391,7 @@ registry! { TateChuYokoSettings: [tate_chu_yoko::KIND] => tate_chu_yoko::SPEC, WarichuSettings: [warichu::KIND] => warichu::SPEC, CompositeFonts: [composite_fonts::KIND] => composite_fonts::SPEC, + KinsokuSets: [kinsoku_sets::KIND] => kinsoku_sets::SPEC, SavePdf: [save_pdf::KIND] => save_pdf::SPEC, SvgOptions: [svg_options::KIND] => svg_options::SPEC, JavaScriptFiles: [javascript_files::KIND] => javascript_files::SPEC, @@ -396,6 +403,8 @@ registry! { ExportAs: ["exportAs"] => export_as::SPEC, ImportPdf: [import_pdf::KIND] => import_pdf::SPEC, SwatchConflict: [swatch_conflict::KIND] => swatch_conflict::SPEC, + ProfileMismatchOpen: [profile_mismatch::OPEN_KIND] => profile_mismatch::OPEN_SPEC, + ProfileMismatchPaste: [profile_mismatch::PASTE_KIND] => profile_mismatch::PASTE_SPEC, FileInfo: [file_info::KIND] => file_info::SPEC, RasterEffectsSettings: [raster_effects::KIND] => raster_effects::SPEC, EffectGallery: [effect_gallery::KIND] => effect_gallery::SPEC, @@ -406,6 +415,7 @@ registry! { TextImport: [text_import::KIND] => text_import::SPEC, PdfPresets: [pdf_presets::KIND] => pdf_presets::SPEC, PdfPreset: [save_pdf::PRESET_KIND] => save_pdf::PRESET_SPEC, + PdfFlattenerOptions: [save_pdf::CUSTOM_KIND] => save_pdf::CUSTOM_SPEC, SaveOptions: [save_options::KIND] => save_options::SPEC, TextExport: [text_export::KIND] => text_export::SPEC, OfficeExport: [office_export::KIND] => office_export::SPEC, @@ -425,6 +435,7 @@ registry! { DivideSlices: [slices::DIVIDE] => slices::DIVIDE_SPEC, EpsOptions: [eps_options::KIND] => eps_options::SPEC, EpsFlattenerOptions: [eps_options::CUSTOM_KIND] => eps_options::CUSTOM_SPEC, + HpglOptions: [hpgl_options::KIND] => hpgl_options::SPEC, Recovery: [crate::recovery::KIND] => recovery::SPEC, PluginStopped: [safe_mode::STOPPED] => safe_mode::STOPPED_SPEC, SafeMode: [safe_mode::KIND] => safe_mode::SPEC, @@ -608,8 +619,10 @@ 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. An Import PDF -/// `allPages` set this way to the other pick sets Import PDF pages as links back to its default. +/// A Graph Data Column Width set this way sets every column, as Cell Style's does. A Width Point +/// Edit side width set this way for several points sets it on every point, as typing it 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); @@ -637,6 +650,7 @@ pub fn set_field(d: &mut Dialog, field: String, value: Value) { let dxf = (d.kind == dxf_options::KIND).then(|| field.clone()); let mosaic = (d.kind == object_mosaic::KIND).then(|| field.clone()); let graph = (d.kind == graph_data::KIND).then(|| field.clone()); + let width = (d.kind == width_point::KIND).then(|| field.clone()); d.fields.insert(field, value); if let Some(field) = dxf { dxf_options::note_set(d, &field); @@ -647,6 +661,9 @@ pub fn set_field(d: &mut Dialog, field: String, value: Value) { if let Some(field) = graph { graph_data::note_set(d, &field); } + if let Some(field) = width { + width_point::note_set(d, &field); + } } /// The fields `ui.dialog.set` can set on `d`, sorted: those it holds other than its `__` ones, the @@ -691,7 +708,7 @@ pub(crate) fn parent(d: &Dialog) -> Option { /// `ui.dialog.set` changed `field` of the open dialog from `old`: a choice that sets other fields /// sets them as choosing it in the dialog does (Export for Screens' `exportPreset`, EPS Options' -/// `flattenerPreset`, which drops the Custom… options), a change +/// and Save PDF's `flattenerPreset`, which drop the Custom… options), a change /// to Export for Screens' sub-folder controls ends an applied preset's item folders, as it does in /// the dialog, Transform Each's Relative / Absolute keeps the Scale fields' size, and Recolor /// Artwork's `group` selects that color group and its `groupAction` runs the button at once. Save @@ -737,9 +754,18 @@ pub fn cancel(app: &mut VectorcraftApp) { return; } if let Some(d) = app.ui.dialog.take() { + if d.kind == "preferences" { + crate::original_editor::cancel(app); + } if d.kind == swatch_conflict::KIND { crate::placing::cancel_swatch_paste(app); } + if d.kind == profile_mismatch::OPEN_KIND { + profile_mismatch::cancel_open(app); + } + if d.kind == profile_mismatch::PASTE_KIND { + crate::placing::cancel_swatch_paste(app); + } if d.kind == plugin::INSTALL_KIND { app.pending_plugin_install = None; } @@ -760,6 +786,10 @@ pub fn cancel(app: &mut VectorcraftApp) { script_run::picker_cancel(app, &d); } missing_links::cancelled(app, &d); + // Cancel discards Recolor Artwork's own history of color edits with them. + if d.kind == recolor::KIND { + app.ui.recolor_history = Default::default(); + } // Find Font's next open starts with an empty replacement search. if d.kind == "findFont" && let Some(ctx) = app.ui_ctx.clone() @@ -813,6 +843,7 @@ pub fn confirm(app: &mut VectorcraftApp) -> DialogResult { /// time). pub(crate) fn settle(app: &mut VectorcraftApp) { crate::placing::settle_swatch_paste(app); + profile_mismatch::settle(app); missing_fonts::requeue_replaced(app); missing_fonts::stop_when_closed(app); find_links::stop_when_closed(app); @@ -896,6 +927,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { let revolves = revolve_gizmo::active(&d); if revolves { revolve_gizmo::show(app, ctx, &mut d); + three_d_classic::surface_outline(app, ctx, &d); } let initial = if revolves { egui::vec2((ctx.content_rect().width() / 2.0 - 226.0).max(0.0), -40.0) } else { egui::vec2(0.0, -40.0) }; let id = egui::Id::unique(("dialog", d.kind.as_str())); diff --git a/crates/ui-egui/src/dialogs/brush_art_options.rs b/crates/ui-egui/src/dialogs/brush_art_options.rs index 64ea036fa2..308b3a9eb9 100644 --- a/crates/ui-egui/src/dialogs/brush_art_options.rs +++ b/crates/ui-egui/src/dialogs/brush_art_options.rs @@ -255,7 +255,8 @@ fn scatter_mode(d: &Dialog, key: &str) -> Variation { Variation::parse(&d.str(&mode_key(key))).unwrap_or_default() } -/// How an art brush's width varies: Fixed, or with the pen's pressure, tilt, bearing or rotation. +/// How an art brush's width varies: Fixed, or with the pen's pressure, tilt, bearing, rotation or +/// wheel. fn art_width_mode(d: &Dialog) -> Variation { Variation::parse(&d.str("widthMode")).filter(|m| m.follows_pen()).unwrap_or(Variation::Fixed) } @@ -436,7 +437,6 @@ fn flips(ui: &mut egui::Ui, d: &mut Dialog) { fn scatter_body(ui: &mut egui::Ui, d: &mut Dialog) { let labels = [tl!("Size:"), tl!("Spacing:"), tl!("Scatter:"), tl!("Rotation:")]; - let modes = Variation::ALL.map(Variation::label); egui::Grid::new("brush-options-scatter").num_columns(4).spacing([8.0, 8.0]).show(ui, |ui| { for (((key, suffix), range), text) in SCATTER.into_iter().zip(Scatter::RANGES).zip(labels) { super::swatch_options::label(ui, text); @@ -450,7 +450,9 @@ fn scatter_body(ui: &mut egui::Ui, d: &mut Dialog) { } }); } - if let Some(m) = widgets::dropdown(ui, ("brush-scatter-mode", key), mode.label(), &modes, 104.0).and_then(|i| Variation::ALL.get(i)) { + let offered = Variation::offered(key == "size"); + let modes: Vec<&str> = offered.iter().map(|m| m.label()).collect(); + if let Some(m) = widgets::dropdown(ui, ("brush-scatter-mode", key), mode.label(), &modes, 104.0).and_then(|i| offered.get(i)) { d.fields.insert(mode_key(key), json!(m.id())); } ui.end_row(); @@ -472,7 +474,7 @@ fn art_body(ui: &mut egui::Ui, d: &mut Dialog) { super::form::slider_field_named(ui, d, "width", tl!("Width:"), range.0..=range.1, "%", &|_| rail); let mode = art_width_mode(d); number(ui, d, "widthMax", range, "%", mode.follows_pen()); - let modes = [Variation::Fixed, Variation::Pressure, Variation::Tilt, Variation::Bearing, Variation::Rotation]; + let modes = [Variation::Fixed, Variation::Pressure, Variation::Tilt, Variation::Bearing, Variation::Rotation, Variation::StylusWheel]; if let Some(m) = widgets::dropdown(ui, "brush-art-width-mode", mode.label(), &modes.map(Variation::label), 104.0).and_then(|i| modes.get(i)) { d.fields.insert("widthMode".into(), json!(m.id())); } diff --git a/crates/ui-egui/src/dialogs/brush_options.rs b/crates/ui-egui/src/dialogs/brush_options.rs index eafe697a0f..f8b25e8249 100644 --- a/crates/ui-egui/src/dialogs/brush_options.rs +++ b/crates/ui-egui/src/dialogs/brush_options.rs @@ -454,8 +454,9 @@ fn calligraphic_body(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { d.fields.insert(key.into(), json!(v)); } let mode = Variation::parse(&d.str(&mode_key(key))).unwrap_or_default(); - let labels = Variation::ALL.map(Variation::label); - if let Some(m) = widgets::dropdown(ui, ("brush-mode", key), mode.label(), &labels, 104.0).and_then(|i| Variation::ALL.get(i)) { + let offered = Variation::offered(key == "size"); + let labels: Vec<&str> = offered.iter().map(|m| m.label()).collect(); + if let Some(m) = widgets::dropdown(ui, ("brush-mode", key), mode.label(), &labels, 104.0).and_then(|i| offered.get(i)) { d.fields.insert(mode_key(key), json!(m.id())); } label(ui, tl!("Variation:")); diff --git a/crates/ui-egui/src/dialogs/color_group_options.rs b/crates/ui-egui/src/dialogs/color_group_options.rs new file mode 100644 index 0000000000..101b5496a3 --- /dev/null +++ b/crates/ui-egui/src/dialogs/color_group_options.rs @@ -0,0 +1,182 @@ +//! Color Group Options: the name of a color group in the Swatches panel. OK renames the group +//! (`swatch.renameGroup`) and keeps it selected in the panel; its swatches and their colors stay +//! as they are. +//! +//! Fields: `name`, `__group` (the group being renamed), `__swatches` (the names of its swatches +//! when the dialog opened), `__index` (its place in the list of color groups) and `__doc` (the uid +//! of its document). + +use serde_json::{Value, json}; + +use super::swatch_options::{grid, label}; +use super::{DialogSpec, form}; +use crate::VectorcraftApp; +use crate::state::Dialog; + +/// The dialog kind of Color Group Options. +pub const KIND: &str = "colorGroupOptions"; + +pub(super) const SPEC: DialogSpec = + DialogSpec { heading: |_| tl!("Color Group Options").into(), body, confirm, min_width: 320.0, ..DialogSpec::FORM }; + +/// The field that holds the uid of the document the dialog opened on. +const DOC: &str = "__doc"; + +/// The field that holds the names of the group's swatches when the dialog opened. +const SWATCHES: &str = "__swatches"; + +/// The field that holds the group's place in the document's list of color groups. +const INDEX: &str = "__index"; + +/// `ui.colorGroupOptions {group?}`: open Color Group Options for color group `group`, or without +/// `group` for the color group selected alone in the Swatches panel. +pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { + let key = "group"; + let group = match p.get(key) { + Some(Value::String(g)) => g.clone(), + None | Some(Value::Null) => crate::panels::swatches::sole_selected_group(app).ok_or("missing `group`")?, + Some(_) => return Err(format!("`{key}` must be a string")), + }; + let st = app.session.active().ok_or("no document open")?; + let at = st.doc.swatch_groups.iter().position(|g| g.name == group).ok_or_else(|| format!("no colour group `{group}`"))?; + let g = &st.doc.swatch_groups[at]; + let swatches: Vec<&str> = g.swatches.iter().map(|w| w.name.as_str()).collect(); + let fields = json!({ "name": g.name.clone(), "__group": g.name.clone(), SWATCHES: swatches, INDEX: at, DOC: st.uid }); + app.ui.dialog = Some(Dialog::new(KIND, fields)); + Ok(Value::Null) +} + +/// Whether the dialog's group is still in its document, at the place in the list, under the name +/// and with the swatches it opened with, and that document is the active one. +fn same_group(app: &VectorcraftApp, d: &Dialog) -> bool { + let Some(st) = app.session.active().filter(|st| d.fields.get(DOC).and_then(Value::as_u64) == Some(st.uid)) else { return false }; + let at = d.fields.get(INDEX).and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok()); + let opened: Vec<&str> = + d.fields.get(SWATCHES).and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).collect()).unwrap_or_default(); + let group = d.str("__group"); + at.and_then(|i| st.doc.swatch_groups.get(i)) + .is_some_and(|g| g.name == group && g.swatches.iter().map(|w| w.name.as_str()).eq(opened.iter().copied())) +} + +fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + grid(ui, |ui| { + label(ui, tl!("Name:")); + form::text(ui, d, "name", 190.0); + ui.end_row(); + }); + false +} + +/// OK: rename the group (the Swatches panel keeps it selected, [`crate::panels::swatches::after_command`]). +/// A name that is empty or that another group or a swatch has keeps the dialog open. When another +/// document has become the active one, or the color group at the group's place in the list no +/// longer has the name and swatches it opened with, it closes as Cancel does and renames nothing. +/// Color groups carry nothing else to tell them apart. +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + if !same_group(app, d) { + app.ui.dialog = None; + return Ok(json!({})); + } + let r = app.run("swatch.renameGroup", json!({ "group": d.str("__group"), "name": d.str("name") })); + if r.is_ok() { + app.ui.dialog = None; + } + r +} + +#[cfg(test)] +mod tests { + use super::*; + use vectorcraft_engine::Session; + + fn app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app + } + + fn set(app: &mut VectorcraftApp, v: &str) { + app.ui.dialog.as_mut().unwrap().fields.insert("name".into(), json!(v)); + } + + fn groups(app: &VectorcraftApp) -> Vec { + app.session.active().unwrap().doc.swatch_groups.iter().map(|g| g.name.clone()).collect() + } + + fn undo_len(app: &VectorcraftApp) -> usize { + app.session.active().unwrap().history.undo.len() + } + + /// The dialog opens on the group's name; OK renames it in one undo step, a taken or empty name + /// keeps the dialog open with nothing changed, Cancel changes nothing, and OK with the name + /// unchanged records no undo step. + #[test] + fn renames_the_group_and_keeps_a_refused_name_open() { + let mut app = app(); + app.run("ui.colorGroupOptions", json!({"group": "Brights"})).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.kind.as_str(), d.str("name").as_str(), d.str("__group").as_str()), (KIND, "Brights", "Brights")); + // Drawn headlessly in the shared frame. + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut out = ctx.run_ui(Default::default(), |ui| super::super::show(&mut app, ui.ctx())); + out.textures_delta.clear(); + let undo = undo_len(&app); + for taken in ["Grays", "White", " "] { + set(&mut app, taken); + assert!(super::super::confirm(&mut app).is_err(), "{taken:?}"); + assert!(app.ui.dialog.is_some(), "{taken:?} keeps the dialog open"); + assert_eq!(undo_len(&app), undo, "{taken:?}"); + } + set(&mut app, "Vivid"); + super::super::cancel(&mut app); + assert!(app.ui.dialog.is_none() && groups(&app).contains(&"Brights".to_string()), "Cancel keeps the name"); + assert_eq!(undo_len(&app), undo); + app.run("ui.colorGroupOptions", json!({"group": "Brights"})).unwrap(); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(undo_len(&app), undo, "the same name records no undo step"); + app.run("ui.colorGroupOptions", json!({"group": "Brights"})).unwrap(); + set(&mut app, "Vivid"); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none() && groups(&app).contains(&"Vivid".to_string())); + assert_eq!(undo_len(&app), undo + 1); + assert!(app.run("ui.colorGroupOptions", json!({"group": "Brights"})).is_err()); + assert!(app.run("ui.colorGroupOptions", json!({"group": "White"})).is_err(), "a swatch is not a group"); + assert!(app.run("ui.colorGroupOptions", json!({})).is_err()); + assert!(app.run("ui.colorGroupOptions", json!({"group": 5})).is_err()); + } + + /// OK closes the dialog and renames nothing when another document has become the active one, + /// or when another group took the name of the group it opened on while it was open. + #[test] + fn renames_only_the_group_it_opened_on() { + let mut app = app(); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("ui.colorGroupOptions", json!({"group": "Brights"})).unwrap(); + app.run("document.activate", json!({"index": 1})).unwrap(); + set(&mut app, "Vivid"); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert!(groups(&app).contains(&"Brights".to_string()), "the document made active keeps its group"); + app.run("document.activate", json!({"index": 0})).unwrap(); + assert!(groups(&app).contains(&"Brights".to_string()), "the group it opened on keeps its name"); + // Its group ungrouped, and another group renamed to its name. + app.run("ui.colorGroupOptions", json!({"group": "Brights"})).unwrap(); + app.run("swatch.ungroup", json!({"name": "Brights"})).unwrap(); + app.run("swatch.renameGroup", json!({"group": "Grays", "name": "Brights"})).unwrap(); + set(&mut app, "Vivid"); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert!(groups(&app).contains(&"Brights".to_string()) && !groups(&app).contains(&"Vivid".to_string())); + // Its group moved to another place in the list. + app.run("swatch.newGroup", json!({"name": "Extra", "swatches": ["White"]})).unwrap(); + let first = groups(&app)[0].clone(); + app.run("ui.colorGroupOptions", json!({"group": first})).unwrap(); + app.run("swatch.move", json!({"names": [first]})).unwrap(); + set(&mut app, "Vivid"); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none() && groups(&app).contains(&first) && !groups(&app).contains(&"Vivid".to_string())); + } +} diff --git a/crates/ui-egui/src/dialogs/command.rs b/crates/ui-egui/src/dialogs/command.rs index de7836f0a5..6fd3009921 100644 --- a/crates/ui-egui/src/dialogs/command.rs +++ b/crates/ui-egui/src/dialogs/command.rs @@ -84,7 +84,8 @@ fn heading_in(lang: crate::i18n::Lang, label: &str) -> String { /// too (#5360), as public tutorials of the dialog show, and Type Tools › Release Type on a Path /// works the same way (#5532), and so do Image Tools › Remove Background and Color Mask and /// Cutting Tools › Weed Box and Lines, Banner Hems and Grommets and Nest Shapes, and Path -/// Precision Tools › Common Tangents. (Cancel rolls a preview back whichever dialog started it.) +/// Precision Tools › Common Tangents and the bounding shapes (Add Bounding Rectangle… and Add +/// Bounding Circle…). (Cancel rolls a preview back whichever dialog started it.) fn previews(d: &Dialog) -> bool { match d.str("__command").as_str() { "object.repeat.options" => d.fields.contains_key("gridType"), @@ -95,7 +96,9 @@ fn previews(d: &Dialog) -> bool { | crate::addons::cutting::WEED | crate::addons::cutting::BANNER | crate::addons::cutting::NEST - | crate::addons::pathtools::COMMON_TANGENTS => true, + | crate::addons::pathtools::COMMON_TANGENTS + | crate::addons::pathtools::BOUNDING_RECTANGLE + | crate::addons::pathtools::BOUNDING_CIRCLE => true, _ => false, } } @@ -150,6 +153,7 @@ fn lengths(command: &str) -> &'static [&'static str] { "object.pathfinder.trap" => &["thickness"], crate::addons::cutting::BRIDGES => &["width"], "object.textWrap.options" => &["offset"], + crate::addons::pathtools::BOUNDING_RECTANGLE | crate::addons::pathtools::BOUNDING_CIRCLE => &["offset"], _ => &[], } } @@ -159,6 +163,11 @@ fn lengths(command: &str) -> &'static [&'static str] { pub(super) fn length_range(command: &str, key: &str) -> Option> { match (command, key) { ("object.textWrap.options", "offset") => Some(vectorcraft_engine::TEXT_WRAP_OFFSET_RANGE), + // The bounding shapes take an offset of 0 or more, and the command refuses one that takes + // the shape past the canvas edge. + (crate::addons::pathtools::BOUNDING_RECTANGLE | crate::addons::pathtools::BOUNDING_CIRCLE, "offset") => { + Some(0.0..=vectorcraft_engine::MAX_COORD) + } _ => None, } } @@ -182,6 +191,7 @@ fn order(command: &str) -> &'static [&'static str] { crate::addons::cutting::BRIDGES => &["width", "count", "direction", "keepOriginal"], crate::addons::packaging::SET_ROLE_SWATCH => &["role", "swatch"], crate::addons::pathtools::COMMON_TANGENTS => &["tangents", "centerline"], + crate::addons::pathtools::BOUNDING_RECTANGLE | crate::addons::pathtools::BOUNDING_CIRCLE => &["offset", "each"], _ => &[], } } diff --git a/crates/ui-egui/src/dialogs/confirm.rs b/crates/ui-egui/src/dialogs/confirm.rs index b4fd6f037e..1ca56cdf5c 100644 --- a/crates/ui-egui/src/dialogs/confirm.rs +++ b/crates/ui-egui/src/dialogs/confirm.rs @@ -130,6 +130,7 @@ pub(crate) fn ask_reset_prefs(app: &mut VectorcraftApp) { fn reset_prefs(app: &mut VectorcraftApp, d: &Dialog) -> Result { let mut prefs = super::parent(d).filter(|p| p.kind == "preferences").ok_or("the dialog it was opened over is no longer open")?; crate::prefs_dialog::reset_fields(&mut prefs); + crate::original_editor::reset(app); app.ui.dialog = Some(prefs); Ok(Value::Null) } diff --git a/crates/ui-egui/src/dialogs/eps_options.rs b/crates/ui-egui/src/dialogs/eps_options.rs index 0eb1853065..40c5f728f9 100644 --- a/crates/ui-egui/src/dialogs/eps_options.rs +++ b/crates/ui-egui/src/dialogs/eps_options.rs @@ -202,7 +202,7 @@ fn custom_body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> let (mut o, unread) = super::flatten::shown_options(&d.fields, ¤t); o.preserve_alpha = false; o.preserve_overprints &= overprints_kept(d); - super::flatten::fields_editor(ui, "eps-flattener", &mut d.fields, &mut o, &unread, true); + super::flatten::fields_editor(ui, "eps-flattener", &mut d.fields, &mut o, &unread, &["preserveAlpha", "preserveOverprints"]); if let Err(e) = ¤t { ui.label(egui::RichText::new(e).color(Tokens::get(ui.ctx()).text_dim).size(11.5)); } diff --git a/crates/ui-egui/src/dialogs/export_as.rs b/crates/ui-egui/src/dialogs/export_as.rs index cd18d6b153..60701aae13 100644 --- a/crates/ui-egui/src/dialogs/export_as.rs +++ b/crates/ui-egui/src/dialogs/export_as.rs @@ -2,7 +2,7 @@ //! artboard, after a central file of the whole document for EPS with two or more when art shows, //! or one page each in a PDF); without artboards the export covers the visible art. OK //! picks the file, then the format's options dialog follows (PNG/JPEG/WebP/PNG-8/GIF Options, SVG -//! Options, Text Export Options, DXF Options, EPS Options, and Save PDF), +//! Options, Text Export Options, DXF Options, EPS Options, HP-GL Options, and Save PDF), //! else the file is written. DWG is listed, greyed out, with what to use instead. The formats of //! installed exporter plug-ins come after the built-in ones: they write the whole document (from //! Export Selection, the selection), and one with parameters asks for them before writing @@ -14,7 +14,7 @@ use std::sync::LazyLock; use serde_json::{Value, json}; use vectorcraft_engine::cmd::fileio::{self, ArtboardPick, Format}; -use super::{DialogSpec, dxf_options, eps_options, form, plugin, png_options, save_pdf, svg_options, text_export}; +use super::{DialogSpec, dxf_options, eps_options, form, hpgl_options, plugin, png_options, save_pdf, svg_options, text_export}; use crate::state::Dialog; use crate::theme::Tokens; use crate::{VectorcraftApp, io, widgets}; @@ -234,7 +234,7 @@ fn options_or_write( } } let plugin = plugin.filter(|p| !p.manifest().params.is_empty()); - let dialog = plugin.is_none() && (f.raster || matches!(f.id, "dxf" | "eps")); + let dialog = plugin.is_none() && (f.raster || matches!(f.id, "dxf" | "eps" | "hpgl")); if selection { // An options dialog keeps the mark as a field of its own, which OK hands on. params[if dialog { SELECTION_FIELD } else { io::EXPORT_SELECTION }] = json!(true); @@ -255,6 +255,10 @@ fn options_or_write( eps_options::open(app, ¶ms); return Ok(Value::Null); } + if f.id == "hpgl" { + hpgl_options::open(app, ¶ms); + return Ok(Value::Null); + } return io::export(app, Some(f.id), Some(path), ¶ms); } }; diff --git a/crates/ui-egui/src/dialogs/flatten.rs b/crates/ui-egui/src/dialogs/flatten.rs index a22631c8e2..456145bfc6 100644 --- a/crates/ui-egui/src/dialogs/flatten.rs +++ b/crates/ui-egui/src/dialogs/flatten.rs @@ -76,17 +76,10 @@ pub(crate) fn shown_options(fields: &Map, current: &Result, - o: &mut FlattenOptions, - unread: &[String], - fixed_preserve: bool, -) { - let set = editor(ui, id, o, true, fixed_preserve, unread); +/// so that it replaces a value of the wrong type; the other fields stay as they were entered. The +/// switches of the options named in `fixed` show but can't be changed. +pub(crate) fn fields_editor(ui: &mut egui::Ui, id: &str, fields: &mut Map, o: &mut FlattenOptions, unread: &[String], fixed: &[&str]) { + let set = editor(ui, id, o, true, fixed, unread); let Ok(Value::Object(m)) = serde_json::to_value(&*o) else { return }; for k in set { if let Some(v) = m.get(k) { @@ -150,7 +143,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { ui.add_space(10.0); // Values refused stay as entered, so that changing another option keeps them. let (mut o, unread) = shown_options(&d.fields, ¤t); - fields_editor(ui, "flatten-dialog", &mut d.fields, &mut o, &unread, false); + fields_editor(ui, "flatten-dialog", &mut d.fields, &mut o, &unread, &[]); if let Err(e) = ¤t { ui.label(egui::RichText::new(e).color(Tokens::get(ui.ctx()).text_dim).size(11.5)); } @@ -227,15 +220,15 @@ const FIELD: f32 = 56.0; /// when one changed. pub(crate) fn options_editor(ui: &mut egui::Ui, id: &str, o: &mut FlattenOptions, enabled: bool) -> bool { let before = o.clone(); - editor(ui, id, o, enabled, false, &[]); + editor(ui, id, o, enabled, &[], &[]); *o != before } -/// The option controls, with the value fields of the options named in `unread` blank. With -/// `fixed_preserve`, Preserve Alpha Transparency and Preserve Overprints and Spot Colors show but -/// can't be changed (the file format or another control sets them). Returns the keys of the -/// options whose controls were set, also to the value they showed. -fn editor(ui: &mut egui::Ui, id: &str, o: &mut FlattenOptions, enabled: bool, fixed_preserve: bool, unread: &[String]) -> Vec<&'static str> { +/// The option controls, with the value fields of the options named in `unread` blank. The +/// switches of the options named in `fixed` show but can't be changed (the file format or another +/// control sets them). Returns the keys of the options whose controls were set, also to the value +/// they showed. +fn editor(ui: &mut egui::Ui, id: &str, o: &mut FlattenOptions, enabled: bool, fixed: &[&str], unread: &[String]) -> Vec<&'static str> { let t = Tokens::get(ui.ctx()); let mut set = Vec::new(); let field_value = |key: &str, v: f64| (!unread.iter().any(|k| k == key)).then_some(v); @@ -289,16 +282,16 @@ fn editor(ui: &mut egui::Ui, id: &str, o: &mut FlattenOptions, enabled: bool, fi } }); ui.add_space(4.0); - let switches: [(&str, &mut bool, bool, &'static str); 6] = [ - (tl!("Convert All Text to Outlines"), &mut o.text_to_outlines, false, "textToOutlines"), - (tl!("Convert All Strokes to Outlines"), &mut o.strokes_to_outlines, false, "strokesToOutlines"), - (tl!("Clip Complex Regions"), &mut o.clip_complex_regions, false, "clipComplexRegions"), - (tl!("Anti-alias Rasters"), &mut o.anti_alias, false, "antiAlias"), - (tl!("Preserve Alpha Transparency"), &mut o.preserve_alpha, fixed_preserve, "preserveAlpha"), - (tl!("Preserve Overprints and Spot Colors"), &mut o.preserve_overprints, fixed_preserve, "preserveOverprints"), + let switches: [(&str, &mut bool, &'static str); 6] = [ + (tl!("Convert All Text to Outlines"), &mut o.text_to_outlines, "textToOutlines"), + (tl!("Convert All Strokes to Outlines"), &mut o.strokes_to_outlines, "strokesToOutlines"), + (tl!("Clip Complex Regions"), &mut o.clip_complex_regions, "clipComplexRegions"), + (tl!("Anti-alias Rasters"), &mut o.anti_alias, "antiAlias"), + (tl!("Preserve Alpha Transparency"), &mut o.preserve_alpha, "preserveAlpha"), + (tl!("Preserve Overprints and Spot Colors"), &mut o.preserve_overprints, "preserveOverprints"), ]; - for (label, v, fixed, key) in switches { - if widgets::check(ui, label, *v, enabled && !fixed) { + for (label, v, key) in switches { + if widgets::check(ui, label, *v, enabled && !fixed.contains(&key)) { *v = !*v; set.push(key); } diff --git a/crates/ui-egui/src/dialogs/form.rs b/crates/ui-egui/src/dialogs/form.rs index b46f35a79f..f19cd18cda 100644 --- a/crates/ui-egui/src/dialogs/form.rs +++ b/crates/ui-egui/src/dialogs/form.rs @@ -847,6 +847,7 @@ pub(crate) fn humanize(k: &str) -> String { "Traps With Process Color" => "Traps with Process Color:".into(), "Cols" => "Columns:".into(), "Flip Cols" => "Flip Columns:".into(), + "Each" => "One per Object:".into(), _ => format!("{s}:"), } } diff --git a/crates/ui-egui/src/dialogs/hpgl_options.rs b/crates/ui-egui/src/dialogs/hpgl_options.rs new file mode 100644 index 0000000000..5bbc6b3e6b --- /dev/null +++ b/crates/ui-egui/src/dialogs/hpgl_options.rs @@ -0,0 +1,265 @@ +//! HP-GL Options (Export As → HP-GL): the language version, the curve tolerance, where the plot's +//! origin lies, the pens (one per color the art draws in, or a pen table of colors), and the order +//! the paths are drawn in (the nearest path next, inner paths first). +//! +//! Fields: `document.export` params (`format: hpgl`, `path?`, the artboard choice) and the HP-GL +//! options (`hpglVersion`, `curveTolerance`, `origin`, `pens`, `sortPaths`, `insideFirst`). OK +//! remembers the options for next time and writes the file (asking where when there is no path); +//! an option or artboard choice the export refuses, or a save panel shown in line that is canceled, +//! keeps the dialog open. A canceled save panel keeps the options remembered before. Opened by Export +//! Selection, it checks and writes the selection alone. A typed Curve Tolerance is kept within 0.01 +//! to 10 points. + +use serde_json::{Map, Value, json}; +use vectorcraft_cad::hpgl::write::{DEFAULT_TOLERANCE, MAX_PENS, TOLERANCE_RANGE}; +use vectorcraft_cad::hpgl::{Origin, Version}; +use vectorcraft_engine::cmd::fileio; + +use super::DialogSpec; +use super::document_setup::{LABEL, check, choice}; +use crate::state::Dialog; +use crate::{VectorcraftApp, io, widgets}; + +pub(super) const KIND: &str = "hpglOptions"; + +pub(super) const SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("HP-GL Options").into(), + body, + confirm, + ok: Some("Export"), + min_width: 420.0, + max_width: Some(460.0), + inputs: |_| &["path"], + ..DialogSpec::FORM +}; + +/// Fields that are not remembered between exports (they belong to one export). +const PER_EXPORT: [&str; 8] = ["format", "path", "useArtboards", "range", "artboard", "artboards", "selectedOnly", io::EXPORT_SELECTION]; + +/// The pen table set aside while One Pen per Color is chosen, so Pen Table shows it again. +const SET_ASIDE: &str = "__pens"; + +/// Why Pen Table could not start from the art's pens, shown under the Pens row. +const PEN_ERROR: &str = "__penError"; + +/// The Origin menu's names, in [`Origin::ALL`] order. +pub(crate) const ORIGIN_NAMES: [&str; 2] = ["Bottom Left", "Center"]; + +/// The options a first HP-GL Options dialog starts from (the export's defaults). +fn defaults() -> Map { + let mut m = Map::new(); + for (k, v) in [ + ("hpglVersion", json!(Version::default().id())), + ("curveTolerance", json!(DEFAULT_TOLERANCE)), + ("origin", json!(Origin::default().id())), + ("pens", Value::Null), + ("sortPaths", json!(false)), + ("insideFirst", json!(false)), + ] { + m.insert(k.into(), v); + } + m +} + +/// Open HP-GL Options for an export whose params (path, artboard choice, any HP-GL option) are +/// `params`, over the options used last. +pub fn open(app: &mut VectorcraftApp, params: &Value) { + let mut fields = defaults(); + for given in [&app.ui.hpgl_options, params] { + if let Some(o) = given.as_object() { + fields.extend(o.iter().map(|(k, v)| (k.clone(), v.clone()))); + } + } + fields.insert("format".into(), json!("hpgl")); + app.ui.dialog = Some(Dialog::new(KIND, Value::Object(fields))); +} + +fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + let versions: Vec<(&str, &str)> = Version::ALL.iter().map(|v| (v.id(), v.label())).collect(); + choice(ui, d, "hpglVersion", tl!("Version:"), &versions); + ui.add_space(4.0); + widgets::label_row(ui, tl!("Curve Tolerance:"), LABEL, |ui| { + let x = d.f64("curveTolerance", DEFAULT_TOLERANCE); + if let Some(v) = widgets::plain_field(ui, "hpgl-tolerance", x, " pt", 2, 80.0) { + let (lo, hi) = (*TOLERANCE_RANGE.start(), *TOLERANCE_RANGE.end()); + d.fields.insert("curveTolerance".into(), json!(v.clamp(lo, hi))); + } + }); + ui.add_space(4.0); + let origins: Vec<(&str, &str)> = Origin::ALL.iter().map(|o| o.id()).zip(ORIGIN_NAMES).collect(); + choice(ui, d, "origin", tl!("Origin:"), &origins); + ui.add_space(10.0); + pens(app, ui, d); + ui.add_space(8.0); + check(ui, d, "sortPaths", tl!("Draw the Nearest Path Next")); + check(ui, d, "insideFirst", tl!("Draw Inner Paths First")); + false +} + +/// Pens: One Pen per Color (`pens` null) or Pen Table (`pens` the colors, pen 1's first), with a +/// row per pen (its number, color and a Remove button) and Add. +fn pens(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { + let table = d.fields.get("pens").is_some_and(Value::is_array); + widgets::label_row(ui, tl!("Pens:"), LABEL, |ui| { + if widgets::radio(ui, tl!("One Pen per Color"), !table, true) { + let _ = set_pen_table(d, false, || Ok(Vec::new())); + d.fields.remove(PEN_ERROR); + } + ui.add_space(12.0); + if widgets::radio(ui, tl!("Pen Table"), table, true) { + let shown = d.clone(); + match set_pen_table(d, true, || automatic_pens(app, &shown)) { + Ok(()) => d.fields.remove(PEN_ERROR), + Err(e) => d.fields.insert(PEN_ERROR.into(), json!(e)), + }; + } + }); + if let Some(e) = d.fields.get(PEN_ERROR).and_then(Value::as_str) { + let t = crate::theme::Tokens::get(ui.ctx()); + ui.label(egui::RichText::new(crate::i18n::message(crate::i18n::current(), e)).color(t.error)); + } + // The table as the radio buttons left it, so a row edit committed this frame can't undo a switch. + // A table longer than a plot takes (set through `ui.dialog.set`) draws no rows: OK refuses it. + let Some(mut list) = d.fields.get("pens").and_then(Value::as_array).filter(|a| a.len() <= MAX_PENS).cloned() else { return }; + let t = crate::theme::Tokens::get(ui.ctx()); + let n = list.len(); + let (mut changed, mut remove) = (false, None); + egui::ScrollArea::vertical().id_salt("hpgl-pens").max_height(180.0).auto_shrink([false, true]).show(ui, |ui| { + for (i, v) in list.iter_mut().enumerate() { + ui.horizontal(|ui| { + ui.add_space(LABEL + 8.0); + ui.add_sized([28.0, 18.0], egui::Label::new(egui::RichText::new((i + 1).to_string()).color(t.text))); + let hex = v.as_str().and_then(|s| s.strip_prefix('#')).unwrap_or_default().to_string(); + let (rect, _) = ui.allocate_exact_size(egui::vec2(20.0, 18.0), egui::Sense::hover()); + if let Some([r, g, b]) = rgb(&hex) { + ui.painter().rect_filled(rect, 2.0, egui::Color32::from_rgb(r, g, b)); + } + ui.painter().rect_stroke(rect, 2.0, egui::Stroke::new(1.0, t.input_border), egui::StrokeKind::Inside); + if let Some(typed) = widgets::hex_field(ui, ("hpgl-pen", i), &hex) + && let Some(color) = pen_color(&typed) + { + *v = json!(color); + changed = true; + } + if widgets::icon_button_enabled(ui, "x", tl!("Remove"), false, n > 1, 22.0).clicked() { + remove = Some(i); + } + }); + } + }); + ui.horizontal(|ui| { + ui.add_space(LABEL + 8.0); + if ui.add_enabled(n < MAX_PENS, |ui: &mut egui::Ui| widgets::flat_button(ui, tl!("Add"), 60.0)).clicked() { + // A new pen starts as the last one's color, ready to be changed. + list.push(list.last().cloned().unwrap_or_else(|| json!("#000000"))); + changed = true; + } + }); + if let Some(i) = remove.filter(|_| list.len() > 1) { + list.remove(i); + changed = true; + } + if changed { + d.fields.insert("pens".into(), Value::Array(list)); + } +} + +/// The pens an export from dialog `d` with no pen table would get: its options, artboard choice and +/// source art (the selection with Export Selected Art Only, or when Export Selection opened `d`); +/// an error when there is no document or the export refuses those. +pub(super) fn automatic_pens(app: &VectorcraftApp, d: &Dialog) -> Result, String> { + let st = app.session.active().ok_or("no document")?; + let (doc, params) = source(st, d)?; + fileio::hpgl::automatic_pens(&doc, ¶ms) +} + +/// The document an export from dialog `d` writes and the export params it reads, as +/// [`io::export`] takes them ([`io::take_selection`]): with Export Selection the selection alone, +/// without the artboard choice, else the whole document or, with Export Selected Art Only, its +/// selected objects. +fn source<'a>(st: &'a vectorcraft_engine::DocState, d: &Dialog) -> Result<(std::borrow::Cow<'a, vectorcraft_doc::Document>, Value), String> { + let (selection, params) = io::take_selection(&super::export_as::exported(d, super::form::params(d)))?; + if !selection { + let doc = fileio::export_source(st, ¶ms).map_err(|e| e.to_string())?; + return Ok((doc, params)); + } + let (doc, _) = fileio::selection_doc(st, "document.exportSelection", false).map_err(|e| e.to_string())?; + Ok((std::borrow::Cow::Owned(doc), params)) +} + +/// Choose Pen Table (`on`) or One Pen per Color. Pen Table shows the table set aside when One Pen +/// per Color was chosen, else the pens the export would give the art (`automatic`), else one black +/// pen when that art draws nothing; when `automatic` fails the dialog is left as it was and the +/// error returned. One Pen per Color sets the table aside. +pub(super) fn set_pen_table(d: &mut Dialog, on: bool, automatic: impl FnOnce() -> Result, String>) -> Result<(), String> { + let table = d.fields.get("pens").filter(|v| v.is_array()).cloned(); + match (on, table) { + (true, None) => { + let kept = d.fields.get(SET_ASIDE).filter(|v| v.as_array().is_some_and(|a| !a.is_empty())).cloned(); + let list = match kept { + Some(list) => list, + None => { + let mut pens = automatic()?; + pens.truncate(MAX_PENS); + if pens.is_empty() { + pens.push("#000000".into()); + } + json!(pens) + } + }; + d.fields.remove(SET_ASIDE); + d.fields.insert("pens".into(), list); + } + (false, Some(list)) => { + d.fields.insert(SET_ASIDE.into(), list); + d.fields.insert("pens".into(), Value::Null); + } + _ => {} + } + Ok(()) +} + +/// A typed pen color (`ff0000` or `#FF0000`) as the table holds it, `#ff0000`; `None` unless it is +/// six hex digits. +fn pen_color(typed: &str) -> Option { + let s = typed.trim(); + let s = s.strip_prefix('#').unwrap_or(s); + rgb(s).map(|_| format!("#{}", s.to_ascii_lowercase())) +} + +/// Six hex digits as a color. +fn rgb(hex: &str) -> Option<[u8; 3]> { + if hex.len() != 6 || !hex.bytes().all(|b| b.is_ascii_hexdigit()) { + return None; + } + let byte = |i: usize| hex.get(i..i + 2).and_then(|h| u8::from_str_radix(h, 16).ok()); + Some([byte(0)?, byte(2)?, byte(4)?]) +} + +/// Check the options, remember them, and write the file(s). +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let params = super::form::params(d); + let st = app.session.active().ok_or("no document")?; + // A bad option or artboard choice, nothing selected, or no art to export keeps the dialog open. + let (source, checked) = source(st, d)?; + fileio::hpgl::check(&source, &checked)?; + let remembered = params.as_object().map(|o| o.iter().filter(|(k, _)| !PER_EXPORT.contains(&k.as_str())).map(|(k, v)| (k.clone(), v.clone()))); + let before = std::mem::replace(&mut app.ui.hpgl_options, Value::Object(remembered.into_iter().flatten().collect())); + app.ui.dialog = None; + let path = d.fields.get("path").and_then(Value::as_str).map(str::to_string); + let waiting = app.picks.is_waiting(); + let r = io::export(app, Some("hpgl"), path, &super::export_as::exported(d, params)); + if !waiting && app.picks.is_waiting() { + // A save panel shown off the UI thread confirms the dialog again when it answers, which + // remembers the options then; until it does, and when it is canceled, the options + // remembered before stay. + app.ui.hpgl_options = before; + } else if r.is_err() && app.ui.dialog.is_none() { + // An export that stops before writing (a save panel that was canceled or could not be + // shown) leaves the dialog open over the options remembered before. A question that a + // save panel asked stays open. + app.ui.hpgl_options = before; + app.ui.dialog = Some(d.clone()); + } + r +} diff --git a/crates/ui-egui/src/dialogs/import_pdf.rs b/crates/ui-egui/src/dialogs/import_pdf.rs index bedd3387c2..5be31baebd 100644 --- a/crates/ui-egui/src/dialogs/import_pdf.rs +++ b/crates/ui-egui/src/dialogs/import_pdf.rs @@ -297,7 +297,11 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { }; match r { Ok(()) => { - app.ui.dialog = None; + // Opening may have asked something else (the profile of the document); only this + // dialog closes. + if app.ui.dialog.as_ref().is_some_and(|x| x.kind == KIND) { + app.ui.dialog = None; + } Ok(Value::Null) } Err(e) => { diff --git a/crates/ui-egui/src/dialogs/kinsoku_sets.rs b/crates/ui-egui/src/dialogs/kinsoku_sets.rs new file mode 100644 index 0000000000..2f67d199ab --- /dev/null +++ b/crates/ui-egui/src/dialogs/kinsoku_sets.rs @@ -0,0 +1,361 @@ +//! Type › Kinsoku Shori Settings… (with Show East Asian Options): the active document's custom +//! Kinsoku Shori sets, the one picked in Kinsoku shown with its four categories: Cannot Start Line, +//! Cannot End Line, Hanging Punctuation and Inseparable Characters. New adds a set based on Hard, +//! Soft, None or a set of the dialog, Delete takes the one picked out, and Add puts the character +//! of a Unicode code point into a category. Nothing changes in the document until OK, +//! which runs `type.kinsokuSets.set` with every set as one undo step; Cancel leaves them as they were. +//! +//! Fields: `__doc` (the uid of the document the dialog opened on, which OK sets the sets of), +//! `__opened` (the names of that document's sets when the dialog opened; OK keeps the sets the +//! document gained since, after the dialog's own), `sets` (the sets as `type.kinsokuSets.set` takes them, each with the name it had in the +//! document as `from`), `selected` (the index of the one picked), `name`, `cannotStart`, +//! `cannotEnd`, `hanging` and `inseparable` (its name and categories as typed, the inseparable +//! sequences separated by spaces), `base` (what New starts from), `code` (the code point Add +//! adds), `into` (the category it adds to) and `shown` (the set the name and category fields +//! were filled from). When `sets` or `selected` is changed so the picked set is no longer `shown`, +//! the fields are filled from the picked set again and what was typed in them is dropped. +//! +//! Behavior reference: the help page +//! . + +use serde_json::{Map, Value, json}; +use vectorcraft_doc::KinsokuSet; + +use super::{DialogSpec, form}; +use crate::state::Dialog; +use crate::{VectorcraftApp, widgets}; + +/// The dialog kind of Kinsoku Shori Settings. +pub const KIND: &str = "kinsokuSets"; + +/// The command OK runs, and the menu item's. +pub const COMMAND: &str = vectorcraft_engine::cmd::kinsokusets::SET; + +/// The field that holds the uid of the document whose sets the dialog shows (`ui.dialog.set` +/// refuses `__` fields). +const DOC: &str = "__doc"; + +/// The field that holds the names of the document's sets when the dialog opened: OK keeps the +/// sets the document gained since, which the dialog does not list. +const OPENED: &str = "__opened"; + +/// The categories, as the command's keys, in the order the dialog shows them. +const CATEGORIES: [&str; 4] = ["cannotStart", "cannotEnd", "hanging", "inseparable"]; + +pub(super) const SPEC: DialogSpec = + DialogSpec { heading: |_| tl!("Kinsoku Shori Settings").into(), body, confirm, min_width: 560.0, ..DialogSpec::FORM }; + +/// Open Kinsoku Shori Settings on the active document's custom sets, the first one picked. +pub fn open(app: &mut VectorcraftApp) -> Result { + let st = app.session.active().ok_or("no document open")?; + let uid = st.uid; + let sets: Vec = st.doc.kinsoku_sets.iter().map(listed).collect(); + let opened: Vec<&str> = st.doc.kinsoku_sets.iter().map(|k| k.name.as_str()).collect(); + let mut d = + Dialog::new(KIND, json!({ DOC: uid, OPENED: opened, "sets": sets, "selected": 0, "base": "hard", "into": "cannotStart", "code": "" })); + show_selected(&mut d); + app.ui.dialog = Some(d); + Ok(Value::Null) +} + +/// A set of the document as the dialog lists it: as `type.kinsokuSets.set` takes it, with its name +/// in the document as `from`. +fn listed(k: &KinsokuSet) -> Value { + let mut v = json!(k); + if let Some(o) = v.as_object_mut() { + o.insert("from".into(), json!(k.name)); + } + v +} + +/// The sets the dialog holds, as the command takes them. +fn sets(d: &Dialog) -> Vec> { + d.fields.get("sets").and_then(Value::as_array).map(|a| a.iter().filter_map(|v| v.as_object().cloned()).collect()).unwrap_or_default() +} + +/// Is the `sets` field a list of sets? One that is not (set with `ui.dialog.set`) is kept as it is: +/// no frame or button replaces it, and OK sends it to the command, which refuses it. +fn holds_sets(d: &Dialog) -> bool { + d.fields.get("sets").and_then(Value::as_array).is_some_and(|a| a.iter().all(Value::is_object)) +} + +fn put_sets(d: &mut Dialog, sets: &[Map]) { + d.fields.insert("sets".into(), json!(sets)); +} + +fn name_of(set: &Map) -> &str { + set.get("name").and_then(Value::as_str).unwrap_or_default() +} + +/// The index of the set picked, within the sets (0 when there are none). +fn selected(d: &Dialog, count: usize) -> usize { + d.fields.get("selected").and_then(Value::as_u64).map_or(0, |i| i as usize).min(count.saturating_sub(1)) +} + +/// Pick set `i`: its name and categories go into the fields. +fn select(d: &mut Dialog, i: usize) { + d.fields.insert("selected".into(), json!(i)); + show_selected(d); +} + +fn show_selected(d: &mut Dialog) { + let list = sets(d); + let set = list.get(selected(d, list.len())).cloned().unwrap_or_default(); + d.fields.insert("name".into(), json!(name_of(&set))); + for key in CATEGORIES { + let text = match set.get(key) { + Some(Value::Array(seqs)) => seqs.iter().filter_map(Value::as_str).collect::>().join(" "), + Some(Value::String(s)) => s.clone(), + _ => String::new(), + }; + d.fields.insert(key.into(), json!(text)); + } + d.fields.insert("shown".into(), Value::Object(set)); +} + +/// Do the name and category fields describe the set picked, `set`? +fn shows(d: &Dialog, set: &Map) -> bool { + d.fields.get("shown").and_then(Value::as_object) == Some(set) +} + +/// The set picked with the name and categories as typed: space characters are left out of the +/// single-character categories, and the inseparable sequences are the words of their field. +fn take_fields(d: &Dialog, set: &mut Map) { + set.insert("name".into(), json!(d.str("name"))); + for key in CATEGORIES { + let text = d.str(key); + let v = if key == "inseparable" { + json!(text.split_whitespace().collect::>()) + } else { + json!(text.chars().filter(|c| !c.is_whitespace()).collect::()) + }; + set.insert(key.into(), v); + } +} + +/// "Kinsoku Set N", the first N that no set in `sets` and no set of the document (`doc`) is named. +/// A set Delete took out keeps its name out of New's, so OK gives its paragraphs Hard instead of +/// the new set's characters. +fn new_name(sets: &[Map], doc: &[KinsokuSet]) -> String { + let taken = |n: &str| sets.iter().any(|s| KinsokuSet::same_name(name_of(s), n)) || doc.iter().any(|k| KinsokuSet::same_name(&k.name, n)); + (1..).map(|n| format!("Kinsoku Set {n}")).find(|n| !taken(n)).unwrap_or_default() +} + +/// The character `code` names: `U+3001`, `u+3001` or `3001`, in hexadecimal. +fn code_char(code: &str) -> Option { + let t = code.trim(); + let hex = t.strip_prefix("U+").or_else(|| t.strip_prefix("u+")).unwrap_or(t); + u32::from_str_radix(hex, 16).ok().and_then(char::from_u32).filter(|c| !c.is_control() && !c.is_whitespace()) +} + +/// What a button asked for, done once the fields are drawn. +enum Action { + New, + Delete, + Add, +} + +/// New's starting points: the built-in sets, then the dialog's own. +fn bases(list: &[Map]) -> Vec<(String, String)> { + let mut v = vec![ + (tl!("Hard").to_string(), "hard".to_string()), + (tl!("Soft").to_string(), "soft".to_string()), + (tl!("None").to_string(), "none".to_string()), + ]; + v.extend(list.iter().map(|s| (name_of(s).to_string(), name_of(s).to_string()))); + v +} + +fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + let mut list = sets(d); + let i = selected(d, list.len()); + if list.get(i).is_some_and(|set| !shows(d, set)) { + show_selected(d); + } + let mut act = None; + let mut picked = None; + let names: Vec = list.iter().map(|s| name_of(s).to_string()).collect(); + let names: Vec<&str> = names.iter().map(String::as_str).collect(); + let bases = bases(&list); + ui.horizontal(|ui| { + widgets::dim_label(ui, tl!("Kinsoku Set")); + if names.is_empty() { + widgets::dim_label(ui, tl!("None")); + } else if let Some(k) = widgets::dropdown_names(ui, "kinsoku-sets-set", names.get(i).copied().unwrap_or_default(), &names, 200.0) { + picked = Some(k); + } + ui.add_space(8.0); + ui.spacing_mut().item_spacing.x = 4.0; + if widgets::flat_button(ui, tl!("New"), 48.0).clicked() { + act = Some(Action::New); + } + widgets::dim_label(ui, tl!("Based on:")); + let base = d.str("base"); + let shown = bases.iter().find(|b| b.1 == base).map_or(base.as_str(), |b| b.0.as_str()); + let base_names: Vec<&str> = bases.iter().map(|b| b.0.as_str()).collect(); + if let Some(k) = widgets::dropdown_names(ui, "kinsoku-sets-base", shown, &base_names, 120.0) + && let Some(b) = bases.get(k) + { + d.fields.insert("base".into(), json!(b.1)); + } + if ui.add_enabled_ui(!list.is_empty(), |ui| widgets::flat_button(ui, tl!("Delete"), 56.0)).inner.clicked() { + act = Some(Action::Delete); + } + }); + if let Some(k) = picked { + select(d, k); + return false; + } + ui.add_space(8.0); + if let Some(set) = list.get_mut(i) { + egui::Grid::new("kinsoku-sets-fields").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| { + widgets::dim_label(ui, tl!("Name:")); + form::text(ui, d, "name", 260.0); + ui.end_row(); + for (key, label) in [ + ("cannotStart", tl!("Cannot Start Line")), + ("cannotEnd", tl!("Cannot End Line")), + ("hanging", tl!("Hanging Punctuation")), + ("inseparable", tl!("Inseparable Characters")), + ] { + widgets::dim_label(ui, label); + form::text_area(ui, d, key, 380.0, 2); + ui.end_row(); + } + }); + ui.add_space(8.0); + ui.horizontal(|ui| { + widgets::dim_label(ui, tl!("Unicode")); + form::text(ui, d, "code", 80.0); + let into = d.str("into"); + let targets = [("cannotStart", tl!("Cannot Start Line")), ("cannotEnd", tl!("Cannot End Line")), ("hanging", tl!("Hanging Punctuation"))]; + let shown = targets.iter().find(|t| t.0 == into).map_or("", |t| t.1); + if let Some(k) = widgets::dropdown_names(ui, "kinsoku-sets-into", shown, &targets.map(|t| t.1), 160.0) + && let Some(t) = targets.get(k) + { + d.fields.insert("into".into(), json!(t.0)); + } + if ui.add_enabled_ui(code_char(&d.str("code")).is_some(), |ui| widgets::flat_button(ui, tl!("Add"), 48.0)).inner.clicked() { + act = Some(Action::Add); + } + }); + let was = name_of(set).to_string(); + take_fields(d, set); + // Based on follows the set it names through a rename. + if d.str("base") == was && name_of(set) != was { + let now = name_of(set).to_string(); + d.fields.insert("base".into(), json!(now)); + } + d.fields.insert("shown".into(), Value::Object(set.clone())); + } + if holds_sets(d) { + put_sets(d, &list); + } + if let Some(a) = act + && let Err(e) = run(app, d, a) + { + app.status(e); + } + false +} + +/// Do what button `act` asks for on the dialog's sets. +fn run(app: &mut VectorcraftApp, d: &mut Dialog, act: Action) -> Result<(), String> { + if !holds_sets(d) { + return Err("the sets must be a list of Kinsoku sets".into()); + } + let mut list = sets(d); + let i = selected(d, list.len()); + match act { + Action::New => { + let base = d.str("base"); + let mut set = match list.iter().find(|s| name_of(s) == base) { + Some(s) => s.clone(), + None => { + let r = app.run("type.kinsokuSets.base", json!({ "base": base }))?; + r["set"].as_object().cloned().ok_or("no Kinsoku set to base the new one on")? + } + }; + set.remove("from"); + let uid = d.fields.get(DOC).and_then(Value::as_u64); + let doc = app.session.documents().iter().find(|t| Some(t.uid) == uid).map(|t| t.doc.kinsoku_sets.to_vec()).unwrap_or_default(); + set.insert("name".into(), json!(new_name(&list, &doc))); + list.push(set); + put_sets(d, &list); + select(d, list.len() - 1); + } + Action::Delete => { + if i < list.len() { + let gone = name_of(&list[i]).to_string(); + list.remove(i); + if d.str("base") == gone { + d.fields.insert("base".into(), json!("hard")); + } + } + put_sets(d, &list); + select(d, i.min(list.len().saturating_sub(1))); + } + Action::Add => { + let c = code_char(&d.str("code")).ok_or("give a character's Unicode code point, as U+3001")?; + let into = d.str("into"); + let key = if CATEGORIES.contains(&into.as_str()) && into != "inseparable" { into } else { "cannotStart".into() }; + let mut text = d.str(&key); + if !text.contains(c) { + text.push(c); + } + d.fields.insert(key, json!(text)); + d.fields.insert("code".into(), json!("")); + if let Some(set) = list.get_mut(i) { + take_fields(d, set); + d.fields.insert("shown".into(), Value::Object(set.clone())); + } + put_sets(d, &list); + } + } + Ok(()) +} + +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + // The fields as typed, also when they were set (`ui.dialog.set`) with no frame drawn since, + // while they still describe the set picked. + let mut list = sets(d); + let i = selected(d, list.len()); + if let Some(set) = list.get_mut(i) + && shows(d, set) + { + take_fields(d, set); + } + // The sets go to the document the dialog opened on, also when another tab is active by now; a + // document closed since closes the dialog and changes nothing. + let uid = d.fields.get(DOC).and_then(Value::as_u64); + if app.session.active().map(|st| st.uid) != uid { + let Some(index) = app.session.documents().iter().position(|doc| Some(doc.uid) == uid) else { + app.ui.dialog = None; + return Err("that document is no longer open".into()); + }; + app.run("document.activate", json!({ "index": index }))?; + } + // A `sets` field that is not a list of sets goes to the command as it is, which refuses it. + let sets = if holds_sets(d) { + // A set the document gained while the dialog was open (a script, another command) is + // kept, after the dialog's sets. + let opened: Vec<&str> = + d.fields.get(OPENED).and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).collect()).unwrap_or_default(); + if let Some(st) = app.session.active() { + list.extend(st.doc.kinsoku_sets.iter().filter(|k| !opened.contains(&k.name.as_str())).filter_map(|k| listed(k).as_object().cloned())); + } + json!(list) + } else { + d.fields.get("sets").cloned().unwrap_or(Value::Null) + }; + let r = app.run(COMMAND, json!({ "sets": sets })); + // A name two sets share, a reserved name or a category too long keeps the dialog open to be + // changed, with its document active. + if r.is_ok() { + app.ui.dialog = None; + } + r +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/dialogs/kinsoku_sets/tests.rs b/crates/ui-egui/src/dialogs/kinsoku_sets/tests.rs new file mode 100644 index 0000000000..1b3ddd9520 --- /dev/null +++ b/crates/ui-egui/src/dialogs/kinsoku_sets/tests.rs @@ -0,0 +1,308 @@ +use serde_json::json; +use vectorcraft_engine::Session; + +use super::*; + +fn app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + app +} + +fn frame(app: &mut VectorcraftApp) { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| super::super::show(app, ui.ctx())); + out.textures_delta.clear(); +} + +fn dialog(app: &mut VectorcraftApp) -> &mut Dialog { + app.ui.dialog.as_mut().expect("Kinsoku Shori Settings open") +} + +fn doc_sets(app: &VectorcraftApp) -> Vec { + app.session.active().unwrap().doc.kinsoku_sets.to_vec() +} + +fn steps(app: &VectorcraftApp) -> usize { + app.session.active().unwrap().history.undo.len() +} + +/// Do `act` with the dialog as it is, as its button does. +fn press(app: &mut VectorcraftApp, act: Action) { + let mut d = app.ui.dialog.clone().unwrap(); + run(app, &mut d, act).unwrap(); + app.ui.dialog = Some(d); +} + +/// Type › Kinsoku Shori Settings… opens on the document's sets; New adds one based on Hard, its +/// categories edited in their fields and Add putting in a character by its code point; nothing +/// changes until OK, which sets them as one undo step; Cancel leaves them. +#[test] +fn kinsoku_sets_change_on_ok_as_one_undo_step() { + let mut app = app(); + crate::menus::invoke(&mut app, COMMAND, json!({})); + assert_eq!(dialog(&mut app).kind, KIND); + frame(&mut app); + press(&mut app, Action::New); + frame(&mut app); + let d = dialog(&mut app); + assert_eq!(d.str("name"), "Kinsoku Set 1"); + assert!(d.str("cannotStart").contains('ー'), "based on Hard"); + d.fields.insert("name".into(), json!("UI Tight")); + d.fields.insert("cannotEnd".into(), json!("「 (")); + d.fields.insert("inseparable".into(), json!("あい ——")); + d.fields.insert("code".into(), json!("U+FF5D")); + d.fields.insert("into".into(), json!("cannotEnd")); + frame(&mut app); + press(&mut app, Action::Add); + assert_eq!(dialog(&mut app).str("cannotEnd"), "「 (}"); + frame(&mut app); + assert!(doc_sets(&app).is_empty()); + let before = steps(&app); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + let sets = doc_sets(&app); + assert_eq!(sets.len(), 1); + assert_eq!((sets[0].name.as_str(), sets[0].cannot_end.clone()), ("UI Tight", vec!['「', '(', '}'])); + assert_eq!(sets[0].inseparable, ["——", "あい"]); + assert_eq!(steps(&app), before + 1); + // OK with nothing changed adds no step; Cancel leaves the sets. + open(&mut app).unwrap(); + frame(&mut app); + super::super::confirm(&mut app).unwrap(); + assert_eq!(steps(&app), before + 1); + open(&mut app).unwrap(); + press(&mut app, Action::Delete); + super::super::cancel(&mut app); + assert_eq!(doc_sets(&app).len(), 1); + // Renamed in the dialog, the set keeps its paragraphs; Delete and OK takes it out. + let id = app.run("text.create", json!({"x": 10, "y": 50, "text": "あいう"})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + app.run("text.setFormat", json!({"kinsoku": "UI Tight"})).unwrap(); + open(&mut app).unwrap(); + dialog(&mut app).fields.insert("name".into(), json!("UI Strict")); + frame(&mut app); + super::super::confirm(&mut app).unwrap(); + let para = |app: &VectorcraftApp| match &app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().kind { + vectorcraft_doc::NodeKind::Text(t) => t.para_at(0).clone(), + _ => panic!("not text"), + }; + assert_eq!(para(&app).kinsoku_name(), "UI Strict"); + open(&mut app).unwrap(); + press(&mut app, Action::Delete); + assert_eq!(dialog(&mut app).str("name"), ""); + frame(&mut app); + super::super::confirm(&mut app).unwrap(); + assert!(doc_sets(&app).is_empty()); + assert_eq!(para(&app).kinsoku_name(), "Hard"); +} + +/// New is based on the choice in Based on, the dialog's own sets included, and takes the next free +/// name; a name two sets share, a built-in name or one left empty keeps the dialog open and changes +/// nothing. +#[test] +fn shared_reserved_or_empty_names_keep_the_dialog_open() { + let mut app = app(); + open(&mut app).unwrap(); + dialog(&mut app).fields.insert("base".into(), json!("none")); + press(&mut app, Action::New); + assert_eq!(dialog(&mut app).str("cannotStart"), ""); + dialog(&mut app).fields.insert("cannotStart".into(), json!("ゝ")); + frame(&mut app); + dialog(&mut app).fields.insert("base".into(), json!("Kinsoku Set 1")); + press(&mut app, Action::New); + let d = dialog(&mut app); + assert_eq!((d.str("name"), d.str("cannotStart")), ("Kinsoku Set 2".to_string(), "ゝ".to_string())); + for bad in ["kinsoku set 1", " ", "Soft"] { + dialog(&mut app).fields.insert("name".into(), json!(bad)); + frame(&mut app); + assert!(super::super::confirm(&mut app).is_err(), "{bad:?}"); + assert!(app.ui.dialog.is_some()); + assert!(doc_sets(&app).is_empty()); + } + dialog(&mut app).fields.insert("name".into(), json!("UI Loose")); + frame(&mut app); + super::super::confirm(&mut app).unwrap(); + assert_eq!(doc_sets(&app).iter().map(|k| k.name.as_str()).collect::>(), ["Kinsoku Set 1", "UI Loose"]); +} + +/// Based on follows a set of the dialog through a rename, so New starts from that set's +/// characters as edited, not from the document's copy under its old name. +#[test] +fn based_on_follows_a_renamed_set() { + let mut app = app(); + app.run("type.kinsokuSets.set", json!({"sets": [{"name": "Doc Set", "cannotStart": "ゝ"}]})).unwrap(); + open(&mut app).unwrap(); + dialog(&mut app).fields.insert("base".into(), json!("Doc Set")); + frame(&mut app); + let d = dialog(&mut app); + d.fields.insert("cannotStart".into(), json!("ゞ")); + d.fields.insert("name".into(), json!("Renamed")); + frame(&mut app); + assert_eq!(dialog(&mut app).str("base"), "Renamed"); + press(&mut app, Action::New); + let d = dialog(&mut app); + assert_eq!((d.str("name"), d.str("cannotStart")), ("Kinsoku Set 1".to_string(), "ゞ".to_string())); +} + +/// Delete then New does not give the new set the deleted set's name, so on OK the deleted set's +/// paragraphs take Hard rather than the new set's characters. +#[test] +fn new_after_delete_does_not_take_the_deleted_name() { + let mut app = app(); + app.run("type.kinsokuSets.set", json!({"sets": [{"name": "Kinsoku Set 1", "cannotStart": "ゝ"}]})).unwrap(); + let id = app.run("text.create", json!({"x": 10, "y": 50, "text": "あいう"})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + app.run("text.setFormat", json!({"kinsoku": "Kinsoku Set 1"})).unwrap(); + open(&mut app).unwrap(); + frame(&mut app); + press(&mut app, Action::Delete); + dialog(&mut app).fields.insert("base".into(), json!("none")); + frame(&mut app); + press(&mut app, Action::New); + assert_eq!(dialog(&mut app).str("name"), "Kinsoku Set 2"); + frame(&mut app); + super::super::confirm(&mut app).unwrap(); + assert_eq!(doc_sets(&app).iter().map(|k| k.name.as_str()).collect::>(), ["Kinsoku Set 2"]); + let para = match &app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().kind { + vectorcraft_doc::NodeKind::Text(t) => t.para_at(0).clone(), + _ => panic!("not text"), + }; + assert_eq!(para.kinsoku_name(), "Hard"); +} + +/// OK takes the fields as they are set (`ui.dialog.set`) even when no frame was drawn since. Once +/// `selected` picks another set, the fields no longer describe it: OK leaves that set as it is, +/// and the next frame fills the fields from it. +#[test] +fn ok_takes_fields_set_without_a_frame() { + let mut app = app(); + let doc = json!([{"name": "Doc Set", "cannotStart": "ゝ"}, {"name": "Other", "cannotStart": "ー"}]); + app.run("type.kinsokuSets.set", json!({ "sets": doc })).unwrap(); + open(&mut app).unwrap(); + let d = dialog(&mut app); + d.fields.insert("name".into(), json!("Scripted")); + d.fields.insert("cannotStart".into(), json!("ゞ")); + super::super::confirm(&mut app).unwrap(); + let sets = doc_sets(&app); + assert_eq!((sets[0].name.as_str(), sets[0].cannot_start.clone()), ("Scripted", vec!['ゞ'])); + + let before = steps(&app); + open(&mut app).unwrap(); + let d = dialog(&mut app); + d.fields.insert("selected".into(), json!(1)); + d.fields.insert("cannotStart".into(), json!("ゝ")); + let pending = app.ui.dialog.clone().unwrap(); + super::super::confirm(&mut app).unwrap(); + assert_eq!(steps(&app), before, "the fields of the set shown before do not go into the one picked"); + assert_eq!(doc_sets(&app)[1].name, "Other"); + app.ui.dialog = Some(pending); + frame(&mut app); + let d = dialog(&mut app); + assert_eq!((d.str("name"), d.str("cannotStart")), ("Other".to_string(), "ー".to_string())); +} + +/// OK sets the sets of the document the dialog opened on, also when another document became the +/// active one while it was open; with that document closed, OK closes the dialog and changes no +/// document's sets. +#[test] +fn ok_sets_the_document_the_dialog_opened_on() { + let mut app = app(); + let first = app.session.active().unwrap().uid; + app.run("type.kinsokuSets.set", json!({ "sets": [{"name": "First", "cannotStart": "ゝ"}] })).unwrap(); + open(&mut app).unwrap(); + assert!(!super::super::accepts_field(dialog(&mut app), DOC), "`ui.dialog.set` cannot change the document"); + dialog(&mut app).fields.insert("name".into(), json!("Soft")); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let other = app.session.active().unwrap().uid; + assert_ne!(other, first); + // A name OK refuses keeps the dialog open on its document, now the active one. + assert!(super::super::confirm(&mut app).is_err()); + assert!(app.ui.dialog.is_some()); + assert_eq!(app.session.active().unwrap().uid, first); + assert_eq!(doc_sets(&app)[0].name, "First"); + app.run("document.activate", json!({ "index": app.session.documents().iter().position(|d| d.uid == other).unwrap() })).unwrap(); + dialog(&mut app).fields.insert("name".into(), json!("Kinsoku Set 1")); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.active().unwrap().uid, first); + assert_eq!(doc_sets(&app)[0].name, "Kinsoku Set 1"); + let second = app.session.documents().iter().find(|d| d.uid != first).unwrap(); + assert!(second.doc.kinsoku_sets.is_empty(), "the other document keeps its sets"); + + // New skips the names of the dialog's document's sets, not of the active document's. + open(&mut app).unwrap(); + press(&mut app, Action::Delete); + app.run("document.activate", json!({ "index": app.session.documents().iter().position(|d| d.uid == other).unwrap() })).unwrap(); + press(&mut app, Action::New); + assert_eq!(dialog(&mut app).str("name"), "Kinsoku Set 2"); + let i = app.session.documents().iter().position(|d| d.uid == first).unwrap(); + app.session.execute("file.close", &json!({ "index": i })).unwrap(); + assert!(super::super::confirm(&mut app).is_err()); + assert!(app.ui.dialog.is_none()); + assert!(app.session.documents().iter().all(|d| d.doc.kinsoku_sets.is_empty())); +} + +/// OK keeps a set the document gained while the dialog was open, after the dialog's sets, and a +/// set deleted in the dialog stays deleted. A `sets` field that is not a list of sets keeps the +/// dialog open and leaves the document's sets as they are, also when a frame is drawn before OK, +/// and New refuses to start from it. +#[test] +fn ok_keeps_sets_added_while_open_and_refuses_malformed_sets() { + let mut app = app(); + app.run("type.kinsokuSets.set", json!({ "sets": [{"name": "First", "cannotStart": "ゝ"}] })).unwrap(); + open(&mut app).unwrap(); + let both = json!([{"name": "First", "cannotStart": "ゝ"}, {"name": "Later", "cannotStart": "ー"}]); + app.run("type.kinsokuSets.set", json!({ "sets": both })).unwrap(); + dialog(&mut app).fields.insert("cannotStart".into(), json!("ゞ")); + super::super::confirm(&mut app).unwrap(); + let sets = doc_sets(&app); + let named = sets.iter().map(|k| (k.name.as_str(), k.cannot_start.clone())).collect::>(); + assert_eq!(named, [("First", vec!['ゞ']), ("Later", vec!['ー'])]); + open(&mut app).unwrap(); + press(&mut app, Action::Delete); + super::super::confirm(&mut app).unwrap(); + let names = |app: &VectorcraftApp| doc_sets(app).iter().map(|k| k.name.clone()).collect::>(); + assert_eq!(names(&app), ["Later"]); + for bad in [Value::Null, json!({}), json!("Later"), json!([1]), json!([{"name": "Later", "cannotStart": "ー"}, 1])] { + for drawn in [false, true] { + open(&mut app).unwrap(); + dialog(&mut app).fields.insert("sets".into(), bad.clone()); + if drawn { + frame(&mut app); + assert_eq!(dialog(&mut app).fields.get("sets"), Some(&bad), "a frame keeps {bad} as it is"); + let mut d = app.ui.dialog.clone().unwrap(); + assert!(run(&mut app, &mut d, Action::New).is_err(), "{bad}"); + assert_eq!(d.fields.get("sets"), Some(&bad), "New keeps {bad} as it is"); + } + assert!(super::super::confirm(&mut app).is_err(), "{bad} drawn: {drawn}"); + assert!(app.ui.dialog.is_some(), "{bad} drawn: {drawn}"); + assert_eq!(names(&app), ["Later"], "{bad} drawn: {drawn}"); + } + } +} + +/// Add takes a code point as U+XXXX, u+xxxx or bare hexadecimal, and never a control or space +/// character or a value that is no character. +#[test] +fn add_reads_unicode_code_points() { + assert_eq!(code_char("U+3001"), Some('、')); + assert_eq!(code_char(" u+ff5d "), Some('}')); + assert_eq!(code_char("300c"), Some('「')); + for bad in ["", "U+", "U+0007", "U+0020", "U+D800", "U+110000", "zz"] { + assert_eq!(code_char(bad), None, "{bad:?}"); + } +} + +/// The menu item shows only with Show East Asian Options on, and needs a document. +#[test] +fn the_menu_item_shows_with_east_asian_options() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.prefs.show_east_asian_options = true; + assert_eq!(crate::menus::shown_state(&app, COMMAND, &json!({})).map(|s| s.0), Some(false)); + app.run("file.new", json!({})).unwrap(); + assert_eq!(crate::menus::shown_state(&app, COMMAND, &json!({})).map(|s| s.0), Some(true)); + app.session.prefs.show_east_asian_options = false; + assert_eq!(crate::menus::shown_state(&app, COMMAND, &json!({})), None); +} diff --git a/crates/ui-egui/src/dialogs/layer_options.rs b/crates/ui-egui/src/dialogs/layer_options.rs index d40d61c6f5..ce954a32cd 100644 --- a/crates/ui-egui/src/dialogs/layer_options.rs +++ b/crates/ui-egui/src/dialogs/layer_options.rs @@ -157,9 +157,14 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { } /// `ui.newLayer {sublayer?}`: Layer Options for a new layer (or sublayer), with the name and -/// colour it would get. +/// colour it would get. In isolation mode a layer that would be outside the isolated art, where the +/// Layers panel does not list it, is an error. pub fn open_new(app: &mut VectorcraftApp, p: &Value) -> Result { let st = app.session.active().ok_or("no document open")?; + let sublayer = crate::menus::opt_bool(p, "sublayer")?.unwrap_or(false); + if crate::panels::layers::new_layer_unlisted(st, sublayer, false) { + return Err("exit isolation mode first".into()); + } let mut layers = vec![]; st.doc.walk(|n| { if n.is_layer() { @@ -170,7 +175,6 @@ pub fn open_new(app: &mut VectorcraftApp, p: &Value) -> Result { while layers.contains(&format!("Layer {i}")) { i += 1; } - let sublayer = p.get("sublayer").and_then(Value::as_bool).unwrap_or(false); let color = LayerColor::Preset((layers.len() % LAYER_COLORS.len()) as u8); let name = format!("Layer {i}"); let name = if app.session.prefs.identify_objects_by == "xmlId" { vectorcraft_doc::xml_id::from_object_name(&name) } else { name }; @@ -325,6 +329,17 @@ pub(crate) fn params(d: &Dialog) -> (&'static str, Value) { fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { let (cmd, p) = params(d); + // Isolation mode can start while the dialog is open. + let sublayer = match cmd { + "layer.new" => Some(false), + "layer.newSublayer" => Some(true), + _ => None, + }; + if let Some(sublayer) = sublayer + && app.session.active().is_some_and(|st| crate::panels::layers::new_layer_unlisted(st, sublayer, false)) + { + return Err("exit isolation mode first".into()); + } run_and_close(app, cmd, p) } @@ -611,6 +626,23 @@ mod tests { } } + /// OK in New Layer Options makes no layer outside the isolated art when isolation mode started + /// while the dialog was open. + #[test] + fn new_layer_options_ok_checks_isolation_again() { + let mut app = app(); + let id = |v: Value| v["id"].as_u64().unwrap(); + let rect = id(app.session.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()); + app.session.execute("select.set", &json!({"ids": [rect]})).unwrap(); + let group = id(app.session.execute("object.group", &json!({})).unwrap()); + app.run("ui.newLayer", json!({})).unwrap(); + app.session.execute("object.isolate", &json!({"id": group})).unwrap(); + draw(&mut app); + let err = super::super::confirm(&mut app).unwrap_err(); + assert!(err.contains("exit isolation mode first"), "{err}"); + assert_eq!(app.session.doc().unwrap().doc.layers.len(), 1); + } + #[test] fn new_layer_options_make_a_layer_and_objects_get_name_show_and_lock() { let mut app = app(); diff --git a/crates/ui-egui/src/dialogs/profile_mismatch.rs b/crates/ui-egui/src/dialogs/profile_mismatch.rs new file mode 100644 index 0000000000..a0f447277e --- /dev/null +++ b/crates/ui-egui/src/dialogs/profile_mismatch.rs @@ -0,0 +1,427 @@ +//! The questions Edit › Color Settings' Ask boxes add (Profile Mismatches: Ask When Opening and +//! Ask When Pasting, Missing Profiles: Ask When Opening), one dialog kind each for opening and for +//! pasting. +//! +//! Opening ([`OPEN_KIND`]): a document whose color mode's profile is not the working space asks +//! whether to use that profile, convert the colors to the working space or discard the profile; one +//! with no profile asks whether to leave it, assign the working space or assign a profile. The +//! choice the policy makes is chosen first. OK opens the document as chosen; Cancel doesn't open +//! it. The file read waits in [`VectorcraftApp::pending_profile_open`]. Fields: `issue` (`mismatch` +//! | `missing`), `name` (the file's), `model` (`RGB` | `CMYK`), `profile` (the one it is tagged +//! with), `working`, `choice` (a `profileChoice` of `document.open`) and `assignProfile`. +//! +//! Pasting ([`PASTE_KIND`]): colors copied, or dragged ([`DROP`]), from a document whose profile is +//! not this document's ask whether to keep their numbers or convert them. OK runs the paste or the +//! drop with `profileMismatch`; Cancel pastes or drops nothing. Fields: `mismatches` (as +//! `clipboard.profileMismatch` lists them), `choice` (`preserveNumbers` | `convert`, or with both +//! models `{rgb, cmyk}` of those, one for each), `__command` +//! and `__params` (the paste or drop to run), and `__doc` (the uid of the document it was asked in). + +use serde_json::{Value, json}; +use vectorcraft_color::cms::{self, ProfileKind}; +use vectorcraft_engine::cmd::colormgmt::{ProfileChoice, ProfileQuestion}; +use vectorcraft_engine::cmd::fileio::{self, ReadFile}; +use vectorcraft_engine::file_access::ScopeHandle; + +use super::swatch_options::{grid, label}; +use super::{DialogResult, DialogSpec}; +use crate::state::Dialog; +use crate::{VectorcraftApp, widgets}; + +/// The dialog kind of the question opening asks. +pub const OPEN_KIND: &str = "profileMismatchOpen"; +/// The dialog kind of the question pasting asks. +pub const PASTE_KIND: &str = "profileMismatchPaste"; +/// The command a drag of artwork from another document runs, which asks as a paste does. +pub const DROP: &str = "edit.dropSelection"; + +pub(super) const OPEN_SPEC: DialogSpec = DialogSpec { + heading: |d| if d.str("issue") == "missing" { tl!("Missing Profile") } else { tl!("Embedded Profile Mismatch") }.into(), + body: open_body, + confirm: open_confirm, + min_width: 400.0, + max_width: Some(480.0), + ..DialogSpec::FORM +}; + +pub(super) const PASTE_SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("Paste Profile Mismatch").into(), + body: paste_body, + confirm: paste_confirm, + min_width: 400.0, + max_width: Some(480.0), + ..DialogSpec::FORM +}; + +/// A file read for File › Open that waits for the answer to its profile question. +pub(crate) struct PendingOpen { + file: ReadFile, + /// Where it was read from: it goes on the recent files once it opens. + path: Option, + /// The automation roots in force where the open was asked for: its linked files are read, and + /// the document is installed, under them and those of the caller that confirms. + scope: ScopeHandle, + /// It was read off the UI thread ([`crate::opening`]): the rest of its read is done there too + /// once the question is answered. An open that answers at once (a path a caller asked for) + /// finishes before OK returns. + background: bool, +} + +/// The choices of a mismatch (`missing`: of a missing profile), as (`choice`, label). +fn open_choices(missing: bool) -> [(&'static str, &'static str); 3] { + if missing { + [("leave", tl!("Leave as is")), ("assignWorking", tl!("Assign the working space")), ("assign", tl!("Assign profile:"))] + } else { + [ + ("useEmbedded", tl!("Use the embedded profile")), + ("convert", tl!("Convert the colors to the working space")), + ("discard", tl!("Discard the embedded profile")), + ] + } +} + +/// The choices pasting offers, as (`choice`, label). +fn paste_choices() -> [(&'static str, &'static str); 2] { + [("preserveNumbers", tl!("Preserve the color numbers")), ("convert", tl!("Convert to keep the colors' appearance"))] +} + +/// Open `file`, read for File › Open from `path`, as `document.open` does, unless Edit › Color +/// Settings asks about its profile ([`ReadFile::ask`]): then the dialog asks first, and the result +/// is `{dialog}`. A file read while another one's question is open waits for its own question +/// until that one is answered (`{dialog, queued: true}`). Opened, the views follow and the file +/// goes on the recent files ([`crate::io::opened`]). `background`: the file was read off the UI +/// thread, and the rest of its read after an answer is done there too. +pub fn open_or_ask(app: &mut VectorcraftApp, file: ReadFile, path: Option, background: bool) -> Result { + ask_or_open(app, PendingOpen { file, path, scope: ScopeHandle::capture(), background }) +} + +/// [`open_or_ask`] for a file that has its scope already. +fn ask_or_open(app: &mut VectorcraftApp, mut pending: PendingOpen) -> Result { + let Some(q) = pending.file.ask() else { + let PendingOpen { file, path, scope, .. } = pending; + return scope.run(|| { + let r = fileio::open_read(&mut app.session, file).map_err(|e| e.to_string())?; + crate::io::opened(app, &r); + if let Some(p) = &path { + crate::io::note_recent(app, p); + } + Ok(r) + }); + }; + if app.pending_profile_open.is_some() { + app.queued_profile_opens.push_back(pending); + return Ok(json!({ "dialog": OPEN_KIND, "queued": true })); + } + app.ui.dialog = Some(Dialog::new(OPEN_KIND, question_fields(&q, &pending.file.name()))); + app.pending_profile_open = Some(pending); + Ok(json!({ "dialog": OPEN_KIND })) +} + +/// The open dialog's fields for question `q` about the file named `name`. +fn question_fields(q: &ProfileQuestion, name: &str) -> Value { + json!({ + "issue": q.issue.id(), + "name": name, + "model": q.model_label(), + "profile": q.profile, + "working": q.working, + "choice": q.default.id(), + "assignProfile": q.working, + }) +} + +/// With no dialog open, the next file waiting for its profile question asks it, or opens as its +/// policy says when the question is gone (Color Settings changed meanwhile). A file that fails to +/// open is reported, and the next one comes. +pub(crate) fn ask_next(app: &mut VectorcraftApp) { + while app.pending_profile_open.is_none() && app.ui.dialog.is_none() { + let Some(next) = app.queued_profile_opens.pop_front() else { return }; + let name = next.file.name(); + if let Err(e) = ask_or_open(app, next) { + crate::io::report_open_error(app, &name, &e); + } + } +} + +/// The `profileChoice` the open dialog's fields give. +fn open_choice(d: &Dialog) -> Result { + let choice = d.str("choice"); + let profile = d.str("assignProfile"); + let profile = (choice == "assign").then_some(profile.as_str()); + ProfileChoice::parse(&choice, profile, "ui.dialog.confirm").map_err(|e| e.to_string()) +} + +fn open_body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + let missing = d.str("issue") == "missing"; + let (name, model, profile, working) = (d.str("name"), d.str("model"), d.str("profile"), d.str("working")); + let vars = [("name", name.as_str()), ("model", model.as_str()), ("profile", profile.as_str()), ("working", working.as_str())]; + let text = if missing { + tl!("“{name}” is not tagged with a {model} profile.") + } else { + tl!("“{name}” is tagged with the {model} profile “{profile}”, which is not the {model} working space “{working}”.") + }; + ui.label(crate::i18n::fmt(text, &vars)); + ui.add_space(10.0); + let choice = d.str("choice"); + for (value, text) in open_choices(missing) { + ui.horizontal(|ui| { + if widgets::radio(ui, text, choice == value, true) { + d.fields.insert("choice".into(), json!(value)); + } + if value == "assign" { + let kind = if model == "CMYK" { ProfileKind::Cmyk } else { ProfileKind::Rgb }; + let current = d.str("assignProfile"); + ui.add_enabled_ui(choice == "assign", |ui| { + if let Some(n) = crate::panels::separations::profile_dropdown(ui, "profile-mismatch-assign", ¤t, kind, None) { + d.fields.insert("assignProfile".into(), json!(n)); + } + }); + } + }); + } + false +} + +/// OK: open the waiting file as chosen, under the automation roots of the open and those of the +/// caller that confirms both. A choice the file refuses keeps the dialog open. When Color Settings +/// changed the question since it was asked, the dialog asks the question as it stands now instead, +/// or the file opens as its policy says when there is no question any more. The next file waiting +/// for its question asks it once no dialog is open ([`settle`]). +fn open_confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { + let choice = open_choice(d)?; + let Some(mut pending) = app.pending_profile_open.take() else { + app.ui.dialog = None; + return Ok(Value::Null); + }; + let scope = pending.scope.clone().within_current(); + if let Err(e) = scope.clone().run(|| pending.file.answer(choice)) { + // The question changed: ask it as it is now (or open by the policy when it is gone). + let now = |q: &ProfileQuestion| question_fields(q, ""); + let asked = |q: &ProfileQuestion| ["issue", "model", "profile", "working"].iter().all(|k| now(q).get(*k) == d.fields.get(*k)); + return match pending.file.ask() { + Some(q) if asked(&q) => { + app.pending_profile_open = Some(pending); + Err(e.to_string()) + } + Some(q) => { + app.ui.dialog = Some(Dialog::new(OPEN_KIND, question_fields(&q, &pending.file.name()))); + app.pending_profile_open = Some(pending); + Ok(json!({ "dialog": OPEN_KIND })) + } + None => { + app.ui.dialog = None; + open_pending(app, pending, scope) + } + }; + } + app.ui.dialog = None; + open_pending(app, pending, scope) +} + +/// Open `pending`, answered or without a question, under `scope`; a failure is reported. A file read +/// off the UI thread does the rest of its read (its linked files and type) there too +/// ([`crate::opening::finish_answered`]). +fn open_pending(app: &mut VectorcraftApp, pending: PendingOpen, scope: ScopeHandle) -> DialogResult { + let PendingOpen { file, path, background, .. } = pending; + let name = file.name(); + let file = match &path { + Some(p) if background && crate::opening::available() => match crate::opening::finish_answered(app, p, file, scope.clone()) { + Ok(r) => return Ok(r), + Err(Some(file)) => *file, + Err(None) => { + let e = "the file stopped being read (please report this bug)".to_string(); + crate::io::report_open_error(app, &name, &e); + return Err(e); + } + }, + _ => file, + }; + scope.run(|| match fileio::open_read(&mut app.session, file) { + Ok(r) => { + crate::io::opened(app, &r); + if let Some(p) = &path { + crate::io::note_recent(app, p); + } + Ok(r) + } + Err(e) => { + let e = e.to_string(); + crate::io::report_open_error(app, &name, &e); + Err(e) + } + }) +} + +/// Cancel, or the dialog closed some other way: the waiting file doesn't open. The next file waiting +/// for its question asks it once no dialog is open ([`settle`]). +pub(crate) fn cancel_open(app: &mut VectorcraftApp) { + app.pending_profile_open = None; +} + +/// A file still waiting once its dialog is gone (another dialog took its place) doesn't open; with +/// no dialog open, the next file waiting for its question asks it. +pub(crate) fn settle(app: &mut VectorcraftApp) { + if app.pending_profile_open.is_some() && !app.ui.dialog.as_ref().is_some_and(|d| d.kind == OPEN_KIND) { + app.pending_profile_open = None; + } + ask_next(app); +} + +/// Before running paste `command` (or `edit.dropSelection`, a drag from another document) with +/// `params`: when Ask When Pasting is on, `params` don't say what to do (`profileMismatch`) and the +/// pasted or dropped colors come from another profile, open the dialog instead and answer +/// `{dialog}`. +pub fn ask_paste(app: &mut VectorcraftApp, command: &str, params: &Value) -> Option { + // A null choice is no choice, as the paste commands read it. + if params.get("profileMismatch").is_some_and(|v| !v.is_null()) || !cms::working_settings().ask_mismatch_paste { + return None; + } + let mismatches = paste_mismatches(app, command, params).filter(|a| !a.is_empty())?; + let choice = first_choice(&mismatches); + let doc = app.session.active().map(|st| st.uid); + let fields = json!({ "mismatches": mismatches, "choice": choice, "__command": command, "__params": params, DOC: doc }); + // A deferred paste this dialog asked about gives way to the new one. + if app.ui.dialog.as_ref().is_some_and(|d| d.kind == PASTE_KIND) { + crate::placing::cancel_swatch_paste(app); + } + app.ui.dialog = Some(Dialog::new(PASTE_KIND, fields)); + Some(Ok(json!({ "dialog": PASTE_KIND }))) +} + +/// The models whose profiles differ for paste `command` with `params` (`clipboard.profileMismatch`): +/// a drop brings the objects it names, a paste the clipboard's, and Paste on All Artboards leaves the +/// backgrounds of copied artboards behind. `None` when they can't be listed. +fn paste_mismatches(app: &mut VectorcraftApp, command: &str, params: &Value) -> Option> { + let query = match command { + DROP => json!({ "sourceDocument": params.get("sourceDocument"), "ids": params.get("ids") }), + ALL_ARTBOARDS => json!({ "allArtboards": true }), + _ => json!({}), + }; + let found = app.session.execute("clipboard.profileMismatch", &query).ok()?; + found["mismatches"].as_array().cloned() +} + +/// Paste on All Artboards, which leaves copied artboards behind. +const ALL_ARTBOARDS: &str = "edit.pasteOnAllArtboards"; + +/// Can the colors of mismatch `m` convert (both profiles are available)? +fn convertible(m: &Value) -> bool { + m["convertible"].as_bool().unwrap_or(true) +} + +/// May the colors of mismatch `m` take `value`? Preserve Numbers always; Convert only when they can +/// convert. +fn allowed(m: &Value, value: &str) -> bool { + value != "convert" || convertible(m) +} + +/// The choice the paste question starts on: the model's policy for one model, and for both a +/// choice for each (`{rgb, cmyk}`), each starting on its model's policy. +fn first_choice(mismatches: &[Value]) -> Value { + let default = |m: &Value| m["default"].as_str().unwrap_or("preserveNumbers").to_string(); + match mismatches { + [m] => json!(default(m)), + _ => Value::Object(mismatches.iter().filter_map(|m| Some((m["model"].as_str()?.to_string(), json!(default(m))))).collect()), + } +} + +/// What `choice` (one choice for every model, or `{rgb?, cmyk?}`) picks for the colors of `model`. +fn picked<'a>(choice: &'a Value, model: &str) -> &'a str { + choice.as_str().or_else(|| choice.get(model).and_then(Value::as_str)).unwrap_or_default() +} + +/// `choice` with `value` picked for the colors of `model`: with one model the value alone, with +/// both a choice for each in which the other model's stays as `choice` has it. +fn pick(choice: &Value, mismatches: &[Value], model: &str, value: &str) -> Value { + if mismatches.len() < 2 { + return json!(value); + } + let each = + mismatches.iter().filter_map(|m| m["model"].as_str()).map(|m| (m.to_string(), json!(if m == model { value } else { picked(choice, m) }))); + Value::Object(each.collect()) +} + +/// Is `choice` one choice for every model, or a choice for each of `mismatches`' models? (Convert +/// for a model whose colors can't convert keeps their numbers, as the paste commands do.) +fn valid_choice(choice: &Value, mismatches: &[Value]) -> bool { + let known = |v: &str| paste_choices().iter().any(|(c, _)| *c == v); + match choice { + Value::String(s) => known(s), + Value::Object(o) => { + let models: Vec<&str> = mismatches.iter().filter_map(|m| m["model"].as_str()).collect(); + o.len() == models.len() && models.iter().all(|m| o.get(*m).and_then(Value::as_str).is_some_and(known)) + } + _ => false, + } +} + +fn paste_body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + let mismatches = d.fields.get("mismatches").and_then(Value::as_array).cloned().unwrap_or_default(); + let choice = d.fields.get("choice").cloned().unwrap_or(Value::Null); + // With both models, each has its own choice under its line; with one, the choice follows it. + for m in &mismatches { + let id = m["model"].as_str().unwrap_or_default(); + let model = id.to_ascii_uppercase(); + let (from, to) = (m["clipboard"].as_str().unwrap_or_default(), m["document"].as_str().unwrap_or_default()); + let text = tl!("The pasted colors come from a document whose {model} profile is “{from}”; this document's is “{to}”."); + ui.label(crate::i18n::fmt(text, &[("model", model.as_str()), ("from", from), ("to", to)])); + ui.add_space(6.0); + let now = picked(&choice, id); + let clicked = ui.push_id(id, |ui| { + grid(ui, |ui| { + let mut clicked = None; + for (value, text) in paste_choices() { + label(ui, ""); + // Colors whose profile is not available can only keep their numbers. + if widgets::radio(ui, text, now == value, allowed(m, value)) { + clicked = Some(value); + } + ui.end_row(); + } + clicked + }) + }); + if let Some(value) = clicked.inner { + d.fields.insert("choice".into(), pick(&choice, &mismatches, id, value)); + } + ui.add_space(10.0); + } + false +} + +/// The field that holds the uid of the document the paste question is about. +const DOC: &str = "__doc"; + +/// OK: run the paste with the choice; any Swatch Conflict question comes next. When another +/// document has become the active one since a paste that runs at once asked, it closes as Cancel +/// does and pastes nothing. When the profiles that paste or drop would bring have changed since it +/// asked (the clipboard, the dragged objects' document or the destination's profile changed), it +/// asks again about the new ones; a paste that waited for its clipboard is checked in the document +/// and with the clipboard it runs with. +fn paste_confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { + let choice = d.fields.get("choice").cloned().unwrap_or(Value::Null); + let asked = d.fields.get("mismatches").and_then(Value::as_array).cloned().unwrap_or_default(); + if !valid_choice(&choice, &asked) { + let key = "choice"; + return Err(format!("`{key}` must be one of {}", "preserveNumbers, convert, {rgb, cmyk} of those")); + } + let deferred = d.fields.get("__deferredPaste").and_then(Value::as_u64); + if deferred.is_none() && d.fields.get(DOC).and_then(Value::as_u64) != app.session.active().map(|st| st.uid) { + app.ui.dialog = None; + return Ok(json!({})); + } + let command = d.str("__command"); + let mut params = d.fields.get("__params").cloned().filter(Value::is_object).unwrap_or_else(|| json!({})); + params["profileMismatch"] = choice; + app.ui.dialog = None; + // Without the answer, the paste asks again about what it brings now. + let changed = |app: &mut VectorcraftApp, command: &str, params: &Value| { + paste_mismatches(app, command, params).is_some_and(|now| !now.is_empty() && now != asked) + }; + let recheck = crate::placing::Recheck { key: "profileMismatch", changed: &changed }; + // A paste that waited for its clipboard runs in the context it was given in. + crate::placing::confirm_swatch_paste(app, &command, params, deferred, Some(&recheck)) +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs b/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs new file mode 100644 index 0000000000..358c6f428e --- /dev/null +++ b/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs @@ -0,0 +1,412 @@ +use vectorcraft_engine::Session; + +use super::*; + +fn frame(app: &mut VectorcraftApp) -> String { + crate::tests_labels::painted_text(app, |app, ui| super::super::show(app, ui.ctx())) +} + +fn set(app: &mut VectorcraftApp, k: &str, v: Value) { + app.ui.dialog.as_mut().unwrap().fields.insert(k.into(), v); +} + +/// The native file of a document with a blue rectangle, assigned `rgb` (none: untagged). +fn file(rgb: Option<&str>) -> Vec { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#3366cc"})).unwrap(); + if let Some(p) = rgb { + s.execute("edit.assignProfile", &json!({ "rgb": p })).unwrap(); + } + let r = s.execute("document.serialize", &json!({})).unwrap(); + vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap() +} + +fn rgb_profile(app: &VectorcraftApp) -> Option { + vectorcraft_engine::cmd::colormgmt::doc_profiles(&app.session.doc().unwrap().doc).0 +} + +/// OK on the open question, run by `confirm`, opens one document, installed with `roots`. +fn confirm_opens_one_under( + app: &mut VectorcraftApp, + roots: Option<&std::sync::Arc>, + confirm: impl FnOnce(&mut VectorcraftApp) -> Value, +) { + let docs = app.session.documents().len(); + let r = confirm(app); + assert_eq!(app.session.documents().len(), docs + 1, "{r}"); + let opened = &app.session.documents()[r["index"].as_u64().unwrap() as usize]; + assert_eq!(opened.opened_by.as_ref().map(|o| o.describe()), roots.map(|o| o.describe())); +} + +/// An open asked under automation roots finishes under them, though OK is pressed outside them: its +/// linked files are read, and the document is installed, with the roots of the open. `tagged` asks +/// with the settings in force. +fn open_asked_under_roots(app: &mut VectorcraftApp, tagged: &[u8]) { + use vectorcraft_engine::file_access; + let dir = crate::tests_folder::Folder::new("profile-mismatch-scope"); + let roots = file_access::AutomationRoots::new(&[dir.as_path()], &[]).unwrap(); + let r = file_access::confine(roots.as_ref(), || crate::io::open_bytes(app, "tagged.vectorcraft", tagged, None)).unwrap(); + assert_eq!(r, json!({ "dialog": OPEN_KIND })); + assert!(file_access::current().is_none(), "OK is pressed outside the roots"); + confirm_opens_one_under(app, roots.as_ref(), |app| super::super::confirm(app).unwrap()); +} + +/// An open asked outside automation roots and confirmed by a caller under them finishes under that +/// caller's roots: the document is installed with them. `tagged` asks with the settings in force. +fn open_confirmed_under_roots(app: &mut VectorcraftApp, tagged: &[u8]) { + use vectorcraft_engine::file_access; + let dir = crate::tests_folder::Folder::new("profile-mismatch-confirm-scope"); + let roots = file_access::AutomationRoots::new(&[dir.as_path()], &[]).unwrap(); + let r = crate::io::open_bytes(app, "tagged.vectorcraft", tagged, None).unwrap(); + assert_eq!(r, json!({ "dialog": OPEN_KIND })); + confirm_opens_one_under(app, roots.as_ref(), |app| file_access::confine(roots.as_ref(), || super::super::confirm(app)).unwrap()); +} + +/// A PNG of one color, 8 × 8. +fn png(rgb: [u8; 3]) -> Vec { + let [r, g, b] = rgb; + let layout = (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8); + let img = craft_image_codecs::Image::from_raw(8, 8, layout.0, layout.1, [r, g, b, 255].repeat(64)).unwrap(); + craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap() +} + +/// The linked files of a document asked about under automation roots, and confirmed outside them, +/// are read under those roots, apart from where the document is installed: of two linked files +/// changed since the save, the one inside the roots updates, and the one outside keeps the picture +/// the document holds. The Ask When Opening box for a mismatch is on. +fn links_read_under_the_roots_of_the_open(app: &mut VectorcraftApp) { + use vectorcraft_engine::file_access; + let dir = crate::tests_folder::Folder::new("profile-mismatch-links"); + let (inside, outside) = (dir.join("inside"), dir.join("outside")); + let (a, b) = (inside.join("in.png"), outside.join("out.png")); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + for p in [&a, &b] { + std::fs::create_dir_all(p.parent().unwrap()).unwrap(); + std::fs::write(p, png([200, 40, 40])).unwrap(); + s.execute("file.place", &json!({"path": p.to_str().unwrap(), "at": [50, 50]})).unwrap(); + } + s.execute("edit.assignProfile", &json!({ "rgb": cms::WIDE_GAMUT_RGB })).unwrap(); + let r = s.execute("document.serialize", &json!({})).unwrap(); + let bytes = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap(); + // The profiles in use are the process's: back to the working spaces. + s.execute("edit.assignProfile", &json!({ "rgb": null })).unwrap(); + for p in [&a, &b] { + let stamp = std::fs::metadata(p).unwrap().modified().unwrap(); + std::fs::write(p, png([40, 40, 200])).unwrap(); + // Link stamps use milliseconds: the new file is dated 2 s later. + let later = std::fs::FileTimes::new().set_modified(stamp + std::time::Duration::from_secs(2)); + std::fs::OpenOptions::new().write(true).open(p).unwrap().set_times(later).unwrap(); + } + let update = std::mem::replace(&mut app.session.prefs.update_links, "automatically".into()); + let roots = file_access::AutomationRoots::new(&[inside.as_path()], &[]).unwrap(); + let r = file_access::confine(roots.as_ref(), || crate::io::open_bytes(app, "linked.vectorcraft", &bytes, None)).unwrap(); + assert_eq!(r, json!({ "dialog": OPEN_KIND })); + let r = super::super::confirm(app).unwrap(); + let updated: Vec<&str> = r["updatedLinks"].as_array().map(|a| a.iter().filter_map(|l| l["name"].as_str()).collect()).unwrap_or_default(); + assert_eq!(updated, ["in.png"], "{r}"); + app.session.prefs.update_links = update; + // A question about the link outside the roots is not part of this check. + if app.ui.dialog.is_some() { + super::super::cancel(app); + } +} + +/// A file read while another one's question is open waits and asks its own question in turn, and +/// each opens only after its own answer: Cancel on the first leaves it closed and asks about the +/// second. `tagged` asks with the settings in force. +fn files_opened_together_ask_in_turn(app: &mut VectorcraftApp, tagged: &[u8]) { + let docs = app.session.documents().len(); + assert_eq!(crate::io::open_bytes(app, "first.vectorcraft", tagged, None).unwrap(), json!({ "dialog": OPEN_KIND })); + let r = crate::io::open_bytes(app, "second.vectorcraft", tagged, None).unwrap(); + assert_eq!(r, json!({ "dialog": OPEN_KIND, "queued": true })); + assert_eq!(app.queued_profile_opens.len(), 1); + super::super::cancel(app); + assert!(app.ui.dialog.as_ref().is_some_and(|d| d.kind == OPEN_KIND) && app.pending_profile_open.is_some(), "the second asks"); + assert!(app.queued_profile_opens.is_empty()); + assert_eq!(app.session.documents().len(), docs, "neither is open"); + super::super::confirm(app).unwrap(); + assert_eq!(app.session.documents().len(), docs + 1); + assert!(app.ui.dialog.is_none() && app.pending_profile_open.is_none()); +} + +/// Color Settings change the open question while it is open: OK asks the question as it is now +/// (another working space) instead of opening, and opens by the policy once there is no question +/// (the working space is the file's profile). `tagged` (Wide Gamut RGB) asks with the settings in +/// force, the working space sRGB. +fn an_answer_waits_for_the_question_it_answers(app: &mut VectorcraftApp, tagged: &[u8]) { + let docs = app.session.documents().len(); + crate::io::open_bytes(app, "tagged.vectorcraft", tagged, None).unwrap(); + app.run("edit.colorSettings", json!({"rgb": cms::DISPLAY_P3})).unwrap(); + assert_eq!(super::super::confirm(app).unwrap(), json!({ "dialog": OPEN_KIND })); + assert_eq!(app.session.documents().len(), docs, "not opened under the old question"); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("working"), cms::canonical_name(cms::DISPLAY_P3), "asked again"); + app.run("edit.colorSettings", json!({"rgb": cms::WIDE_GAMUT_RGB})).unwrap(); + let r = super::super::confirm(app).unwrap(); + assert!(r.get("index").is_some() && app.ui.dialog.is_none(), "{r}"); + assert_eq!(app.session.documents().len(), docs + 1); +} + +/// Swatch Conflict asks again when the conflicts a converting paste raises change while it is open: +/// the destination is assigned another profile, so the pasted swatch converts to another color. OK +/// then pastes nothing and asks about the new conflict; OK on that one pastes as chosen. +fn swatch_conflicts_are_asked_again_when_they_change(app: &mut VectorcraftApp) { + use super::super::swatch_conflict; + let swatch = json!({"name": "Brand", "color": "#3366cc", "global": true}); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("swatch.new", swatch.clone()).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + app.run("paint.setFill", json!({"swatch": "Brand"})).unwrap(); + app.run("edit.assignProfile", json!({ "rgb": cms::WIDE_GAMUT_RGB })).unwrap(); + app.run("edit.copy", json!({})).unwrap(); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("swatch.new", swatch).unwrap(); + let count = |app: &VectorcraftApp| app.session.doc().unwrap().doc.layers[0].children().map_or(0, |c| c.len()); + let before = count(app); + let r = app.run("edit.paste", json!({"profileMismatch": "convert"})).unwrap(); + assert_eq!(r["dialog"], swatch_conflict::KIND, "{r}"); + let asked = app.ui.dialog.as_ref().unwrap().fields["conflicts"].clone(); + set(app, "choice", json!("add")); + app.run("edit.assignProfile", json!({ "rgb": cms::DISPLAY_P3 })).unwrap(); + let r = super::super::confirm(app).unwrap(); + assert_eq!(r["dialog"], swatch_conflict::KIND, "asked again: {r}"); + assert_eq!(count(app), before, "nothing pasted under the old list"); + assert_ne!(app.ui.dialog.as_ref().unwrap().fields["conflicts"], asked); + set(app, "choice", json!("add")); + let r = super::super::confirm(app).unwrap(); + assert_eq!((count(app), r["renamed"].as_array().map(Vec::len)), (before + 1, Some(1)), "{r}"); +} + +/// Cancel on the paste question pastes nothing, and a null `profileMismatch` asks as leaving it out +/// does. `count` counts the active document's objects. +fn paste_canceled(app: &mut VectorcraftApp, count: impl Fn(&VectorcraftApp) -> usize) { + let before = count(app); + for params in [json!({}), json!({ "profileMismatch": null })] { + assert_eq!(app.run("edit.paste", params.clone()).unwrap(), json!({ "dialog": PASTE_KIND }), "{params} asks"); + super::super::cancel(app); + assert_eq!(count(app), before); + } +} + +/// Another document becomes the active one while the paste question is open: OK pastes nothing, into +/// neither document, whichever is active. +fn paste_asked_before_another_document_is_active(app: &mut VectorcraftApp) { + let counts = |app: &VectorcraftApp| -> Vec<(u64, usize)> { + app.session.documents().iter().map(|st| (st.uid, st.doc.layers[0].children().map_or(0, |c| c.len()))).collect() + }; + let (asked_in, before) = (app.session.active_index().unwrap(), counts(app)); + assert_eq!(app.run("edit.paste", json!({})).unwrap(), json!({ "dialog": PASTE_KIND })); + app.run("document.activate", json!({"index": 0})).unwrap(); + super::super::confirm(app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(counts(app), before, "nothing pasted into any document"); + app.run("document.activate", json!({ "index": asked_in })).unwrap(); +} + +/// A drag of the art of the document assigned Display P3 into the active one asks as Paste does: +/// Cancel drops nothing, and OK drops it as chosen. When the source document's profile changes while +/// the question is open, OK drops nothing and asks again about the new profile. `count` counts the +/// active document's objects. +fn drop_asks_as_paste_does(app: &mut VectorcraftApp, count: impl Fn(&VectorcraftApp) -> usize) { + let p3 = Some(cms::DISPLAY_P3); + let docs = app.session.documents(); + let at = docs.iter().position(|st| vectorcraft_engine::cmd::colormgmt::doc_profiles(&st.doc).0.as_deref() == p3).unwrap(); + let source = &docs[at]; + let ids: Vec = source.doc.layers[0].children().unwrap().iter().map(|n| n.id.0).collect(); + let n = ids.len(); + let drop = json!({"sourceDocument": source.uid, "ids": ids, "grab": [0, 0], "at": [50, 50]}); + let before = count(app); + assert_eq!(app.run(DROP, drop.clone()).unwrap(), json!({ "dialog": PASTE_KIND })); + assert_eq!(count(app), before, "nothing dropped yet"); + super::super::cancel(app); + assert_eq!(count(app), before, "Cancel drops nothing"); + assert_eq!(app.run(DROP, drop).unwrap(), json!({ "dialog": PASTE_KIND })); + // The source document is assigned another profile before OK. + let asked_in = app.session.active_index().unwrap(); + app.run("document.activate", json!({ "index": at })).unwrap(); + app.session.execute("edit.assignProfile", &json!({ "rgb": cms::WIDE_GAMUT_RGB })).unwrap(); + app.run("document.activate", json!({ "index": asked_in })).unwrap(); + assert_eq!(super::super::confirm(app).unwrap(), json!({ "dialog": PASTE_KIND })); + assert_eq!(count(app), before, "nothing dropped under the old question"); + let asked = &app.ui.dialog.as_ref().unwrap().fields["mismatches"][0]["clipboard"]; + assert_eq!(asked, &json!(cms::WIDE_GAMUT_RGB), "asked again about the new profile"); + set(app, "choice", json!("convert")); + let r = super::super::confirm(app).unwrap(); + assert_eq!(r["profileMismatch"][0]["choice"], "convert"); + assert!(app.ui.dialog.is_none()); + assert_eq!(count(app), before + n); +} + +/// A paste question about both models has a choice for each, starting on its model's policy, and +/// picking one model's choice in the dialog leaves the other's as it was; OK checks the choice. +#[test] +fn a_paste_question_about_both_models_has_a_choice_for_each() { + let both = [ + json!({"model": "rgb", "clipboard": "Wide RGB", "document": "sRGB", "default": "preserveNumbers", "convertible": true}), + json!({"model": "cmyk", "clipboard": "Ink A", "document": "Ink B", "default": "convert", "convertible": true}), + ]; + assert_eq!(first_choice(&both), json!({"rgb": "preserveNumbers", "cmyk": "convert"})); + assert_eq!(first_choice(&both[1..]), json!("convert"), "one model starts on its policy"); + for (choice, ok) in [ + (json!({"rgb": "convert", "cmyk": "preserveNumbers"}), true), + (json!("convert"), true), + (json!({"rgb": "convert"}), false), + (json!({"rgb": "convert", "cmyk": "keep"}), false), + (json!({"rgb": "convert", "cmyk": "convert", "lab": "convert"}), false), + (json!(""), false), + ] { + assert_eq!(valid_choice(&choice, &both), ok, "{choice}"); + } + // Picking CMYK's choice keeps RGB's, also when one choice was set for both. + let start = first_choice(&both); + assert_eq!(pick(&start, &both, "cmyk", "preserveNumbers"), json!({"rgb": "preserveNumbers", "cmyk": "preserveNumbers"})); + assert_eq!(pick(&json!("convert"), &both, "rgb", "preserveNumbers"), json!({"rgb": "preserveNumbers", "cmyk": "convert"})); + assert_eq!(pick(&json!("convert"), &both[..1], "rgb", "preserveNumbers"), json!("preserveNumbers")); + // The dialog draws a pair of choices under each model's line. + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let fields = json!({ "mismatches": both, "choice": start, "__command": "edit.paste", "__params": {} }); + app.ui.dialog = Some(Dialog::new(PASTE_KIND, fields)); + let text = frame(&mut app); + assert_eq!(text.matches("Preserve the color numbers").count(), 2, "{text}"); +} + +/// With Color Settings' Ask boxes on, File › Open asks about a document whose profile is not the +/// working space, or that has none, and opens it as chosen; Cancel doesn't open it, and a refused +/// choice keeps the dialog. Paste, and a drag from another document, ask about colors from another +/// profile and paste or drop as chosen. With the boxes off, nothing asks. An open asked or confirmed +/// under automation roots finishes under them, and a paste asked in one document pastes nothing once +/// another is active. +#[test] +fn opening_and_pasting_ask_about_profiles() { + const CHILD: &str = "VECTORCRAFT_TEST_PROFILE_PROMPTS"; + if std::env::var_os(CHILD).is_none() { + // Color settings are process-wide: change them in a separate test process. + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "dialogs::profile_mismatch::tests::opening_and_pasting_ask_about_profiles", "--nocapture"]) + .env(CHILD, "1") + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + output.status.success() && stdout.contains("test result: ok. 1 passed; 0 failed;"), + "isolated profile prompt test failed:\n{stdout}\n{}", + String::from_utf8_lossy(&output.stderr), + ); + return; + } + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let (tagged, plain) = (file(Some(cms::WIDE_GAMUT_RGB)), file(None)); + // The boxes are off: the document opens as the policy says. + let r = crate::io::open_bytes(&mut app, "tagged.vectorcraft", &tagged, None).unwrap(); + assert!(r.get("index").is_some() && app.ui.dialog.is_none()); + assert_eq!(rgb_profile(&app).as_deref(), Some(cms::WIDE_GAMUT_RGB)); + + // Profile Mismatches: Ask When Opening. + app.run("edit.colorSettings", json!({"askMismatchOpen": true, "rgbPolicy": "convert"})).unwrap(); + let docs = app.session.documents().len(); + let r = crate::io::open_bytes(&mut app, "tagged.vectorcraft", &tagged, None).unwrap(); + assert_eq!(r, json!({ "dialog": OPEN_KIND })); + assert_eq!(app.session.documents().len(), docs, "not open yet"); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!( + (d.str("issue"), d.str("model"), d.str("profile"), d.str("choice")), + ("mismatch".into(), "RGB".into(), cms::WIDE_GAMUT_RGB.into(), "convert".into()) + ); + let text = frame(&mut app); + for label in [ + "Embedded Profile Mismatch", + "Use the embedded profile", + "Convert the colors to the working space", + "Discard the embedded profile", + cms::WIDE_GAMUT_RGB, + ] { + assert!(text.contains(label), "{label} in {text}"); + } + // Cancel: nothing opens. + super::super::cancel(&mut app); + assert!(app.pending_profile_open.is_none()); + assert_eq!(app.session.documents().len(), docs); + crate::io::open_bytes(&mut app, "tagged.vectorcraft", &tagged, None).unwrap(); + set(&mut app, "choice", json!("useEmbedded")); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none() && app.pending_profile_open.is_none()); + assert_eq!(app.session.documents().len(), docs + 1); + assert_eq!(rgb_profile(&app).as_deref(), Some(cms::WIDE_GAMUT_RGB), "kept, though the policy converts"); + + open_asked_under_roots(&mut app, &tagged); + open_confirmed_under_roots(&mut app, &tagged); + links_read_under_the_roots_of_the_open(&mut app); + files_opened_together_ask_in_turn(&mut app, &tagged); + + // Missing Profiles: Ask When Opening, and a choice the file refuses. + app.run("edit.colorSettings", json!({"askMismatchOpen": false, "askMissingOpen": true, "rgbPolicy": "preserveEmbedded"})).unwrap(); + crate::io::open_bytes(&mut app, "plain.vectorcraft", &plain, None).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.kind.as_str(), d.str("issue"), d.str("choice")), (OPEN_KIND, "missing".into(), "leave".into())); + let text = frame(&mut app); + for label in ["Missing Profile", "Leave as is", "Assign the working space", "Assign profile:"] { + assert!(text.contains(label), "{label} in {text}"); + } + set(&mut app, "choice", json!("assign")); + set(&mut app, "assignProfile", json!(cms::DEVICE_CMYK)); + assert!(super::super::confirm(&mut app).is_err()); + assert!(app.ui.dialog.as_ref().is_some_and(|d| d.kind == OPEN_KIND) && app.pending_profile_open.is_some(), "still asking"); + set(&mut app, "assignProfile", json!(cms::DISPLAY_P3)); + super::super::confirm(&mut app).unwrap(); + assert_eq!(rgb_profile(&app).as_deref(), Some(cms::DISPLAY_P3)); + assert!(app.session.doc().unwrap().is_dirty(), "assigning changed the document"); + + // Profile Mismatches: Ask When Pasting. + app.run("edit.colorSettings", json!({"askMissingOpen": false, "askMismatchPaste": true})).unwrap(); + app.run("select.all", json!({})).unwrap(); + app.run("edit.copy", json!({})).unwrap(); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + let r = app.run("edit.paste", json!({})).unwrap(); + assert_eq!(r, json!({ "dialog": PASTE_KIND })); + let text = frame(&mut app); + for label in ["Paste Profile Mismatch", "Preserve the color numbers", "Convert to keep the colors' appearance", cms::DISPLAY_P3] { + assert!(text.contains(label), "{label} in {text}"); + } + set(&mut app, "choice", json!("convert")); + let r = super::super::confirm(&mut app).unwrap(); + assert_eq!(r["profileMismatch"][0]["choice"], "convert"); + assert!(app.ui.dialog.is_none()); + // Cancel pastes nothing; with the box off nothing asks. + let count = |app: &VectorcraftApp| app.session.doc().unwrap().doc.layers[0].children().map_or(0, |c| c.len()); + paste_canceled(&mut app, count); + paste_asked_before_another_document_is_active(&mut app); + drop_asks_as_paste_does(&mut app, count); + let before = count(&app); + app.run("edit.colorSettings", json!({"askMismatchPaste": false})).unwrap(); + let r = app.run("edit.paste", json!({})).unwrap(); + assert_eq!(r["profileMismatch"][0]["choice"], "preserveNumbers"); + assert_eq!(count(&app), before + 1); + swatch_conflicts_are_asked_again_when_they_change(&mut app); + all_artboards_leaves_backgrounds_out(&mut app); + // It changes the working space: last. + app.run("edit.colorSettings", json!({"askMismatchOpen": true})).unwrap(); + an_answer_waits_for_the_question_it_answers(&mut app, &tagged); +} + +/// Convert is offered only for a model whose colors can convert (`convertible`). +#[test] +fn convert_needs_both_profiles() { + let stuck = json!({"model": "rgb", "clipboard": "Gone", "document": "sRGB", "default": "preserveNumbers", "convertible": false}); + let free = json!({"model": "rgb", "clipboard": "Wide RGB", "document": "sRGB", "default": "convert", "convertible": true}); + assert!(allowed(&stuck, "preserveNumbers") && !allowed(&stuck, "convert")); + assert!(allowed(&free, "convert") && allowed(&json!({"model": "rgb"}), "convert")); +} + +/// Paste on All Artboards asks about what it brings, without the backgrounds of copied artboards. +fn all_artboards_leaves_backgrounds_out(app: &mut VectorcraftApp) { + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("artboard.setProps", json!({"index": 0, "color": "#3366cc"})).unwrap(); + app.run("edit.assignProfile", json!({ "rgb": cms::WIDE_GAMUT_RGB })).unwrap(); + app.run("artboard.copy", json!({"index": 0})).unwrap(); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + let listed = |app: &mut VectorcraftApp, command: &str| paste_mismatches(app, command, &json!({})).map(|m| m.len()); + assert_eq!(listed(app, "edit.paste"), Some(1), "the background is RGB"); + assert_eq!(listed(app, ALL_ARTBOARDS), Some(0)); +} diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index b3cb557b61..267b2ac0c8 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -70,6 +70,12 @@ //! the most used color first and repeating when the rows outnumber them, and the art previews //! them; OK keeps them as one undo step. A new count of Colors keeps the picks: the new rows take them again. //! +//! Undo Changes and Redo Changes beside the Color Theme Picker (`ui.recolorUndo`, `ui.recolorRedo`) +//! step back and forward through the dialog's own color edits ([`History`]), not the document's +//! undo history; Cancel discards them and OK still records one undo step. Each opening starts +//! with nothing to undo, and selecting another color group or Save Changes leaves nothing to undo +//! or redo. +//! //! Fields (`ui.dialog.set`): `rows` ([{from: [keys], to: key, exclude?, tint?: percent of a spot //! color, added?}]; a row with no current colors, `from: []`, recolors no art, and with `added: true` //! (a color the Add Color tool added) adds its new color to the color group; `to: null`, no new color), `colors` (null: Auto, or a count), `method`, `preserveWhite`, `preserveBlack`, @@ -223,6 +229,8 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { let mut rs = rows(&d); snap(app, &d, &mut rs); d.fields.insert("rows".into(), Value::Array(rs)); + // Undo Changes has nothing to undo on a new opening. + app.ui.recolor_history = History { opened: Some(snapshot(&d)), ..History::default() }; app.ui.dialog = Some(d); Ok(Value::Null) } @@ -499,6 +507,7 @@ fn select_group(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> d.fields.insert("__newGroup".into(), json!(true)); d.fields.insert("groupName".into(), json!(NEW_GROUP)); } + restart_history(app, d); return Ok(()); } Value::String(n) => n.clone(), @@ -538,6 +547,7 @@ fn select_group(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> d.fields.remove(COMPS); } d.fields.insert("__assign".into(), Value::Array(assign)); + restart_history(app, d); Ok(()) } @@ -559,6 +569,7 @@ fn group_action(app: &mut VectorcraftApp, d: &mut Dialog, action: &Value) -> Res // Nothing changed since the last save but perhaps the name. let name = d.str("groupName"); if name.trim().is_empty() || group.as_deref() == Some(name.as_str()) { + restart_history(app, d); return Ok(()); } cancel_preview(app, d); @@ -572,6 +583,7 @@ fn group_action(app: &mut VectorcraftApp, d: &mut Dialog, action: &Value) -> Res d.fields.insert("group".into(), name.clone()); d.fields.insert(GROUP_LOADED.into(), name.clone()); d.fields.insert("groupName".into(), name); + restart_history(app, d); Ok(()) } Some("save") => { @@ -678,6 +690,7 @@ fn group_action(app: &mut VectorcraftApp, d: &mut Dialog, action: &Value) -> Res reread_rows(app, d, &rs, &before, &gone); } } + restart_history(app, d); Ok(()) } Some("delete") => { @@ -1338,14 +1351,19 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { /// The tabs and the controls under them. Returns the row whose new color a double-click or Pick /// from Swatches asked to pick in the Color Picker, with `true` for Pick from Swatches. fn main(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> Option<(usize, bool)> { + seed(app, d); sync(app, d); sync_theme(app, d); sync_weights(app, d); + // The fields as the dialog read the art are where Undo Changes starts, also when the pointer is + // down on the first frame and the first step is recorded only on release. + app.ui.recolor_history.start(d); if let Err(e) = run_group_action(app, d) { app.status(e); } let t = Tokens::get(ui.ctx()); let picking = d.bool(THEME_PICKER); + let mut stepped = None; ui.horizontal(|ui| { let tab = d.str("tab"); for (id, label) in [("assign", tl!("Assign")), ("edit", tl!("Edit"))] { @@ -1357,6 +1375,12 @@ fn main(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> Option<(usize, if widgets::icon_button(ui, "pipette", tl!("Color Theme Picker"), picking, 24.0).clicked() { d.fields.insert(THEME_PICKER.into(), json!(!picking)); } + let h = &app.ui.recolor_history; + for (back, icon, tip) in [(true, "undo-2", tl!("Undo Changes")), (false, "redo-2", tl!("Redo Changes"))] { + if widgets::icon_button_enabled(ui, icon, tip, false, h.can(d, back), 24.0).clicked() { + stepped = Some(back); + } + } let storage = d.bool(GROUP_STORAGE); if widgets::icon_button(ui, "library", tl!("Show Color Groups"), storage, 24.0).clicked() { d.fields.insert(GROUP_STORAGE.into(), json!(!storage)); @@ -1369,6 +1393,9 @@ fn main(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> Option<(usize, ui.label(egui::RichText::new(tl!("Preset:")).color(t.text_dim)); }); }); + if let Some(back) = stepped { + app.ui.recolor_history.step(d, back); + } widgets::divider(ui); ui.add_space(4.0); if d.bool(THEME_PICKER) { @@ -1405,6 +1432,12 @@ fn main(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> Option<(usize, }); } sync(app, d); + // New rows take the picks now, so that a new count of Colors is one step. + sync_theme(app, d); + // A change is a step once the pointer is up: a drag is one step from press to release. + if !ui.input(|i| i.pointer.any_down()) { + app.ui.recolor_history.note(d); + } if d.bool("__art") { match find_params(d) { // Find shows the art so with Preview off too. @@ -1431,6 +1464,187 @@ pub(super) fn with_new_color(app: &VectorcraftApp, mut d: Dialog, i: usize, c: C d } +/// The fields a step of Undo Changes and Redo Changes restores: what the art is recolored with. +const STEP_FIELDS: [&str; 11] = + ["rows", "colors", "method", "preserveWhite", "preserveBlack", "preserveGrays", "limitTo", "rule", "globalAdjust", THEME_PICKS, WEIGHTS]; +/// The fields that record which reduction, picks and weights the rows already took, restored with +/// [`STEP_FIELDS`] so that the restored rows are not reduced, picked or weighed again. +const STEP_MARKS: [&str; 4] = ["__reduced", THEME_DONE, WEIGHED, PRESERVED]; +/// VectorCraft's own limits on the steps Undo Changes keeps: at most this many, and at most this +/// many bytes of them as JSON; the oldest go first. +const MAX_STEPS: usize = 64; +const MAX_STEP_BYTES: usize = 4 << 20; + +type Snapshot = serde_json::Map; + +/// The open dialog's own history of color edits: Undo Changes goes back one edit and Redo Changes +/// forward one, without touching the document's undo history. A change of [`STEP_FIELDS`] is one +/// step once the pointer is up, so a drag is one step; a new edit after Undo Changes ends what Redo +/// Changes could restore. +#[derive(Clone, Debug, Default)] +pub struct History { + /// The fields the dialog opened with (or had when its steps were dropped), before it read the + /// art, until its first frame or command. + opened: Option, + /// The fields after the last step (none before the dialog's first frame). + base: Option, + undo: Vec, + redo: Vec, +} + +/// Drop the dialog's steps, after another color group is selected or Save Changes rewrites the +/// group: Undo Changes and Redo Changes then have no step to go to. The fields of `d` are where +/// Undo Changes starts again, as on a new opening, so fields set before the next frame or step +/// (with `ui.dialog.set`) are a step back to them. +fn restart_history(app: &mut VectorcraftApp, d: &Dialog) { + app.ui.recolor_history = History { opened: Some(snapshot(d)), ..History::default() }; +} + +/// The size of `s` as JSON, which [`MAX_STEP_BYTES`] limits. +fn snapshot_size(s: &Snapshot) -> usize { + serde_json::to_vec(s).map_or(0, |b| b.len()) +} + +/// The fields of `d` a step restores ([`STEP_FIELDS`] and [`STEP_MARKS`]). +fn snapshot(d: &Dialog) -> Snapshot { + STEP_FIELDS.iter().chain(&STEP_MARKS).filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone()))).collect() +} + +/// Before the first step is recorded: when fields were set after the dialog opened (with +/// `ui.dialog.set`, before a frame drew it), the fields it opened with, as they read the art, are +/// the step Undo Changes goes back to. +fn seed(app: &mut VectorcraftApp, d: &Dialog) { + let Some(opened) = app.ui.recolor_history.opened.take() else { return }; + if app.ui.recolor_history.base.is_some() || snapshot(d) == opened { + return; + } + let mut first = d.clone(); + first.fields.remove(super::form::PREVIEWED); + for k in STEP_FIELDS.iter().chain(&STEP_MARKS) { + match opened.get(*k) { + Some(v) => first.fields.insert(k.to_string(), v.clone()), + None => first.fields.remove(*k), + }; + } + sync(app, &mut first); + sync_theme(app, &mut first); + app.ui.recolor_history.base = Some(snapshot(&first)); +} + +impl History { + /// Take the fields of `d` as those after the last step when no step has them yet. + fn start(&mut self, d: &Dialog) { + if self.base.is_none() { + self.base = Some(snapshot(d)); + } + } + + /// Whether the fields of `d` differ from those after the last step. + fn pending(&self, d: &Dialog) -> bool { + self.base.as_ref().is_some_and(|b| STEP_FIELDS.iter().any(|k| d.fields.get(*k) != b.get(*k))) + } + + /// Record a change of `d`'s fields since the last step as a step. + fn note(&mut self, d: &Dialog) { + if self.base.is_some() && !self.pending(d) { + return; + } + if let Some(before) = self.base.replace(snapshot(d)) { + self.undo.push(before); + self.redo.clear(); + self.trim(); + } + } + + /// Drop the oldest steps past [`MAX_STEPS`] and [`MAX_STEP_BYTES`], keeping the newest step + /// even when it and the current fields alone pass the byte limit. + fn trim(&mut self) { + let extra = self.undo.len().saturating_sub(MAX_STEPS); + self.undo.drain(..extra); + let mut total: usize = self.base.iter().chain(&self.undo).map(snapshot_size).sum(); + let mut gone = 0; + while total > MAX_STEP_BYTES && gone + 1 < self.undo.len() { + total -= snapshot_size(&self.undo[gone]); + gone += 1; + } + self.undo.drain(..gone); + } + + fn can(&self, d: &Dialog, back: bool) -> bool { + // Before the first frame or command, fields set since the dialog opened are a step back, + // except rows and weights that the art's reduction is about to replace or drop ([`sync`]). + if self.base.is_none() + && let Some(opened) = &self.opened + { + let reduces = d.bool("__art") && d.fields.get("__reduced") != Some(&reduce_params(d)); + let kept = |k: &&&str| !(reduces && (**k == "rows" || **k == WEIGHTS)); + return back && STEP_FIELDS.iter().filter(kept).any(|k| d.fields.get(*k) != opened.get(*k)); + } + if back { !self.undo.is_empty() || self.pending(d) } else { !self.redo.is_empty() && !self.pending(d) } + } + + /// Undo Changes (`back`) or Redo Changes on `d`: give it the fields of the step before or after. + /// Returns false when there is none. + fn step(&mut self, d: &mut Dialog, back: bool) -> bool { + self.note(d); + let (from, to) = if back { (&mut self.undo, &mut self.redo) } else { (&mut self.redo, &mut self.undo) }; + let Some(s) = from.pop() else { return false }; + to.extend(self.base.take()); + for k in STEP_FIELDS.iter().chain(&STEP_MARKS) { + match s.get(*k) { + Some(v) => d.fields.insert(k.to_string(), v.clone()), + None => d.fields.remove(*k), + }; + } + // The rows hold no slider edit or drag, and the selection keeps to them. + for k in [COMPS, DRAG, BAR_DRAG, SHUFFLED] { + d.fields.remove(k); + } + let n = rows(d).len(); + d.fields.insert("__sel".into(), json!(selection(d).into_iter().filter(|i| *i < n).collect::>())); + self.base = Some(s); + true + } +} + +/// Undo Changes (`ui.recolorUndo`, `back`) or Redo Changes (`ui.recolorRedo`) in the open Recolor +/// Artwork dialog → {changed, canUndo, canRedo}. +pub(crate) fn step(app: &mut VectorcraftApp, back: bool) -> Result { + if app.ui.dialog.as_ref().is_none_or(|d| d.kind != KIND) { + return Err("Recolor Artwork is not open".into()); + } + let Some(mut d) = app.ui.dialog.take() else { return Err("Recolor Artwork is not open".into()) }; + // Fields set since the last frame take effect first, as the next frame would give them. + seed(app, &d); + sync(app, &mut d); + sync_theme(app, &mut d); + sync_weights(app, &mut d); + let mut h = std::mem::take(&mut app.ui.recolor_history); + let changed = h.step(&mut d, back); + let r = json!({"changed": changed, "canUndo": h.can(&d, true), "canRedo": h.can(&d, false)}); + app.ui.recolor_history = h; + // The art previews the step at once, as the frame after a button would preview it. + if changed && d.bool("__art") { + sync_weights(app, &mut d); + match find_params(&d) { + Some(p) => { + let _ = form::preview_now(app, &mut d, "Recolor Artwork", "command.batch", p); + } + None => { + let p = apply_params(&d); + form::preview_without_check(app, &mut d, "Recolor Artwork", CMD, p); + } + } + } + app.ui.dialog = Some(d); + Ok(r) +} + +/// Whether Undo Changes (`back`) or Redo Changes can run: Recolor Artwork is open with a step to go to. +pub(crate) fn can_step(app: &VectorcraftApp, back: bool) -> bool { + app.ui.dialog.as_ref().filter(|d| d.kind == KIND).is_some_and(|d| app.ui.recolor_history.can(d, back)) +} + /// OK: keep the previewed recolour as one undo step (or apply it, e.g. to a colour group only; or /// save colours opened alone as a new colour group). fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { @@ -1450,9 +1664,12 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { } if d.bool("__newGroup") { let colors = group_colors(app, &d, rows(&d).iter().filter(|r| in_group(r))); - return form::commit_preview(app, "swatch.newGroup", json!({"name": d.str("groupName"), "colors": colors, "keepModel": true})); + let r = form::commit_preview(app, "swatch.newGroup", json!({"name": d.str("groupName"), "colors": colors, "keepModel": true}))?; + app.ui.recolor_history = History::default(); + return Ok(r); } let r = form::commit_preview(app, CMD, apply_params(&d))?; + app.ui.recolor_history = History::default(); // The Preserve checkboxes (shown with art) open as confirmed here next time (#2960). if d.bool("__art") { app.ui.recolor_preserve = @@ -3449,6 +3666,47 @@ mod tests { assert_eq!(g.swatches.iter().filter_map(|w| w.paint.color()).collect::>(), [Color::rgb8(255, 128, 0)]); } + /// Undo Changes keeps at most [`MAX_STEPS`] steps and [`MAX_STEP_BYTES`] of them, the oldest + /// going first; fields that change nothing make no step, and with fields larger than the limit + /// only the newest step is kept, so Undo Changes is never on with no step to go to. + #[test] + fn undo_changes_keeps_a_bounded_history() { + let mut d = Dialog::new(KIND, json!({"rows": [], "colors": null})); + let mut h = History::default(); + h.note(&d); + h.note(&d); + assert!(h.undo.is_empty(), "no change, no step"); + for n in 0..MAX_STEPS + 6 { + d.fields.insert("colors".into(), json!(n)); + h.note(&d); + } + assert_eq!(h.undo.len(), MAX_STEPS, "the oldest steps go first"); + assert_eq!(h.undo[0]["colors"], json!(5)); + // Rows of 100 KiB each: the steps kept stay within the byte limit. + let big = |n: usize| json!([{"from": [format!("{n}{}", "x".repeat(100 << 10))], "to": null}]); + for n in 0..60 { + d.fields.insert("rows".into(), big(n)); + h.note(&d); + } + let size = |s: &Snapshot| serde_json::to_vec(s).unwrap().len(); + let total: usize = h.base.iter().chain(&h.undo).map(size).sum(); + assert!(total <= MAX_STEP_BYTES, "{total}"); + assert!(h.undo.len() < 60 && !h.undo.is_empty(), "{}", h.undo.len()); + assert!(h.step(&mut d, true), "the newest step is kept"); + assert_eq!(d.fields["rows"], big(58)); + // Current fields past the limit alone: only the step to them is kept, so Undo Changes + // still goes back one step. + d.fields.insert("rows".into(), json!([{"from": ["x".repeat(MAX_STEP_BYTES)], "to": null}])); + h.note(&d); + assert!(h.undo.len() == 1 && h.redo.is_empty(), "{}", h.undo.len()); + d.fields.insert("colors".into(), json!(1)); + assert!(h.can(&d, true), "the change to colors is a step too"); + assert!(h.step(&mut d, true), "and it is kept"); + assert_eq!(d.fields["colors"], json!(MAX_STEPS + 5), "Undo Changes gives back the colors before it"); + assert_eq!(h.undo.len(), 0, "the step before it went to keep the newest"); + assert!(!h.can(&d, true)); + } + /// Sets `field` of the open dialog to `value` as `ui.dialog.set` does: a refused value leaves /// the dialog as it was. fn set(app: &mut VectorcraftApp, field: &str, value: Value) -> Result<(), String> { @@ -3536,6 +3794,105 @@ mod tests { assert_eq!(group_hex(&app, "A"), Some(vec!["#ff0000".into(), "#00ff00".into()]), "other groups are left as they are"); } + /// Without art: selecting another color group in the list and Save Changes leave Undo Changes + /// and Redo Changes no step to go to, so OK gives the selected group the rows read for it. + #[test] + fn another_group_or_save_changes_leaves_nothing_to_undo() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "A", "colors": ["#ff0000", "#00ff00"], "keepModel": true})).unwrap(); + app.run("swatch.newGroup", json!({"name": "B", "colors": ["#0000ff", "#ffff00", "#ffffff"], "keepModel": true})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "A"})).unwrap(); + frame(&mut app, &ctx, 0.0, vec![], 0); + let edit = |app: &mut VectorcraftApp, to: &str| { + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + rs[0]["to"] = json!(to); + d.fields.insert("rows".into(), Value::Array(rs)); + }; + edit(&mut app, "rgb 0 0 0"); + frame(&mut app, &ctx, 0.1, vec![], 0); + assert!(super::can_step(&app, true), "the edit is a step"); + + set(&mut app, "group", json!("B")).unwrap(); + frame(&mut app, &ctx, 0.2, vec![], 0); + assert!(!super::can_step(&app, true) && !super::can_step(&app, false), "another group leaves no step"); + assert_eq!(super::step(&mut app, true).unwrap()["changed"], json!(false)); + assert_eq!(new_colors(&app).len(), 3, "the rows of B"); + + edit(&mut app, "rgb 0 128 0"); + frame(&mut app, &ctx, 0.3, vec![], 0); + assert!(super::can_step(&app, true), "the edit is a step"); + act(&mut app, &ctx, 0.4, "save").unwrap(); + assert_eq!(group_hex(&app, "B"), Some(vec!["#008000".into(), "#ffff00".into(), "#ffffff".into()])); + assert!(!super::can_step(&app, true) && !super::can_step(&app, false), "Save Changes leaves no step"); + assert_eq!(super::step(&mut app, true).unwrap()["changed"], json!(false)); + + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(group_hex(&app, "B"), Some(vec!["#008000".into(), "#ffff00".into(), "#ffffff".into()]), "OK keeps B's saved colors"); + assert_eq!(group_hex(&app, "A"), Some(vec!["#ff0000".into(), "#00ff00".into()]), "and leaves A as it was"); + } + + /// Without art: rows set after another color group is selected, with no frame between, are a + /// step back to the rows read for that group. + #[test] + fn an_edit_right_after_another_group_is_a_step() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "A", "colors": ["#ff0000", "#00ff00"], "keepModel": true})).unwrap(); + app.run("swatch.newGroup", json!({"name": "B", "colors": ["#0000ff", "#ffff00", "#ffffff"], "keepModel": true})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "A"})).unwrap(); + frame(&mut app, &ctx, 0.0, vec![], 0); + set(&mut app, "group", json!("B")).unwrap(); + assert!(!super::can_step(&app, true) && !super::can_step(&app, false), "another group leaves no step"); + let b = new_colors(&app); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + rs[0]["to"] = json!("rgb 0 0 0"); + d.fields.insert("rows".into(), Value::Array(rs)); + assert!(super::can_step(&app, true), "the edit is a step"); + assert_eq!(super::step(&mut app, true).unwrap()["changed"], json!(true)); + assert_eq!(new_colors(&app), b, "Undo Changes gives back the rows read for B"); + assert_eq!(super::step(&mut app, false).unwrap()["changed"], json!(true)); + assert_eq!(new_colors(&app)[0], json!("rgb 0 0 0"), "Redo Changes gives back the edit"); + } + + /// With art not linked to the group: Save Changes with the rows as the last Save Changes left + /// them, after an edit and Undo Changes, leaves Redo Changes no step to go to either. + #[test] + fn an_unchanged_save_changes_leaves_nothing_to_redo() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + let (red, blue) = (square(&mut app, 10.0, "#ff0000"), square(&mut app, 40.0, "#0000ff")); + app.run("swatch.newGroup", json!({"name": "Plain", "colors": ["#ff0000", "#0000ff"], "keepModel": true})).unwrap(); + app.run("select.set", json!({"ids": [red, blue]})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Plain"})).unwrap(); + frame(&mut app, &ctx, 0.0, vec![], 0); + let edit = |app: &mut VectorcraftApp, to: &str| { + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + rs[0]["to"] = json!(to); + d.fields.insert("rows".into(), Value::Array(rs)); + }; + edit(&mut app, "rgb 0 128 0"); + frame(&mut app, &ctx, 0.1, vec![], 0); + act(&mut app, &ctx, 0.2, "save").unwrap(); + assert!(app.ui.dialog.as_ref().unwrap().fields.contains_key(SAVED_ROWS), "the art kept its colors"); + edit(&mut app, "rgb 0 0 0"); + frame(&mut app, &ctx, 0.3, vec![], 0); + assert_eq!(super::step(&mut app, true).unwrap()["changed"], json!(true)); + assert!(unchanged_since_save(app.ui.dialog.as_ref().unwrap()), "the rows are as saved"); + assert!(super::can_step(&app, false), "the edit can be redone"); + act(&mut app, &ctx, 0.4, "save").unwrap(); + assert!(!super::can_step(&app, true) && !super::can_step(&app, false), "Save Changes leaves no step"); + } + /// Without art: after a group is picked in the list, the same Color Theme Picker picks that gave /// the group before it its colors give the new group's rows the palette of the art picked too. #[test] @@ -3619,13 +3976,17 @@ mod tests { let undo = undo_len(&app); let d = app.ui.dialog.as_mut().unwrap(); let mut rs = super::rows(d); - rs[0]["to"] = json!("rgb 0 0 0"); + let row_of = |rs: &[Value], hex: &str| rs.iter().position(|r| super::from_colors(r).iter().any(|c| c.to_hex() == hex)).unwrap(); + let red_row = row_of(&rs, "#ff0000"); + rs[red_row]["to"] = json!("rgb 0 0 0"); + let blue_to = super::to_color(&rs[row_of(&rs, "#0000ff")]).unwrap().to_hex(); d.fields.insert("rows".into(), Value::Array(rs)); frame(&mut app, &ctx, 0.1, vec![], 0); assert!(app.session.in_interaction(), "the art previews"); let previewed = app.session.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Mixed").map(|g| g.swatches.clone()); assert_eq!(previewed.as_ref().map(Vec::len), Some(3), "the preview's rewrite of the group keeps its other swatch"); assert_eq!(previewed.and_then(|s| s.last().cloned()), Some(fade_swatch()), "with its paint"); + assert_eq!(group_hex(&app, "Mixed"), Some(vec!["#000000".into(), blue_to]), "each color swatch takes its row's new color"); let refused: Result<(), String> = Err("color group `Mixed` holds swatches that are not colors, which Save Changes can't keep".into()); assert_eq!(act(&mut app, &ctx, 0.2, "save"), refused); crate::dialogs::cancel(&mut app); diff --git a/crates/ui-egui/src/dialogs/revolve.rs b/crates/ui-egui/src/dialogs/revolve.rs index c7c98a5de0..1812f41d42 100644 --- a/crates/ui-egui/src/dialogs/revolve.rs +++ b/crates/ui-egui/src/dialogs/revolve.rs @@ -37,12 +37,19 @@ pub(super) fn body(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { let id = d.str("__effect"); let defaults = vectorcraft_effects::default_params(&id).unwrap_or(json!({})); - // Reset all resets the shape, view and light; the mapped graphics and the render - // settings stay. + // Reset all resets the shape, view and light; the mapped graphics, Map Art with its + // options and the render settings stay. let defaults = match defaults { Value::Object(mut m) => { - m.remove(vectorcraft_effects::GRAPHICS); - m.remove(vectorcraft_effects::RENDER); + for key in [ + vectorcraft_effects::GRAPHICS, + vectorcraft_effects::RENDER, + vectorcraft_effects::MAP_ART, + vectorcraft_effects::MAP_SHADE, + vectorcraft_effects::MAP_INVISIBLE, + ] { + m.remove(key); + } Value::Object(m) } other => other, @@ -175,6 +182,11 @@ pub(super) fn c3(s: &'static str) -> &'static str { /// first two, the light gizmo on Lighting. fn solid_controls(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, id: &str) { let classic = vectorcraft_effects::is_classic_three_d(id); + // Map Art takes the place of the tabs until its Done. + if classic && super::three_d_classic::map_art_open(d) { + super::three_d_classic::map_art_controls(app, ui, d); + return; + } let object = id == EXTRUDE || id == INFLATE || id == CLASSIC_EXTRUDE || id == CLASSIC_REVOLVE; let mut tabs = vec![]; if object { diff --git a/crates/ui-egui/src/dialogs/revolve/tests.rs b/crates/ui-egui/src/dialogs/revolve/tests.rs index 223c617981..dd5f05ad5d 100644 --- a/crates/ui-egui/src/dialogs/revolve/tests.rs +++ b/crates/ui-egui/src/dialogs/revolve/tests.rs @@ -106,6 +106,83 @@ fn button(pos: Pos2, pressed: bool) -> Event { Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Default::default() } } +#[test] +fn map_art_maps_a_symbol_onto_a_surface_of_extrude_and_bevel_classic() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width":300,"height":300})).unwrap(); + let mark = app.run("path.create", json!({"d":"M250 250L260 250L260 270L250 270Z"})).unwrap()["id"].clone(); + app.run("threeD.addGraphic", json!({"name":"Mark","ids":[mark]})).unwrap(); + app.run("path.create", json!({"d":"M50 50L150 50L150 150L50 150Z"})).unwrap(); + app.run("effect.dialog", json!({"effect":CLASSIC_EXTRUDE,"item":null})).unwrap(); + let ctx = egui::Context::default(); + theme::install_fonts(&ctx); + theme::apply(&ctx, Default::default()); + let mut h = Harness { app, ctx, screen: vec2(1280.0, 900.0), texts: vec![] }; + h.settle(); + h.click(h.rect("Map Art…").center()); + assert!(h.app.ui.dialog.as_ref().unwrap().bool("__mapArt"), "Map Art… opens Map Art"); + let count: usize = h.texts.iter().find_map(|(s, _)| s.strip_prefix("/ ")).and_then(|n| n.parse().ok()).expect("the surface count"); + assert!(count >= 6, "a square's solid has at least six surfaces: {count}"); + // The Symbol menu maps the symbol onto the surface shown, the first. + h.click(h.rect("None").center()); + h.click(h.rect("Mark").center()); + let maps = |h: &Harness| vectorcraft_effects::surface_maps(&json!({"mapArt": h.app.ui.dialog.as_ref().unwrap().fields.get("mapArt").cloned()})); + assert_eq!(maps(&h).iter().map(|m| (m.surface, m.symbol.as_str(), m.scale_x)).collect::>(), [(1, "Mark", 100.0)]); + // The next surface has no map until it is given one; Scale to Fit fills the first. + h.click(h.rect(">").center()); + assert_eq!(h.value("__mapSurface"), 2.0); + assert_eq!(maps(&h).len(), 1); + h.click(h.rect("<").center()); + h.click(h.rect("Scale to Fit").center()); + assert!(maps(&h)[0].scale_x > 100.0, "the 10-point art is scaled up to the 100-point cap: {:?}", maps(&h)); + h.click(h.rect("Done").center()); + assert!(!h.app.ui.dialog.as_ref().unwrap().bool("__mapArt"), "Done goes back to the effect's options"); + dialogs::confirm(&mut h.app).unwrap(); + let state = h.app.session.doc().unwrap(); + let id = state.selection.objects[0]; + let params = &state.doc.node(id).unwrap().appearance.effects[0].params; + assert_eq!(vectorcraft_effects::surface_maps(params).len(), 1, "{params}"); + assert!(params.get("__mapArt").is_none() && params.get("__mapSurface").is_none(), "the dialog's own state stays out of the effect"); +} + +#[test] +fn map_art_maps_no_more_surfaces_than_an_object_takes() { + let max = vectorcraft_effects::MAX_MAPS; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width":300,"height":300})).unwrap(); + let mark = app.run("path.create", json!({"d":"M250 250L260 250L260 270L250 270Z"})).unwrap()["id"].clone(); + app.run("threeD.addGraphic", json!({"name":"Mark","ids":[mark]})).unwrap(); + // A star with 36 points has 72 corners, so its solid has two caps and 72 walls. + let corners: Vec = (0..72) + .map(|i| { + let (r, a) = (if i % 2 == 0 { 100.0 } else { 60.0 }, f64::from(i) * std::f64::consts::TAU / 72.0); + format!("{:.3} {:.3}", 150.0 + r * a.cos(), 150.0 + r * a.sin()) + }) + .collect(); + app.run("path.create", json!({"d": format!("M{}Z", corners.join(" L"))})).unwrap(); + app.run("effect.dialog", json!({"effect":CLASSIC_EXTRUDE,"item":null})).unwrap(); + let ctx = egui::Context::default(); + theme::install_fonts(&ctx); + theme::apply(&ctx, Default::default()); + let mut h = Harness { app, ctx, screen: vec2(1280.0, 900.0), texts: vec![] }; + h.settle(); + h.click(h.rect("Map Art…").center()); + let count: usize = h.texts.iter().find_map(|(s, _)| s.strip_prefix("/ ")).and_then(|n| n.parse().ok()).expect("the surface count"); + assert!(count > max, "{count} surfaces"); + // Every map the object takes is used, and the surface shown has none. + let full: Vec = (1..=max).map(|surface| json!({"surface": surface, "symbol": "Mark"})).collect(); + let d = h.app.ui.dialog.as_mut().unwrap(); + d.fields.insert("mapArt".into(), json!(full)); + d.fields.insert("__mapSurface".into(), json!(max + 1)); + h.settle(); + h.click(h.rect("None").center()); + if h.texts.iter().any(|(s, _)| s == "Mark") { + h.click(h.rect("Mark").center()); + } + let raw = h.app.ui.dialog.as_ref().unwrap().fields.get("mapArt").cloned().unwrap_or_default(); + assert_eq!(raw.as_array().map(Vec::len), Some(max), "no map past the limit is written"); +} + #[test] fn values_labels_sliders_and_reset_dots_change_the_live_effect_in_one_undo_step() { let mut h = Harness::new(vec2(1280.0, 900.0)); @@ -694,6 +771,27 @@ fn every_3d_dialog_has_color_and_reset_all_restores_white() { } } +#[test] +fn reset_all_keeps_map_art_and_its_options() { + for effect in [CLASSIC_EXTRUDE, CLASSIC_REVOLVE] { + let mut h = Harness::with("M100 100L200 100L200 200L100 200Z", effect, vec2(1280.0, 900.0)); + h.settle(); + let maps = json!([{"surface": 1, "symbol": "Mark"}]); + let d = h.app.ui.dialog.as_mut().unwrap(); + d.fields.insert("mapArt".into(), maps.clone()); + d.fields.insert("mapShade".into(), json!(true)); + d.fields.insert("mapInvisible".into(), json!(true)); + d.fields.insert("rotationX".into(), json!(40.0)); + h.settle(); + h.click(h.response("revolve-reset-all").center()); + let d = h.app.ui.dialog.as_ref().unwrap(); + assert_eq!(d.f64("rotationX", 0.0), -21.88, "{effect}: the view is reset"); + assert_eq!(d.fields.get("mapArt"), Some(&maps), "{effect}: the maps stay"); + assert!(d.bool("mapShade") && d.bool("mapInvisible"), "{effect}: Shade Artwork and Invisible Geometry stay"); + dialogs::cancel(&mut h.app); + } +} + #[test] fn light_list_add_select_edit_delete_and_reset_keep_each_light_independent() { for effect in [REVOLVE, EXTRUDE, INFLATE, vectorcraft_effects::ROTATE] { diff --git a/crates/ui-egui/src/dialogs/save_pdf.rs b/crates/ui-egui/src/dialogs/save_pdf.rs index 85ff601db0..a8db555bfb 100644 --- a/crates/ui-egui/src/dialogs/save_pdf.rs +++ b/crates/ui-egui/src/dialogs/save_pdf.rs @@ -4,7 +4,8 @@ //! The fields are the `document.exportPdf` options (sections are objects such as `compression`), //! plus `preset`, `range`, `path?` and UI-only `__` keys, so agents fill the dialog with //! `ui.dialog.set`. OK runs `document.exportPdf` through [`io::export_pdf`]; the Summary is -//! `document.pdfSettings`. Save Preset… names the settings as a preset (`pdf.preset.save`). +//! `document.pdfSettings`, and its Save Summary… writes it to a text file (`ui.pdfSummary.save`). +//! Save Preset… names the settings as a preset (`pdf.preset.save`). //! Opened from Export As with Use Artboards off (`__artBounds`), the dialog has no Artboards //! section, and OK writes one page of the visible art's bounds through [`io::export`]; opened //! from Export Selection (`__selection` too), the page is the selection's crop. While Alt (Option @@ -18,8 +19,8 @@ use std::sync::LazyLock; use serde_json::{Map, Value, json}; use vectorcraft_doc::Unit; -use vectorcraft_engine::cmd::FlattenOptions; use vectorcraft_engine::cmd::fileio::{SaveMode, pdf}; +use vectorcraft_engine::cmd::{FlattenOptions, FlattenerPreset}; use vectorcraft_pdf::{ Changes, Choice, ColorConversion, Compatibility, Downsample, Encryption, ImageCodec, JpegQuality, MarkKind, MonoCodec, Overprint, PdfSettings, Printing, ProfileInclusion, Standard, @@ -37,11 +38,22 @@ pub(super) const SPEC: DialogSpec = DialogSpec { body, confirm, ok: Some("Save PDF"), - inputs: |_| &["path"], + inputs: |_| &["path", "flattener"], reset: Some(reset), ..DialogSpec::FORM }; +/// Custom Transparency Flattener Options, opened over Save PDF by Custom… beside Flattener preset. +pub(super) const CUSTOM_KIND: &str = "pdfFlattenerOptions"; + +pub(super) const CUSTOM_SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("Custom Transparency Flattener Options").into(), + body: custom_body, + confirm: custom_confirm, + min_width: 420.0, + ..DialogSpec::FORM +}; + /// The dialog kind of the preset editor (New / Edit in Edit → PDF Presets). pub(super) const PRESET_KIND: &str = "pdfPreset"; @@ -99,6 +111,19 @@ pub fn open(app: &mut VectorcraftApp, params: &Value) -> Result { Some(v) => return Err(format!("useArtboards must be true or false, not {v}")), }; let mut fields = settings_fields(app, params)?; + // The PDF settings keep no flattener options: those asked for go over the flattener preset. + match params.get("flattener") { + None | Some(Value::Null) => {} + Some(f @ Value::Object(o)) => { + let known = serde_json::to_value(FlattenOptions::default()).unwrap_or_default(); + if let Some(k) = o.keys().find(|k| known.get(k.as_str()).is_none()) { + return Err(format!("flattener.{k} is not a flattener option")); + } + FlattenOptions::for_export(None, Some(f), &[]).map_err(|e| format!("flattener: {e}"))?; + fields.insert("flattener".into(), f.clone()); + } + Some(v) => return Err(format!("flattener must be an object of flattener options, not {v}")), + } let s = |k: &str| params.get(k).and_then(Value::as_str); fields.insert("preset".into(), json!(s("preset").unwrap_or(pdf::DEFAULT_PRESET))); fields.insert("__presets".into(), json!(pdf::presets(&app.session))); @@ -534,6 +559,10 @@ fn preset_rows(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { d.fields.remove(SAVE_AS); } }); + // `pdf.preset.save` keeps `flattenerPreset` but not `flattener`. + if d.fields.contains_key("flattener") { + note(ui, tl!("The PDF preset keeps the flattener preset but not the Custom… settings.")); + } } } @@ -771,7 +800,8 @@ fn edit_bleed(d: &mut Dialog, side: usize, value: f64) { /// `ui.dialog.set` set `field` of Save PDF or the PDF preset editor: `__bleedLinked` links or /// unlinks the bleed as its button does, and must be true or false; every write of `bleed`, the -/// same values included, drops the link's state, so the link follows the values set. +/// same values included, drops the link's state, so the link follows the values set. A flattener +/// preset set there drops the Custom… options, as choosing it in the dropdown does. pub(super) fn field_set(d: &mut Dialog, field: &str) -> Result<(), String> { match field { BLEED_LINKED => match d.fields.get(BLEED_LINKED).cloned() { @@ -785,6 +815,10 @@ pub(super) fn field_set(d: &mut Dialog, field: &str) -> Result<(), String> { d.fields.remove(BLEED_LINKED); Ok(()) } + "flattenerPreset" => { + d.fields.remove("flattener"); + Ok(()) + } _ => Ok(()), } } @@ -862,6 +896,103 @@ fn output(ui: &mut egui::Ui, d: &mut Dialog) { } } +/// The name of the flattener preset Save PDF `d` flattens with: its `flattenerPreset` (High +/// Resolution when empty), a built-in one named by id (`high`) as its name. +fn flattener_name(d: &Dialog) -> String { + let name = get(d, "flattenerPreset").as_str().map(str::trim).filter(|n| !n.is_empty()).unwrap_or(pdf::DEFAULT_FLATTENER); + FlattenOptions::preset_label(&name.to_ascii_lowercase()).unwrap_or(name).to_string() +} + +/// The flattener options Save PDF `d` flattens with: its preset, with the Custom… options over it. +fn flattener(d: &Dialog, saved: &[FlattenerPreset]) -> Result { + FlattenOptions::for_export(Some(&flattener_name(d)), d.fields.get("flattener"), saved) +} + +/// The switches the PDF 1.3 writer sets itself, which Custom Transparency Flattener Options show +/// but can't change: rasterized areas are always clipped to their regions and keep no alpha, and +/// overprints are kept only with Overprint set to Preserve. +const FIXED: [&str; 3] = ["clipComplexRegions", "preserveAlpha", "preserveOverprints"]; + +/// `o` as the PDF 1.3 writer flattens with it (see [`FIXED`]), for Save PDF `parent`. +fn as_written(o: &mut FlattenOptions, parent: &Dialog) { + o.clip_complex_regions = true; + o.preserve_alpha = false; + o.preserve_overprints &= choice::(parent, "advanced.overprint") != Some(Overprint::Discard); +} + +/// Custom Transparency Flattener Options over Save PDF `parent`, on the options it flattens with +/// (the default preset's while those are not valid). +pub(super) fn over(parent: &Dialog, saved: &[FlattenerPreset]) -> Dialog { + let mut o = flattener(parent, saved).unwrap_or_else(|_| FlattenOptions::preset(pdf::DEFAULT_FLATTENER).unwrap_or_default()); + let kept = o.preserve_overprints; + as_written(&mut o, parent); + let mut d = Dialog::new(CUSTOM_KIND, json!({})); + super::flatten::put_options(&mut d.fields, &o); + d.fields.insert(KEPT_OVERPRINTS.into(), json!(kept)); + d.fields.insert(super::PARENT.into(), serde_json::to_value(parent).unwrap_or_default()); + d +} + +/// The `preserveOverprints` value of the options Custom Transparency Flattener Options opened on, +/// before Overprint applies to it. +const KEPT_OVERPRINTS: &str = "__keptOverprints"; + +/// The options Custom Transparency Flattener Options `d` holds. +fn custom_options(d: &Dialog) -> Result { + FlattenOptions::from_params_with(&Value::Object(d.fields.clone()), &[]) +} + +/// The flattener options, with the switches of [`FIXED`] showing what the PDF 1.3 writer does. +fn custom_body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + let current = custom_options(d); + // Values refused stay as entered, so that changing another option keeps them. + let (mut o, unread) = super::flatten::shown_options(&d.fields, ¤t); + if let Some(parent) = super::parent(d) { + as_written(&mut o, &parent); + } + super::flatten::fields_editor(ui, "pdf-flattener", &mut d.fields, &mut o, &unread, &FIXED); + if let Err(e) = ¤t { + ui.label(egui::RichText::new(e).color(Tokens::get(ui.ctx()).text_dim).size(11.5)); + } + ui.add_space(8.0); + form::caption(ui, tl!("PDF 1.3 files clip rasterized areas to their regions, and Overprint sets whether overprints are kept.")); + false +} + +/// OK: Save PDF again, flattening with these options over its preset (High Resolution when a saved +/// preset was deleted meanwhile). Options equal to the preset's leave the preset alone; bad options +/// keep the dialog open. +fn custom_confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let mut o = custom_options(d)?; + let mut parent = super::parent(d).ok_or("the dialog it was opened over is no longer open")?; + let kept = d + .fields + .get(KEPT_OVERPRINTS) + .and_then(Value::as_bool) + .or_else(|| flattener(&parent, &app.session.prefs.flattener_presets).ok().map(|before| before.preserve_overprints)); + let base = match FlattenOptions::find_preset(&flattener_name(&parent), &app.session.prefs.flattener_presets) { + Some(base) => base, + None => { + set(&mut parent, "flattenerPreset", json!("")); + FlattenOptions::preset(pdf::DEFAULT_FLATTENER).unwrap_or_default() + } + }; + // The writer sets the first two itself, so they take the preset's values: options that + // otherwise match the preset leave its name showing. The writer keeps overprints only where the + // options and Overprint both keep them, so the options keep the value they opened with, even + // when their preset was deleted, changed or made again under its name meanwhile. + o.clip_complex_regions = base.clip_complex_regions; + o.preserve_alpha = base.preserve_alpha; + o.preserve_overprints = kept.unwrap_or(o.preserve_overprints); + if o == base { + parent.fields.remove("flattener"); + } else { + parent.fields.insert("flattener".into(), serde_json::to_value(&o).map_err(|e| e.to_string())?); + } + app.ui.dialog = Some(parent); + Ok(Value::Null) +} + fn advanced(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { heading(ui, tl!("Fonts")); let outline = get(d, "advanced.outlineText").as_bool() == Some(true); @@ -879,17 +1010,24 @@ fn advanced(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { || choice::(d, "standard").is_some_and(Standard::flattens); row(ui, tl!("Flattener preset:"), |ui| { let presets = app.session.flattener_presets(); - let names: Vec<&str> = presets.iter().map(|p| p.name.as_str()).collect(); - // The built-in presets come first (translated); the saved ones are names. - let builtins = names.len().saturating_sub(app.session.prefs.flattener_presets.len()); - let name = get(d, "flattenerPreset").as_str().map(str::trim).filter(|n| !n.is_empty()).unwrap_or(pdf::DEFAULT_FLATTENER); - // A built-in preset named by id (`high`) shows as its name. - let current = FlattenOptions::preset_label(&name.to_ascii_lowercase()).unwrap_or(name).to_string(); + let saved = &app.session.prefs.flattener_presets; + // [Custom] while Custom… options differ from the preset's. + let current = flattener(d, saved).ok(); + // The preset as the list names it: the export finds a name in any case. + let name = flattener_name(d); + let name = presets.iter().find(|p| p.name.eq_ignore_ascii_case(name.trim())).map_or(name.as_str(), |p| p.name.as_str()); + let mut custom = false; ui.add_enabled_ui(flat, |ui| { - if let Some(n) = super::mixed_dropdown(ui, "flattenerPreset", ¤t, &names, 200.0, |k| k < builtins).and_then(|i| names.get(i)) { - set(d, "flattenerPreset", json!(n)); + if let Some(p) = super::flatten::preset_dropdown(ui, "flattenerPreset", &presets, name, current.as_ref(), 200.0) { + set(d, "flattenerPreset", json!(p.name)); + d.fields.remove("flattener"); } + // PDF presets keep no custom flattener options, so the preset editor has no Custom…. + custom = d.kind == KIND && widgets::flat_button_fit(ui, tl!("Custom…"), 72.0).clicked(); }); + if custom { + *d = over(d, saved); + } }); if flat { let name = get(d, "flattenerPreset").as_str().map(str::trim).filter(|n| !n.is_empty()).unwrap_or(pdf::DEFAULT_FLATTENER); @@ -992,26 +1130,57 @@ pub(super) fn option_label(option: &str) -> String { } /// `document.pdfSettings` for the dialog with the document's warnings (an export in memory), -/// cached until a field or the document changes. +/// cached until a field, the document, the saved PDF or flattener presets, the loaded color +/// profiles or the available fonts change. fn summary_of(app: &mut VectorcraftApp, ctx: &egui::Context, p: &Value) -> Result { - let revision = app.session.active().map_or(0, |s| s.revision); - let stamp = egui::Id::unique((p.to_string(), revision)); - let key = egui::Id::unique("save-pdf-summary"); + let (key, stamp) = summary_key(app, p); if let Some((s, v)) = ctx.data(|m| m.get_temp::<(egui::Id, Result)>(key)) && s == stamp { return v; } - let mut q = p.clone(); - q["includeDocument"] = json!(true); - let v = app.session.execute("document.pdfSettings", &q).map_err(|e| e.to_string()); + let v = summary_settings(app, p); ctx.data_mut(|m| m.insert_temp(key, (stamp, v.clone()))); v } +/// Where [`summary_of`] keeps the Summary, and the stamp of what it was computed for: the params +/// `p`, the active document and its revision, the saved PDF presets (which `preset` can name), the +/// saved flattener presets (which `flattenerPreset` can name), the loaded color profiles (which +/// `output.destination` and `output.outputIntent` can name) and the available fonts (which decide +/// what is embedded or outlined). +fn summary_key(app: &VectorcraftApp, p: &Value) -> (egui::Id, egui::Id) { + let document = app.session.active().map(|s| (s.uid, s.revision)); + let prefs = &app.session.prefs; + let presets = serde_json::to_string(&(&prefs.pdf_presets, &prefs.flattener_presets)).unwrap_or_default(); + let shared = (vectorcraft_color::cms::profiles_generation(), vectorcraft_text::FontDb::global().generation()); + (egui::Id::unique("save-pdf-summary"), egui::Id::unique((p.to_string(), document, presets, shared))) +} + +/// `document.pdfSettings` for the dialog's `document.exportPdf` params `p`, with the document's +/// warnings (an export in memory). +fn summary_settings(app: &mut VectorcraftApp, p: &Value) -> Result { + let mut q = p.clone(); + q["includeDocument"] = json!(true); + app.session.execute("document.pdfSettings", &q).map_err(|e| e.to_string()) +} + +/// The `document.pdfSettings` params of the Summary: the dialog's export params, without the +/// preset editor's own `name` and `description`, which are not PDF options. +fn summary_params(d: &Dialog) -> Value { + let mut p = params(d); + if d.kind == PRESET_KIND + && let Some(o) = p.as_object_mut() + { + o.remove("name"); + o.remove("description"); + } + p +} + fn summary(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { let t = Tokens::get(ui.ctx()); - let v = match summary_of(app, ui.ctx(), ¶ms(d)) { + let v = match summary_of(app, ui.ctx(), &summary_params(d)) { Ok(v) => v, Err(e) => { heading(ui, tl!("Error")); @@ -1020,31 +1189,145 @@ fn summary(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { } }; heading(ui, tl!("Options")); - let mut changed: Vec<&Value> = v["changed"].as_array().map(|a| a.iter().collect()).unwrap_or_default(); - changed.sort_by_key(|c| section_of(c["option"].as_str().unwrap_or_default())); + let changed = changed_options(&v); if changed.is_empty() { - let base = if d.kind == PRESET_KIND { pdf::DEFAULT_PRESET } else { tl!("the preset") }; - note(ui, &crate::i18n::fmt(tl!("Every option matches {base}."), &[("base", base)])); + note(ui, &unchanged_line(d)); } option_rows(ui, changed, option_label); heading(ui, tl!("Warnings")); warning_rows(ui, v["warnings"].as_array().map(Vec::as_slice).unwrap_or_default()); + ui.add_space(8.0); + if widgets::secondary_button(ui, tl!("Save Summary…")).clicked() { + // The text of the Summary drawn now: saving it does not compute the settings again. + let text = summary_text(d, &v); + if let Err(e) = crate::picks::in_dialog(app, d, move |app, d| save_summary_from_dialog(app, d, &text)) { + app.status(e); + } + } +} + +/// The changed options of `document.pdfSettings`'s reply `v`, in the order of the sections. +fn changed_options(v: &Value) -> Vec<&Value> { + let mut changed: Vec<&Value> = v["changed"].as_array().map(|a| a.iter().collect()).unwrap_or_default(); + changed.sort_by_key(|c| section_of(c["option"].as_str().unwrap_or_default())); + changed +} + +/// The Summary's line when no option differs from the preset. +fn unchanged_line(d: &Dialog) -> String { + let base = if d.kind == PRESET_KIND { pdf::DEFAULT_PRESET } else { tl!("the preset") }; + crate::i18n::fmt(tl!("Every option matches {base}."), &[("base", base)]) +} + +/// The Summary of `document.pdfSettings`'s reply `v` as text, line for line as the section shows +/// it in the interface language: Options and each changed option (or the line saying none +/// changed), a blank line, then Warnings and each warning (or "None."). Lines end in LF, including +/// line breaks inside an option's value. +fn summary_text(d: &Dialog, v: &Value) -> String { + let lang = crate::i18n::current(); + let mut lines = vec![tl!("Options").to_string()]; + let changed = changed_options(v); + if changed.is_empty() { + lines.push(unchanged_line(d)); + } + lines.extend(changed.into_iter().map(|c| option_line(c, option_label))); + lines.push(String::new()); + lines.push(tl!("Warnings").to_string()); + let warnings = v["warnings"].as_array().map(Vec::as_slice).unwrap_or_default(); + if warnings.is_empty() { + lines.push(tl!("None.").to_string()); + } + lines.extend(warnings.iter().map(|w| warning_line(lang, w.as_str().unwrap_or_default()))); + let mut text = lines.join("\n").replace("\r\n", "\n").replace('\r', "\n"); + text.push('\n'); + text +} + +/// The UI command that writes the Summary to a text file. +pub(crate) const SAVE_SUMMARY: &str = "ui.pdfSummary.save"; + +/// Is a dialog with the Summary open (Save PDF, or the preset editor)? +pub(crate) fn summary_open(app: &VectorcraftApp) -> bool { + app.ui.dialog.as_ref().is_some_and(|d| d.kind == KIND || d.kind == PRESET_KIND) +} + +/// `ui.pdfSummary.save {path}`: write the open Save PDF dialog's (or preset editor's) Summary as +/// text to `path` (the web downloads it under the path's file name). The Summary the section last +/// drew for the same fields, document, saved PDF and flattener presets, loaded color profiles +/// and available fonts is used as it is; the settings are computed only when there is none. The dialog stays open and the document is not changed → +/// `{path, bytes}`. A missing, empty or non-string `path` is an error that writes nothing. +pub(crate) fn save_summary(app: &mut VectorcraftApp, p: &Value) -> Result { + let key = "path"; + let path = match p.get(key) { + None | Some(Value::Null) => return Err("missing `path`".into()), + Some(Value::String(s)) if s.trim().is_empty() => return Err("path is empty".into()), + Some(Value::String(s)) => Some(s.clone()), + Some(_) => return Err(format!("`{key}` must be a string")), + }; + let d = app.ui.dialog.clone().filter(|_| summary_open(app)).ok_or("the Save PDF dialog is not open")?; + let p = summary_params(&d); + let v = match app.ui_ctx.clone() { + Some(ctx) => summary_of(app, &ctx, &p), + None => summary_settings(app, &p), + }?; + write_summary(app, path, &summary_text(&d, &v)) +} + +/// Save Summary…: the Summary's `text` to a file picked in a save panel (the web downloads it). A +/// write that fails is told in a message over the dialog, which shows again when it closes; a +/// canceled panel writes nothing. +fn save_summary_from_dialog(app: &mut VectorcraftApp, d: &mut Dialog, text: &str) -> Result<(), String> { + let waiting = app.ui.told.len(); + let r = write_summary(app, None, text); + // The message about a failed write: the open dialog when the panel answered after this frame, + // else waiting behind the dialog being drawn. + let told = app.ui.dialog.take_if(|t| t.kind == super::confirm::MESSAGE).or_else(|| { + (app.ui.told.len() > waiting && app.ui.told.last().is_some_and(|t| t.kind == super::confirm::MESSAGE)).then(|| app.ui.told.pop()).flatten() + }); + if let Some(mut told) = told { + told.fields.insert(super::PARENT.into(), serde_json::to_value(&*d).unwrap_or_default()); + *d = told; + } + match r { + Err(e) if e == "cancelled" => Ok(()), + r => r.map(|_| ()), + } +} + +/// Write the Summary's `text` (UTF-8) to `path`, else to a picked ` PDF Summary.txt` +/// next to the document → `{path, bytes}`. +fn write_summary(app: &mut VectorcraftApp, path: Option, text: &str) -> Result { + let title = app.session.active().map(|d| d.title()).unwrap_or_default(); + let stem = std::path::Path::new(&title).file_stem().map_or_else(|| "Untitled".into(), |s| s.to_string_lossy().into_owned()); + let path = io::write_named(app, path, &format!("{stem} PDF Summary.txt"), text.as_bytes())?; + app.status(format!("Saved {path}")); + Ok(json!({ "path": path, "bytes": text.len() })) } /// A Summary line per changed option (`{option, value}`), labelled by `label`. pub(super) fn option_rows<'a>(ui: &mut egui::Ui, changed: impl IntoIterator, label: impl Fn(&str) -> String) { let t = Tokens::get(ui.ctx()); for c in changed { - let value = match &c["value"] { - Value::Bool(b) => if *b { tl!("On") } else { tl!("Off") }.to_string(), - Value::String(s) if c["option"] == "marks.kind" => choice_label(crate::i18n::current(), "marks.kind", s).to_string(), - Value::String(s) => s.clone(), - other => other.to_string(), - }; - ui.label(egui::RichText::new(format!("{} {value}", crate::i18n::colon(&label(c["option"].as_str().unwrap_or_default())))).color(t.text)); + ui.label(egui::RichText::new(option_line(c, &label)).color(t.text)); } } +/// The displayed value of the changed option `c` (`{option, value}`). +fn option_value(c: &Value) -> String { + match &c["value"] { + Value::Bool(b) => if *b { tl!("On") } else { tl!("Off") }.to_string(), + Value::String(s) if c["option"] == "marks.kind" => choice_label(crate::i18n::current(), "marks.kind", s).to_string(), + Value::String(s) => s.clone(), + other => other.to_string(), + } +} + +/// The Summary's line for the changed option `c` (`{option, value}`), labeled by `label`, with the +/// colon the interface language writes. +fn option_line(c: &Value, label: impl Fn(&str) -> String) -> String { + format!("{} {}", crate::i18n::colon(&label(c["option"].as_str().unwrap_or_default())), option_value(c)) +} + /// The Summary's warnings ("None." without any). pub(super) fn warning_rows(ui: &mut egui::Ui, warnings: &[Value]) { let t = Tokens::get(ui.ctx()); diff --git a/crates/ui-egui/src/dialogs/save_pdf/tests.rs b/crates/ui-egui/src/dialogs/save_pdf/tests.rs index 1f04c8c912..501aed4ed0 100644 --- a/crates/ui-egui/src/dialogs/save_pdf/tests.rs +++ b/crates/ui-egui/src/dialogs/save_pdf/tests.rs @@ -68,6 +68,372 @@ fn every_section_draws() { assert!(warnings.len() == 1 && warnings[0].as_str().unwrap().contains("permissions"), "{warnings:?}"); } +/// `ui.pdfSummary.save` writes the Summary as the section shows it, as UTF-8 text with LF line +/// endings: Options with each changed option in the order of the sections, a blank line, then +/// Warnings. The dialog stays open and the document does not change. +#[test] +fn save_summary_writes_the_summary_as_text() { + let (mut app, written, _) = app(); + app.run("file.export.pdf", json!({})).unwrap(); + set_field(&mut app, "thumbnails", json!(true)); + set_field(&mut app, "security.printing", json!("low")); + let revision = app.session.active().unwrap().revision; + let r = app.run(SAVE_SUMMARY, json!({"path": "/tmp/Ünïcode (1) summary.txt"})).unwrap(); + assert_eq!(r["path"], "/tmp/Ünïcode (1) summary.txt", "the path is used as given"); + let w = written.borrow(); + assert_eq!(w.len(), 1); + assert_eq!(w[0].0, "/tmp/Ünïcode (1) summary.txt"); + assert_eq!(r["bytes"], w[0].1.len()); + let text = String::from_utf8(w[0].1.clone()).expect("UTF-8"); + assert!(!text.contains('\r') && text.ends_with('\n'), "LF line endings: {text:?}"); + let lines: Vec<&str> = text.lines().collect(); + assert_eq!(lines[..5], ["Options", "General › Thumbnails: On", "Security › Printing: low", "", "Warnings"], "{text}"); + assert!(lines.len() == 6 && lines[5].starts_with("⚠ ") && lines[5].contains("permissions"), "{text}"); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(KIND), "the dialog stays open"); + assert_eq!(app.session.active().unwrap().revision, revision, "the document does not change"); + assert_eq!(app.ui.status, "Saved /tmp/Ünïcode (1) summary.txt"); +} + +/// A text option whose value holds CRLF or CR line breaks is written with LF line breaks, so the +/// file has one kind of line ending. +#[test] +fn save_summary_writes_line_breaks_in_values_as_lf() { + let (mut app, written, _) = app(); + app.run("file.export.pdf", json!({})).unwrap(); + set_field(&mut app, "output.outputCondition", json!("first\r\nsecond\rthird")); + app.run(SAVE_SUMMARY, json!({"path": "/tmp/summary.txt"})).unwrap(); + let text = String::from_utf8(written.borrow()[0].1.clone()).unwrap(); + assert!(!text.contains('\r'), "LF line endings: {text:?}"); + assert!(text.contains("first\nsecond\nthird\n"), "{text:?}"); +} + +/// With every option as the preset has it and nothing to warn about, the file holds the lines +/// that say so, in the interface language. +#[test] +fn save_summary_writes_the_lines_for_no_changes_and_no_warnings() { + let (mut app, written, _) = app(); + app.run("file.export.pdf", json!({})).unwrap(); + app.run(SAVE_SUMMARY, json!({"path": "/tmp/summary.txt"})).unwrap(); + let text = String::from_utf8(written.borrow()[0].1.clone()).unwrap(); + assert_eq!(text, "Options\nEvery option matches the preset.\n\nWarnings\nNone.\n"); + crate::i18n::set_current(crate::i18n::Lang::from_code("de").expect("de registered")); + let r = app.run(SAVE_SUMMARY, json!({"path": "/tmp/zusammenfassung.txt"})); + crate::i18n::set_current(crate::i18n::Lang::EN); + r.unwrap(); + let de = String::from_utf8(written.borrow()[1].1.clone()).unwrap(); + let de_lang = crate::i18n::Lang::from_code("de").unwrap(); + let expected = format!( + "{}\n{}\n\n{}\n{}\n", + crate::i18n::tr(de_lang, "Options"), + crate::i18n::fmt(crate::i18n::tr(de_lang, "Every option matches {base}."), &[("base", crate::i18n::tr(de_lang, "the preset"))]), + crate::i18n::tr(de_lang, "Warnings"), + crate::i18n::tr(de_lang, "None."), + ); + assert_eq!(de, expected); + assert_ne!(de, text, "the labels are translated"); +} + +/// The preset editor's Summary is saved too, measured against the app's default preset, and the +/// editor stays open. +#[test] +fn save_summary_writes_the_preset_editors_summary() { + let (mut app, written, _) = app(); + open_preset(&mut app, &json!({})).unwrap(); + set_field(&mut app, "thumbnails", json!(true)); + app.run(SAVE_SUMMARY, json!({"path": "/tmp/preset summary.txt"})).unwrap(); + let text = String::from_utf8(written.borrow()[0].1.clone()).unwrap(); + assert_eq!(text, "Options\nGeneral › Thumbnails: On\n\nWarnings\nNone.\n"); + set_field(&mut app, "thumbnails", json!(false)); + app.run(SAVE_SUMMARY, json!({"path": "/tmp/preset summary.txt"})).unwrap(); + let text = String::from_utf8(written.borrow()[1].1.clone()).unwrap(); + assert_eq!(text, format!("Options\nEvery option matches {}.\n\nWarnings\nNone.\n", pdf::DEFAULT_PRESET)); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(PRESET_KIND), "the editor stays open"); +} + +/// A path that is empty or not a string, and no Save PDF dialog open, are errors that write +/// nothing. +#[test] +fn save_summary_refuses_a_bad_path_and_a_closed_dialog() { + let (mut app, written, _) = app(); + assert_eq!(app.run(SAVE_SUMMARY, json!({"path": "/tmp/s.txt"})).unwrap_err(), "the Save PDF dialog is not open"); + app.run("file.export.pdf", json!({})).unwrap(); + assert_eq!(app.run(SAVE_SUMMARY, json!({"path": ""})).unwrap_err(), "path is empty"); + assert_eq!(app.run(SAVE_SUMMARY, json!({"path": " "})).unwrap_err(), "path is empty"); + assert_eq!(app.run(SAVE_SUMMARY, json!({"path": 5})).unwrap_err(), "`path` must be a string"); + assert!(written.borrow().is_empty()); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(KIND)); +} + +/// The command needs a path: omitted or null, it is an error that shows no save panel and writes +/// nothing. +#[test] +fn save_summary_requires_a_path() { + let (mut app, written, _) = app(); + let asked: Rc> = Rc::default(); + let a = asked.clone(); + app.services.pick_save = Some(Box::new(move |pick: &crate::FilePick| { + *a.borrow_mut() += 1; + Some(format!("/tmp/{}", pick.name)) + })); + app.run("file.export.pdf", json!({})).unwrap(); + assert_eq!(app.run(SAVE_SUMMARY, json!({})).unwrap_err(), "missing `path`"); + assert_eq!(app.run(SAVE_SUMMARY, json!({"path": null})).unwrap_err(), "missing `path`"); + assert_eq!(*asked.borrow(), 0, "no save panel"); + assert!(written.borrow().is_empty()); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(KIND)); +} + +/// The command uses the Summary the section drew for the same fields and document, without +/// computing the settings again (an export in memory), and computes them once a field changes. +#[test] +fn save_summary_uses_the_summary_the_section_drew() { + let (mut app, written, _) = app(); + app.run("file.export.pdf", json!({})).unwrap(); + set_field(&mut app, "__section", json!("Summary")); + let ctx = egui::Context::default(); + theme::install_fonts(&ctx); + app.ui_ctx = Some(ctx.clone()); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| super::super::show(&mut app, ui.ctx())); + out.textures_delta.clear(); + // The drawn Summary, replaced with one that no computation gives. + let (key, stamp) = summary_key(&app, ¶ms(app.ui.dialog.as_ref().unwrap())); + let drawn = ctx.data(|m| m.get_temp::<(egui::Id, Result)>(key)).expect("the section's Summary"); + assert_eq!(drawn.0, stamp, "drawn for these fields"); + let kept: Result = Ok(json!({"changed": [{"option": "thumbnails", "value": "kept"}], "warnings": []})); + ctx.data_mut(|m| m.insert_temp(key, (stamp, kept))); + app.run(SAVE_SUMMARY, json!({"path": "/tmp/a.txt"})).unwrap(); + let text = String::from_utf8(written.borrow()[0].1.clone()).unwrap(); + assert_eq!(text, "Options\nGeneral › Thumbnails: kept\n\nWarnings\nNone.\n"); + set_field(&mut app, "thumbnails", json!(true)); + app.run(SAVE_SUMMARY, json!({"path": "/tmp/b.txt"})).unwrap(); + let text = String::from_utf8(written.borrow()[1].1.clone()).unwrap(); + assert!(text.starts_with("Options\nGeneral › Thumbnails: On\n"), "computed for the changed field: {text}"); +} + +/// The Summary drawn for one document is not used for another that becomes active with the same +/// revision and the same fields. +#[test] +fn save_summary_does_not_use_another_documents_summary() { + let (mut app, written, _) = app(); + let first = app.session.active_index().unwrap(); + let revision = app.session.active().unwrap().revision; + app.run("file.new", json!({"width": 120, "height": 90})).unwrap(); + let second = app.session.active_index().unwrap(); + app.session.set_active(first); + app.run("file.export.pdf", json!({})).unwrap(); + let ctx = egui::Context::default(); + app.ui_ctx = Some(ctx.clone()); + let (key, stamp) = summary_key(&app, ¶ms(app.ui.dialog.as_ref().unwrap())); + let kept: Result = Ok(json!({"changed": [{"option": "thumbnails", "value": "kept"}], "warnings": []})); + ctx.data_mut(|m| m.insert_temp(key, (stamp, kept))); + app.session.set_active(second); + app.session.active_mut().unwrap().revision = revision; + app.run(SAVE_SUMMARY, json!({"path": "/tmp/a.txt"})).unwrap(); + let text = String::from_utf8(written.borrow()[0].1.clone()).unwrap(); + assert!(!text.contains("kept"), "the other document's Summary: {text}"); +} + +/// The Summary is computed again when the saved preset it compares against is replaced while the +/// dialog stays open. +#[test] +fn save_summary_compares_against_a_replaced_preset() { + let (mut app, written, _) = app(); + app.run("pdf.preset.save", json!({"name": "Mine", "thumbnails": true})).unwrap(); + app.run("ui.savePdfDialog", json!({"preset": "Mine"})).unwrap(); + set_field(&mut app, "thumbnails", json!(false)); + app.ui_ctx = Some(egui::Context::default()); + app.run(SAVE_SUMMARY, json!({"path": "/tmp/a.txt"})).unwrap(); + let text = String::from_utf8(written.borrow()[0].1.clone()).unwrap(); + assert!(text.starts_with("Options\nGeneral › Thumbnails: Off\n"), "{text}"); + app.run("pdf.preset.save", json!({"name": "Mine", "thumbnails": false})).unwrap(); + app.run(SAVE_SUMMARY, json!({"path": "/tmp/b.txt"})).unwrap(); + let text = String::from_utf8(written.borrow()[1].1.clone()).unwrap(); + assert!(text.starts_with("Options\nEvery option matches the preset.\n"), "compared against the replaced preset: {text}"); +} + +/// The Summary is computed again when the saved flattener preset the dialog names is deleted while +/// the dialog stays open: the settings are then refused, and nothing is written. +#[test] +fn save_summary_sees_a_deleted_flattener_preset() { + let (mut app, written, _) = app(); + app.run("flattener.presets.save", json!({"name": "Mine Flat", "preset": "Low Resolution"})).unwrap(); + app.run("file.export.pdf", json!({})).unwrap(); + set_field(&mut app, "flattenerPreset", json!("Mine Flat")); + app.ui_ctx = Some(egui::Context::default()); + app.run(SAVE_SUMMARY, json!({"path": "/tmp/a.txt"})).unwrap(); + app.run("flattener.presets.delete", json!({"name": "Mine Flat"})).unwrap(); + let e = app.run(SAVE_SUMMARY, json!({"path": "/tmp/b.txt"})).unwrap_err(); + assert!(e.contains("Mine Flat"), "the deleted preset is refused: {e}"); + assert_eq!(written.borrow().len(), 1, "nothing written for the deleted preset"); +} + +/// The Summary is computed again when a loaded profile the dialog converts to is removed while the +/// dialog stays open: the settings are then refused, and nothing is written. +#[test] +fn save_summary_sees_a_removed_profile() { + use vectorcraft_color::cms; + let name = "Summary Stamp CMYK"; + // The built-in CMYK profile's file renamed `name`: padded with spaces, which names drop. + let utf16 = |s: &str| s.encode_utf16().flat_map(u16::to_be_bytes).collect::>(); + let mut bytes = cms::icc_bytes(cms::DEVICE_CMYK).unwrap().to_vec(); + let (from, to) = (utf16(cms::DEVICE_CMYK), utf16(&format!("{name: PDF +/// Summary.txt`, the file holds the text the section shows, and the dialog stays open. A canceled +/// panel writes nothing; a failed write is told over the dialog, which shows again when the +/// message closes. The web downloads the file under the suggested name. +#[test] +fn the_save_summary_button_writes_the_summary() { + let (mut app, written, _) = app(); + let suggested: Rc>> = Rc::default(); + let s = suggested.clone(); + app.services.pick_save = Some(Box::new(move |pick: &crate::FilePick| { + s.borrow_mut().push(pick.name.clone()); + Some(format!("/tmp/{}", pick.name)) + })); + app.run("file.export.pdf", json!({})).unwrap(); + set_field(&mut app, "__section", json!("Summary")); + set_field(&mut app, "thumbnails", json!(true)); + let ctx = egui::Context::default(); + theme::install_fonts(&ctx); + click_save_summary(&mut app, &ctx); + let title = app.session.active().unwrap().title(); + let stem = std::path::Path::new(&title).file_stem().unwrap().to_string_lossy().into_owned(); + let name = format!("{stem} PDF Summary.txt"); + assert_eq!(suggested.borrow()[..], *std::slice::from_ref(&name)); + { + let w = written.borrow(); + assert_eq!(w.len(), 1, "written once"); + assert_eq!(w[0].0, format!("/tmp/{name}")); + let text = String::from_utf8(w[0].1.clone()).unwrap(); + assert!(text.starts_with("Options\nGeneral › Thumbnails: On\n\nWarnings\n"), "{text}"); + } + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(KIND), "the dialog stays open"); + // Canceled: nothing written, no status, the dialog stays. + app.services.pick_save = Some(Box::new(|_: &crate::FilePick| None)); + app.ui.status.clear(); + click_save_summary(&mut app, &ctx); + assert_eq!(written.borrow().len(), 1, "a canceled panel writes nothing"); + assert!(app.ui.status.is_empty(), "{}", app.ui.status); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(KIND)); + // A failed write: a message names the file, over the dialog. + app.services.pick_save = Some(Box::new(|pick: &crate::FilePick| Some(format!("/tmp/{}", pick.name)))); + app.services.write = Some(Box::new(|_: &str, _: &[u8]| Err("disk full".into()))); + click_save_summary(&mut app, &ctx); + let told = app.ui.dialog.clone().expect("a message"); + assert_eq!(told.kind, super::super::confirm::MESSAGE, "status {:?}, waiting {:?}", app.ui.status, app.ui.told); + assert!(told.str("message").contains(&name), "{:?}", told.fields); + assert_eq!(super::super::parent(&told).map(|d| d.kind), Some(KIND.to_string()), "the dialog is under the message"); + super::super::cancel(&mut app); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(KIND), "the dialog shows again"); + // The web downloads it under the suggested name. + let downloads: Log = Log::default(); + let dl = downloads.clone(); + app.services.download = Some(Box::new(move |n: &str, b: &[u8]| { + dl.borrow_mut().push((n.to_string(), b.to_vec())); + Ok(()) + })); + click_save_summary(&mut app, &ctx); + let d = downloads.borrow(); + assert_eq!(d.len(), 1); + assert_eq!(d[0].0, name); + assert!(String::from_utf8(d[0].1.clone()).unwrap().starts_with("Options\n")); +} + +/// The saved Summary writes each option line with the colon the interface language uses, as the +/// Summary section shows it: French puts a no-break space before the colon, Japanese writes a +/// full-width colon. +#[test] +fn the_summary_text_uses_the_languages_colon() { + let changed = json!({"option": "thumbnails", "value": true}); + for (code, colon) in [("en", ":"), ("fr", "\u{a0}:"), ("ja", ":")] { + crate::i18n::set_current(crate::i18n::Lang::from_code(code).expect("registered")); + let line = option_line(&changed, |_| "X".to_string()); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert!(line.starts_with(&format!("X{colon} ")), "{code}: {line:?}"); + } +} + +/// Click the Summary section's Save Summary… button in frames of the dialog layer (the dialog's +/// window draws nothing in its first frame, which sizes it). +fn click_save_summary(app: &mut VectorcraftApp, ctx: &egui::Context) { + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 1000.0)); + let run = |app: &mut VectorcraftApp, events: Vec| { + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }, |ui| super::super::show(app, ui.ctx())); + out.textures_delta.clear(); + crate::tests_removeanchors::shapes_text(&out.shapes.iter().map(|c| c.shape.clone()).collect::>()) + }; + run(app, vec![]); + let labels = run(app, vec![]); + let at = + labels.iter().find(|(t, _)| t.trim() == "Save Summary…").map(|(_, r)| r.center()).unwrap_or_else(|| panic!("no Save Summary… in {labels:?}")); + let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + run(app, vec![egui::Event::PointerMoved(at), button(true)]); + run(app, vec![button(false)]); +} + #[test] fn confirm_runs_export_pdf_with_the_dialog_options() { let (mut app, written, opened) = app(); @@ -916,3 +1282,291 @@ fn advanced_section_shows_raster_resolution_note() { frame(&mut app); assert!(app.ui.dialog.is_some()); } + +/// Headless frames of the dialog layer with screen-reader output. +struct Reader(egui::Context); + +impl Reader { + fn new() -> Self { + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + theme::install_fonts(&ctx); + Self(ctx) + } + + fn run(&self, app: &mut VectorcraftApp, events: Vec) -> egui::FullOutput { + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1280.0, 900.0)); + let mut out = + self.0.run_ui(egui::RawInput { events, screen_rect: Some(screen), ..Default::default() }, |ui| super::super::show(app, ui.ctx())); + out.textures_delta.clear(); + out + } + + /// The Custom… button of the open dialog, with whether it is enabled. + fn custom(&self, app: &mut VectorcraftApp) -> Option<(egui::accesskit::NodeId, bool)> { + self.run(app, vec![]); + let out = self.run(app, vec![]); + let nodes = &out.platform_output.accesskit_update.as_ref()?.nodes; + nodes.iter().find(|(_, n)| n.label() == Some("Custom…") && n.role() == egui::accesskit::Role::Button).map(|(id, n)| (*id, !n.is_disabled())) + } + + /// The labels and values the open dialog shows. + fn texts(&self, app: &mut VectorcraftApp) -> Vec { + self.run(app, vec![]); + let out = self.run(app, vec![]); + let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); + nodes.iter().flat_map(|(_, n)| [n.label(), n.value()]).flatten().map(str::to_string).collect() + } + + /// Click Custom… in Save PDF's Advanced section. + fn click_custom(&self, app: &mut VectorcraftApp) { + let (node, enabled) = self.custom(app).expect("a Custom… button"); + assert!(enabled, "Custom… is enabled"); + let click = egui::accesskit::ActionRequest { + action: egui::accesskit::Action::Click, + target_node: node, + target_tree: egui::accesskit::TreeId::ROOT, + data: None, + }; + self.run(app, vec![egui::Event::AccessKitActionRequest(click)]); + } +} + +fn kind(app: &VectorcraftApp) -> Option<&str> { + app.ui.dialog.as_ref().map(|d| d.kind.as_str()) +} + +/// Save PDF on `params` (and `path`), showing Advanced. +fn open_advanced(app: &mut VectorcraftApp, params: Value) { + let mut p = params; + p["path"] = json!("/tmp/out.pdf"); + app.run("ui.savePdfDialog", p).unwrap(); + set_field(app, "__section", json!("Advanced")); +} + +/// A second rectangle, half transparent, over the first one. +fn transparent_overlap(app: &mut VectorcraftApp) { + app.run("select.none", json!({})).unwrap(); + app.run("shape.rectangle", json!({"x": 30, "y": 20, "width": 50, "height": 40})).unwrap(); + app.run("transparency.set", json!({"opacity": 50})).unwrap(); +} + +/// The images a written PDF reopens with. +fn images(pdf: &[u8]) -> usize { + let doc = vectorcraft_pdf::import(pdf).unwrap(); + let mut n = 0; + for l in &doc.layers { + l.walk(&mut |x| n += matches!(x.kind, vectorcraft_doc::NodeKind::Image(_)) as usize); + } + n +} + +#[test] +fn custom_is_enabled_where_the_save_flattens() { + let (mut app, _, _) = app(); + let r = Reader::new(); + for (params, flattens) in [ + (json!({"compatibility": "1.3"}), true), + (json!({"standard": "pdfX1a"}), true), + (json!({"standard": "pdfX3"}), true), + (json!({"compatibility": "1.4"}), false), + (json!({"standard": "pdfX4"}), false), + ] { + open_advanced(&mut app, params.clone()); + assert_eq!(r.custom(&mut app).map(|(_, enabled)| enabled), Some(flattens), "{params}"); + } + // PDF presets keep no custom flattener options, so the preset editor has no Custom…. + open_preset(&mut app, &json!({})).unwrap(); + set_field(&mut app, "__section", json!("Advanced")); + set_field(&mut app, "compatibility", json!("1.3")); + assert_eq!(r.custom(&mut app), None); +} + +#[test] +fn custom_starts_from_the_preset_and_cancel_goes_back_unchanged() { + let (mut app, _, _) = app(); + open_advanced(&mut app, json!({"compatibility": "1.3", "flattenerPreset": "low"})); + let r = Reader::new(); + r.custom(&mut app); + let before = app.ui.dialog.as_ref().unwrap().fields.clone(); + r.click_custom(&mut app); + assert_eq!(kind(&app), Some(CUSTOM_KIND)); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.f64("balance", 0.0), d.f64("gradientPpi", 0.0)), (75.0, 150.0), "Low Resolution's"); + // Low Resolution doesn't clip, but the PDF 1.3 writer does. + assert!(d.bool("clipComplexRegions"), "shown as written"); + app.ui.dialog.as_mut().unwrap().fields.insert("balance".into(), json!(10)); + super::super::cancel(&mut app); + assert_eq!(kind(&app), Some(KIND)); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields, before, "Cancel leaves Save PDF as it was"); +} + +#[test] +fn custom_options_are_written_until_a_preset_is_chosen() { + let (mut app, written, _) = app(); + transparent_overlap(&mut app); + open_advanced(&mut app, json!({"compatibility": "1.3"})); + let r = Reader::new(); + r.click_custom(&mut app); + app.ui.dialog.as_mut().unwrap().fields.insert("balance".into(), json!(0)); + super::super::confirm(&mut app).unwrap(); + assert_eq!(kind(&app), Some(KIND), "OK goes back to Save PDF"); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(d.fields["flattener"]["balance"].as_f64(), Some(0.0)); + let saved = &app.session.prefs.flattener_presets; + assert_ne!(flattener(d, saved).ok(), FlattenOptions::preset(pdf::DEFAULT_FLATTENER), "the preset shows [Custom]"); + // A preset set through `ui.dialog.set` drops the custom options. + let kept = d.clone(); + let dialog = app.ui.dialog.as_mut().unwrap(); + assert!(super::super::accepts_field(dialog, "flattenerPreset")); + let old = dialog.fields.get("flattenerPreset").cloned(); + super::super::set_field(dialog, "flattenerPreset".into(), json!("Low Resolution")); + super::super::field_set(&mut app, "flattenerPreset", old.as_ref()).unwrap(); + assert!(!app.ui.dialog.as_ref().unwrap().fields.contains_key("flattener")); + app.ui.dialog = Some(kept); + super::super::confirm(&mut app).unwrap(); + assert!(images(&written.borrow()[0].1) > 0, "balance 0 rasterizes the flattened art"); + open_advanced(&mut app, json!({"compatibility": "1.3"})); + super::super::confirm(&mut app).unwrap(); + assert_eq!(images(&written.borrow()[1].1), 0, "High Resolution keeps it vector"); +} + +#[test] +fn custom_options_equal_to_the_preset_leave_its_name() { + let (mut app, _, _) = app(); + let r = Reader::new(); + for overprint in ["preserve", "discard"] { + open_advanced(&mut app, json!({"compatibility": "1.3", "flattenerPreset": "medium", "advanced": {"overprint": overprint}})); + r.click_custom(&mut app); + assert_eq!(app.ui.dialog.as_ref().unwrap().bool("preserveOverprints"), overprint == "preserve", "{overprint}"); + super::super::confirm(&mut app).unwrap(); + assert_eq!(kind(&app), Some(KIND)); + assert!(!app.ui.dialog.as_ref().unwrap().fields.contains_key("flattener"), "{overprint}"); + } +} + +/// OK keeps Custom… options that drop overprints dropping them, although the preset keeps them. +#[test] +fn custom_keeps_options_that_drop_overprints() { + let (mut app, _, _) = app(); + let params = json!({"compatibility": "1.3", "advanced": {"overprint": "preserve"}, "flattener": {"preserveOverprints": false}}); + open_advanced(&mut app, params); + Reader::new().click_custom(&mut app); + assert!(!app.ui.dialog.as_ref().unwrap().bool("preserveOverprints"), "shown as written"); + super::super::confirm(&mut app).unwrap(); + assert_eq!(kind(&app), Some(KIND)); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(flattener(d, &app.session.prefs.flattener_presets).map(|o| o.preserve_overprints), Ok(false)); +} + +#[test] +fn custom_shows_alpha_as_the_pdf_1_3_writer_drops_it() { + let (mut app, written, _) = app(); + transparent_overlap(&mut app); + open_advanced(&mut app, json!({"compatibility": "1.3", "flattener": {"balance": 0, "preserveAlpha": true}})); + Reader::new().click_custom(&mut app); + assert!(!app.ui.dialog.as_ref().unwrap().bool("preserveAlpha"), "shown as written"); + super::super::confirm(&mut app).unwrap(); + assert_eq!(kind(&app), Some(KIND)); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["flattener"]["preserveAlpha"].as_bool(), Some(false)); + super::super::confirm(&mut app).unwrap(); + assert!(written.borrow()[0].1.starts_with(b"%PDF-1.3") && images(&written.borrow()[0].1) > 0); +} + +#[test] +fn bad_custom_options_keep_the_dialog_open() { + let (mut app, _, _) = app(); + open_advanced(&mut app, json!({"compatibility": "1.3"})); + Reader::new().click_custom(&mut app); + app.ui.dialog.as_mut().unwrap().fields.insert("gradientPpi".into(), json!(9000)); + let e = super::super::confirm(&mut app).unwrap_err(); + assert!(e.contains("resolutions"), "{e}"); + assert_eq!(kind(&app), Some(CUSTOM_KIND)); +} + +#[test] +fn custom_options_outlive_a_saved_preset_deleted_meanwhile() { + let (mut app, written, _) = app(); + app.run("flattener.presets.save", json!({"name": "Mine", "balance": 20})).unwrap(); + open_advanced(&mut app, json!({"compatibility": "1.3", "flattenerPreset": "Mine"})); + Reader::new().click_custom(&mut app); + assert_eq!(app.ui.dialog.as_ref().unwrap().f64("balance", 0.0), 20.0, "the saved preset's"); + app.run("flattener.presets.delete", json!({"name": "Mine"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("balance".into(), json!(30)); + super::super::confirm(&mut app).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.str("flattenerPreset"), d.fields["flattener"]["balance"].as_f64()), (String::new(), Some(30.0))); + super::super::confirm(&mut app).unwrap(); + assert!(written.borrow()[0].1.starts_with(b"%PDF-1.3")); +} + +/// OK keeps the overprint option of a saved preset deleted meanwhile, whichever value Overprint +/// shows it with, although the default preset keeps overprints. +#[test] +fn custom_keeps_the_overprint_option_of_a_saved_preset_deleted_meanwhile() { + let (mut app, _, _) = app(); + for (kept, overprint) in [(false, "preserve"), (true, "discard")] { + app.run("flattener.presets.save", json!({"name": "Mine", "balance": 20, "preserveOverprints": kept})).unwrap(); + open_advanced(&mut app, json!({"compatibility": "1.3", "flattenerPreset": "Mine", "advanced": {"overprint": overprint}})); + Reader::new().click_custom(&mut app); + assert!(!app.ui.dialog.as_ref().unwrap().bool("preserveOverprints"), "shown as written ({overprint})"); + app.run("flattener.presets.delete", json!({"name": "Mine"})).unwrap(); + super::super::confirm(&mut app).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(d.fields["flattener"]["preserveOverprints"].as_bool(), Some(kept), "{overprint}"); + } +} + +/// OK keeps the overprint option Custom… opened with when its saved preset is deleted and made +/// again under the same name with another overprint option meanwhile. +#[test] +fn custom_keeps_the_overprint_option_it_opened_with_over_a_preset_made_again() { + let (mut app, _, _) = app(); + app.run("flattener.presets.save", json!({"name": "Mine", "balance": 20, "preserveOverprints": false})).unwrap(); + open_advanced(&mut app, json!({"compatibility": "1.3", "flattenerPreset": "Mine", "advanced": {"overprint": "preserve"}})); + Reader::new().click_custom(&mut app); + assert!(!app.ui.dialog.as_ref().unwrap().bool("preserveOverprints"), "shown as the preset had it"); + app.run("flattener.presets.delete", json!({"name": "Mine"})).unwrap(); + app.run("flattener.presets.save", json!({"name": "Mine", "balance": 20, "preserveOverprints": true})).unwrap(); + super::super::confirm(&mut app).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(d.fields["flattener"]["preserveOverprints"].as_bool(), Some(false)); +} + +/// Flattener preset shows a preset named in another case by its name, not as [Custom]. +#[test] +fn flattener_preset_shows_a_name_given_in_any_case() { + let (mut app, _, _) = app(); + app.run("flattener.presets.save", json!({"name": "Mine", "balance": 20})).unwrap(); + let r = Reader::new(); + for (given, shown) in [("MINE", "Mine"), ("HIGH RESOLUTION", "High Resolution")] { + open_advanced(&mut app, json!({"compatibility": "1.3", "flattenerPreset": given})); + let texts = r.texts(&mut app); + assert!(texts.iter().any(|t| t == shown), "{given}: {texts:?}"); + assert!(!texts.iter().any(|t| t == "[Custom]"), "{given}: {texts:?}"); + } +} + +#[test] +fn save_preset_says_it_leaves_the_custom_flattener_options_out() { + let (mut app, _, _) = app(); + let r = Reader::new(); + let note = "The PDF preset keeps the flattener preset but not the Custom… settings."; + app.run("ui.savePdfDialog", json!({"compatibility": "1.3", "flattener": {"balance": 10}})).unwrap(); + set_field(&mut app, SAVE_AS, json!("Mine")); + assert!(r.texts(&mut app).iter().any(|t| t == note), "with Custom… options"); + app.ui.dialog.as_mut().unwrap().fields.remove("flattener"); + assert!(!r.texts(&mut app).iter().any(|t| t == note), "without them"); +} + +#[test] +fn save_pdf_opens_with_the_flattener_options_given_and_refuses_bad_ones() { + let (mut app, _, _) = app(); + app.run("ui.savePdfDialog", json!({"compatibility": "1.3", "flattener": {"lineArtPpi": 600}})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["flattener"], json!({"lineArtPpi": 600})); + for bad in [json!({"bogus": 1}), json!(5), json!({"gradientPpi": 9000})] { + app.ui.dialog = None; + assert!(app.run("ui.savePdfDialog", json!({"flattener": bad})).is_err(), "{bad}"); + assert!(app.ui.dialog.is_none(), "{bad}"); + } +} diff --git a/crates/ui-egui/src/dialogs/swatch_conflict.rs b/crates/ui-egui/src/dialogs/swatch_conflict.rs index fb8b528b01..96ff733c42 100644 --- a/crates/ui-egui/src/dialogs/swatch_conflict.rs +++ b/crates/ui-egui/src/dialogs/swatch_conflict.rs @@ -36,8 +36,7 @@ pub fn ask(app: &mut VectorcraftApp, command: &str, params: &Value) -> Option DialogResult { } let mut params = d.fields.get("__params").cloned().filter(Value::is_object).unwrap_or_else(|| json!({})); params["swatchConflict"] = Value::Object(choices); + // When the conflicts the paste raises have changed meanwhile (another profile converts the + // pasted swatches), it asks again about them instead. + let asked = list.to_vec(); app.ui.dialog = None; - crate::placing::confirm_swatch_paste(app, &d.str("__command"), params, d.fields.get("__deferredPaste").and_then(Value::as_u64)) + let changed = |app: &mut VectorcraftApp, _: &str, params: &Value| found(app, params).is_some_and(|now| now != asked); + let recheck = crate::placing::Recheck { key: "swatchConflict", changed: &changed }; + let deferred = d.fields.get("__deferredPaste").and_then(Value::as_u64); + crate::placing::confirm_swatch_paste(app, &d.str("__command"), params, deferred, Some(&recheck)) +} + +/// The swatch conflicts pasting with `params` raises (`clipboard.conflicts`), with the swatches as +/// the paste brings them: converted from another profile when it converts. +fn found(app: &mut VectorcraftApp, params: &Value) -> Option> { + let mut q = json!({}); + if let Some(m) = params.get("profileMismatch") { + q["profileMismatch"] = m.clone(); + } + let found = app.session.execute("clipboard.conflicts", &q).ok()?; + found["swatches"].as_array().cloned() } diff --git a/crates/ui-egui/src/dialogs/symbolism_options.rs b/crates/ui-egui/src/dialogs/symbolism_options.rs index 05392bbd4f..43a37812b5 100644 --- a/crates/ui-egui/src/dialogs/symbolism_options.rs +++ b/crates/ui-egui/src/dialogs/symbolism_options.rs @@ -1,10 +1,16 @@ //! Symbolism Tools Options (double-click a Symbolism tool): the brush the eight tools share, which //! lasts across tool switches and is saved with the preferences. OK sets it with -//! `tool.setOption {tool, values}`. +//! `tool.setOption {tool, values}`, and gives a new Symbol Set Density to the selected symbol sets +//! with `symbol.setDensity`. //! -//! Fields: `tool`; `diameter` (points), `intensity` and `density` (Symbol Set Density), 1–10. +//! Fields: `tool` (the tool whose options show; the Tool row changes it); `diameter` (points), +//! `intensity` and `density` (Symbol Set Density), 1–10; `usePressure`; `method` (`userDefined`, +//! `average` or `random`); `showBrush`; `sprayScrunch`, `spraySize`, `spraySpin`, `sprayScreen`, +//! `sprayStain` and `sprayStyle` (Symbol Sprayer, each `average` or `userDefined`); `proportional` +//! and `affectsDensity` (Symbol Sizer); `densityWas` (the density the dialog opened with). use serde_json::{Map, Value, json}; +use vectorcraft_tools::settings::SYMBOLISM; use super::{DialogResult, DialogSpec, form, set_tool_options_and_close}; use crate::state::Dialog; @@ -14,19 +20,35 @@ use crate::{VectorcraftApp, widgets}; pub const KIND: &str = "symbolismOptions"; pub(super) const SPEC: DialogSpec = - DialogSpec { heading: |_| tl!("Symbolism Tools Options").into(), body, confirm, min_width: 320.0, ..DialogSpec::FORM }; + DialogSpec { heading: |_| tl!("Symbolism Tools Options").into(), body, confirm, min_width: 340.0, ..DialogSpec::FORM }; -/// The options the dialog edits. -const KEYS: [&str; 3] = ["diameter", "intensity", "density"]; +/// The numbers the dialog edits. +const NUMBERS: [&str; 3] = ["diameter", "intensity", "density"]; + +/// The checkboxes the dialog edits. +const SWITCHES: [&str; 4] = ["usePressure", "showBrush", "proportional", "affectsDensity"]; + +/// The Symbol Sprayer options. +const SPRAY: [&str; 6] = ["sprayScrunch", "spraySize", "spraySpin", "sprayScreen", "sprayStain", "sprayStyle"]; + +/// The density the dialog opened with: OK spaces the selected symbol sets from it to the new one. +const DENSITY_WAS: &str = "densityWas"; /// Width of the label column. const LABEL_W: f32 = 130.0; +/// Width of the dropdowns. +const CHOICE_W: f32 = 170.0; + /// Open the options of Symbolism tool `tool` (one of `vectorcraft_tools::settings::SYMBOLISM`) /// with their current values. pub fn open(app: &mut VectorcraftApp, tool: &str) -> Value { let o = app.session.tool_options_of(tool); - let mut fields: Map = KEYS.iter().filter_map(|key| Some((key.to_string(), o.get(*key)?.clone()))).collect(); + let keys = NUMBERS.iter().chain(&SWITCHES).chain(&SPRAY).chain(&["method"]); + let mut fields: Map = keys.filter_map(|key| Some((key.to_string(), o.get(*key)?.clone()))).collect(); + if let Some(density) = fields.get("density").cloned() { + fields.insert(DENSITY_WAS.into(), density); + } fields.insert("tool".into(), json!(tool)); app.ui.dialog = Some(Dialog { kind: KIND.into(), fields }); json!({ "dialog": KIND }) @@ -34,22 +56,100 @@ pub fn open(app: &mut VectorcraftApp, tool: &str) -> Value { fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { let unit = app.session.general_unit(); + // The tool whose options show below (the eight tools share one toolbar icon, so they are listed + // by name). + let tools: Vec<(&str, &str)> = SYMBOLISM.iter().filter_map(|id| Some((*id, vectorcraft_tools::tool_info(id)?.label))).collect(); + form::choice(ui, d, "tool", tl!("Tool:"), (LABEL_W, CHOICE_W), &tools); + let tool = d.str("tool"); + ui.add_space(6.0); widgets::label_row(ui, tl!("Diameter:"), LABEL_W, |ui| { form::length(ui, d, "diameter", unit, 100.0); }); - for (key, label) in [("intensity", tl!("Intensity:")), ("density", tl!("Symbol Set Density:"))] { - widgets::label_row(ui, label, LABEL_W, |ui| { - if let Some(v) = widgets::range_field(ui, ("symbolism", key), d.f64(key, 5.0), 1.0..=10.0, "", 0, 100.0) { - d.fields.insert(key.into(), json!(v)); + // The Symbol Sprayer uses neither Intensity nor pen pressure. + let sprayer = tool == "symbolSprayer"; + let pressure = d.bool("usePressure"); + widgets::label_row(ui, tl!("Intensity:"), LABEL_W, |ui| { + ui.add_enabled_ui(!pressure && !sprayer, |ui| { + if let Some(v) = widgets::range_field(ui, ("symbolism", "intensity"), d.f64("intensity", 5.0), 1.0..=10.0, "", 0, 100.0) { + d.fields.insert("intensity".into(), json!(v)); } }); + }); + widgets::label_row(ui, "", LABEL_W, |ui| { + ui.add_enabled_ui(!sprayer, |ui| form::check(ui, d, "usePressure", tl!("Use Pressure Pen"))); + }); + widgets::label_row(ui, tl!("Symbol Set Density:"), LABEL_W, |ui| { + if let Some(v) = widgets::range_field(ui, ("symbolism", "density"), d.f64("density", 5.0), 1.0..=10.0, "", 0, 100.0) { + d.fields.insert("density".into(), json!(v)); + } + }); + // The Symbol Sprayer and the Symbol Shifter have no Method. + ui.add_enabled_ui(!["symbolSprayer", "symbolShifter"].contains(&tool.as_str()), |ui| { + let methods = [("userDefined", tl!("User Defined")), ("average", tl!("Average")), ("random", tl!("Random"))]; + form::choice(ui, d, "method", tl!("Method:"), (LABEL_W, CHOICE_W), &methods); + }); + if tool == "symbolSprayer" { + ui.add_space(10.0); + widgets::subheader(ui, tl!("Symbol Sprayer Options")); + ui.add_space(4.0); + let modes = [("average", tl!("Average")), ("userDefined", tl!("User Defined"))]; + let labels = [tl!("Scrunch:"), tl!("Size:"), tl!("Spin:"), tl!("Screen:"), tl!("Stain:"), tl!("Style:")]; + for (key, label) in SPRAY.iter().zip(labels) { + form::choice(ui, d, key, label, (LABEL_W, CHOICE_W), &modes); + } } + if tool == "symbolSizer" { + ui.add_space(10.0); + widgets::subheader(ui, tl!("Symbol Sizer Options")); + ui.add_space(4.0); + form::check(ui, d, "proportional", tl!("Proportional Resizing")); + form::check(ui, d, "affectsDensity", tl!("Resizing Affects Density")); + } + ui.add_space(10.0); + form::check(ui, d, "showBrush", tl!("Show Brush Size and Intensity")); false } -/// OK: set the brush the Symbolism tools share (the tool keeps it within its ranges). +/// The selected symbol sets that can be edited (not locked or hidden). +fn selected_sets(app: &VectorcraftApp) -> Vec { + let Some(st) = app.session.active() else { return vec![] }; + let editable = st.doc.editable(); + st.selection + .objects + .iter() + .filter(|id| st.doc.node(**id).is_some_and(vectorcraft_engine::cmd::is_symbol_set) && editable(**id)) + .map(|id| id.0) + .collect() +} + +/// OK: set the brush the Symbolism tools share, after giving a new Symbol Set Density to the +/// selected symbol sets. Every option is checked first, so a value the tools refuse (a number out +/// of its range included) leaves the symbol sets and the options as they are. 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(); + let mut values: Map = + NUMBERS.iter().filter(|k| d.fields.contains_key(**k)).map(|k| (k.to_string(), json!(d.f64(k, 0.0)))).collect(); + // The checkboxes and choices as the fields hold them, so a value the tools do not have is refused. + values.extend(SWITCHES.iter().chain(&SPRAY).chain(&["method"]).filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone())))); + // An option `tool.setOption` refuses leaves the symbol sets as they are too. + let tool = d.str("tool"); + if !SYMBOLISM.contains(&tool.as_str()) { + return Err(format!("unknown tool `{tool}`")); + } + // A number, or text that reads as one (a length with its unit for the diameter). + let readable = |v: &Value| match v { + Value::Number(_) => true, + Value::String(s) => vectorcraft_doc::Unit::Points.parse(s).is_some(), + _ => false, + }; + if let Some(k) = NUMBERS.iter().chain(&[DENSITY_WAS]).find(|k| d.fields.get(**k).is_some_and(|v| !readable(v))) { + return Err(format!("`{k}` must be a number")); + } + vectorcraft_tools::symbolism::check_options(&tool, &values)?; + let (from, to) = (d.f64(DENSITY_WAS, 0.0).clamp(1.0, 10.0), d.f64("density", 0.0).clamp(1.0, 10.0)); + let sets = selected_sets(app); + if d.fields.contains_key(DENSITY_WAS) && from != to && !sets.is_empty() { + app.run("symbol.setDensity", json!({ "from": from, "to": to, "ids": sets }))?; + } set_tool_options_and_close(app, json!({ "tool": d.str("tool"), "values": values })) } @@ -58,12 +158,21 @@ mod tests { use super::*; use vectorcraft_engine::Session; - #[test] - fn the_symbolism_tools_share_the_options_ok_sets() { + fn app() -> VectorcraftApp { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app + } + + fn painted(app: &mut VectorcraftApp) -> String { + crate::tests_labels::painted_text(app, |app, ui| super::super::show(app, ui.ctx())) + } + + #[test] + fn the_symbolism_tools_share_the_options_ok_sets() { + let mut app = app(); app.run("tool.options", json!({"tool": "symbolSizer"})).unwrap(); - let text = crate::tests_labels::painted_text(&mut app, |app, ui| super::super::show(app, ui.ctx())); + let text = painted(&mut app); for label in ["Symbolism Tools Options", "Diameter:", "Intensity:", "Symbol Set Density:"] { assert!(text.contains(label), "{label} in {text}"); } @@ -78,4 +187,167 @@ mod tests { let o = app.session.tool_options_of("symbolSprayer"); assert_eq!((o["diameter"].as_f64(), o["intensity"].as_f64(), o["density"].as_f64()), (Some(120.0), Some(9.0), Some(2.0))); } + + /// Every tool shows the general options; the Symbol Sprayer and the Symbol Sizer show their own + /// sections, and the Tool row's choice decides which. + #[test] + fn the_sprayer_and_the_sizer_show_their_sections() { + let mut app = app(); + let general = ["Tool:", "Use Pressure Pen", "Method:", "User Defined", "Show Brush Size and Intensity"]; + let sprayer = ["Symbol Sprayer Options", "Scrunch:", "Size:", "Spin:", "Screen:", "Stain:", "Style:"]; + let sizer = ["Symbol Sizer Options", "Proportional Resizing", "Resizing Affects Density"]; + for (tool, own, others) in + [("symbolSprayer", &sprayer[..], &sizer[..]), ("symbolSizer", &sizer[..], &sprayer[..]), ("symbolStainer", &[][..], &sprayer[..])] + { + app.run("tool.options", json!({"tool": tool})).unwrap(); + let text = painted(&mut app); + for label in general.iter().chain(own) { + assert!(text.contains(label), "{tool}: {label} in {text}"); + } + for label in others { + assert!(!text.contains(label), "{tool}: no {label} in {text}"); + } + } + // The Stainer's dialog, switched to the Sizer with the Tool row. + app.ui.dialog.as_mut().unwrap().fields.insert("tool".into(), json!("symbolSizer")); + let text = painted(&mut app); + assert!(text.contains("Proportional Resizing") && !text.contains("Scrunch:"), "{text}"); + } + + /// The Symbol Sprayer uses neither Intensity nor pen pressure: its Use Pressure Pen is disabled, + /// and the other tools' is not. + #[test] + fn the_sprayer_disables_use_pressure_pen() { + let mut app = app(); + for (tool, off) in [("symbolSprayer", true), ("symbolSizer", false), ("symbolShifter", false)] { + app.run("tool.options", json!({"tool": tool})).unwrap(); + let tree = crate::widgets::accessibility_tests::tree(|ui| super::super::show(&mut app, ui.ctx())); + let pen = crate::widgets::accessibility_tests::named(&tree, "Use Pressure Pen"); + assert_eq!(pen.is_disabled(), off, "{tool}"); + } + } + + /// OK sets Method, Use Pressure Pen, Show Brush Size and Intensity and the Sprayer's and the + /// Sizer's options for the eight tools, and the dialog opens with them again. + #[test] + fn ok_sets_the_method_the_pen_and_the_tool_sections() { + let mut app = app(); + app.run("tool.options", json!({"tool": "symbolSprayer"})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + assert_eq!((d.str("method"), d.bool("usePressure"), d.bool("showBrush")), ("userDefined".to_string(), false, true)); + assert_eq!((d.str("sprayStain"), d.bool("proportional"), d.bool("affectsDensity")), ("average".to_string(), true, false)); + for (k, v) in [ + ("method", json!("random")), + ("usePressure", json!(true)), + ("showBrush", json!(false)), + ("sprayStain", json!("userDefined")), + ("spraySpin", json!("userDefined")), + ("proportional", json!(false)), + ("affectsDensity", json!(true)), + ] { + d.fields.insert(k.into(), v); + } + super::super::confirm(&mut app).unwrap(); + let o = app.session.tool_options_of("symbolScreener"); + assert_eq!((o["method"].as_str(), o["usePressure"].as_bool(), o["showBrush"].as_bool()), (Some("random"), Some(true), Some(false))); + assert_eq!( + (o["sprayStain"].as_str(), o["spraySpin"].as_str(), o["sprayScrunch"].as_str()), + (Some("userDefined"), Some("userDefined"), Some("average")) + ); + assert_eq!((o["proportional"].as_bool(), o["affectsDensity"].as_bool()), (Some(false), Some(true))); + app.run("tool.options", json!({"tool": "symbolSizer"})).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.str("method"), d.bool("usePressure"), d.bool("affectsDensity")), ("random".to_string(), true, true)); + } + + /// A new Symbol Set Density spaces the instances of the selected symbol set, as one undo step; + /// the same density, or no set selected, adds none. + #[test] + fn ok_gives_a_new_density_to_the_selected_symbol_set() { + let mut app = app(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); + app.run("symbol.new", json!({"name": "Dot"})).unwrap(); + app.run("select.set", json!({"ids": []})).unwrap(); + let points: Vec = (0..8).map(|i| json!([40.0 + 40.0 * f64::from(i), 150.0])).collect(); + let set = app.run("symbol.spray", json!({"name": "Dot", "points": points, "radius": 4})).unwrap()["id"].as_u64().unwrap(); + let width = |app: &VectorcraftApp| { + let st = app.session.active().unwrap(); + st.doc.node(vectorcraft_doc::NodeId(set)).and_then(|n| n.geometric_bounds()).map(|b| b.width()).unwrap() + }; + let undo = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.len(); + let (was, steps) = (width(&app), undo(&app)); + // The same density: the set stays as it is. + app.run("tool.options", json!({"tool": "symbolSprayer"})).unwrap(); + super::super::confirm(&mut app).unwrap(); + assert_eq!((width(&app), undo(&app)), (was, steps)); + // A higher density packs the set closer, as one undo step. + app.run("tool.options", json!({"tool": "symbolSprayer"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("density".into(), json!(9)); + super::super::confirm(&mut app).unwrap(); + assert!(width(&app) < was * 0.8, "{} of {was}", width(&app)); + assert_eq!(undo(&app), steps + 1); + assert_eq!(app.session.tool_options_of("symbolSizer")["density"].as_f64(), Some(9.0)); + // An option the tools do not have: neither the set nor the options change. + let (was, steps) = (width(&app), undo(&app)); + app.run("tool.options", json!({"tool": "symbolSprayer"})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("density".into(), json!(3)); + d.fields.insert("method".into(), json!("smooth")); + assert!(super::super::confirm(&mut app).is_err()); + assert_eq!((width(&app), undo(&app)), (was, steps)); + app.run("tool.options", json!({"tool": "symbolSprayer"})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("density".into(), json!(3)); + d.fields.insert("usePressure".into(), json!(1)); + assert!(super::super::confirm(&mut app).is_err()); + assert_eq!((width(&app), undo(&app)), (was, steps)); + // A tool that is not a Symbolism tool, a density that is not a number, or a number out of + // its range. + for (k, v) in + [("tool", json!("pen")), ("density", json!("three")), ("densityWas", json!(null)), ("diameter", json!(1)), ("intensity", json!(11))] + { + app.run("tool.options", json!({"tool": "symbolSprayer"})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("density".into(), json!(3)); + d.fields.insert(k.into(), v); + assert!(super::super::confirm(&mut app).is_err(), "{k}"); + assert_eq!((width(&app), undo(&app)), (was, steps), "{k}"); + } + // A length with its unit is a diameter. + app.run("tool.options", json!({"tool": "symbolSprayer"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("diameter".into(), json!("12 pt")); + super::super::confirm(&mut app).unwrap(); + assert_eq!(app.session.tool_options_of("symbolSizer")["diameter"].as_f64(), Some(12.0)); + assert_eq!(app.session.tool_options_of("symbolSizer")["density"].as_f64(), Some(9.0)); + app.ui.dialog = None; + // Without a set selected only the option changes. + app.run("select.set", json!({"ids": []})).unwrap(); + let (was, steps) = (width(&app), undo(&app)); + app.run("tool.options", json!({"tool": "symbolSprayer"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("density".into(), json!(2)); + super::super::confirm(&mut app).unwrap(); + assert_eq!((width(&app), undo(&app)), (was, steps)); + assert_eq!(app.session.tool_options_of("symbolSizer")["density"].as_f64(), Some(2.0)); + } + + /// A locked symbol set in the selection keeps its spacing, and OK still sets the options. + #[test] + fn ok_sets_the_options_with_a_locked_symbol_set_selected() { + let mut app = app(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); + app.run("symbol.new", json!({"name": "Dot"})).unwrap(); + app.run("select.set", json!({"ids": []})).unwrap(); + let set = app.run("symbol.spray", json!({"name": "Dot", "points": [[40, 150], [120, 150]], "radius": 4})).unwrap()["id"].as_u64().unwrap(); + app.run("object.lock", json!({})).unwrap(); + app.session.select(|_, sel| sel.set([vectorcraft_doc::NodeId(set)])).unwrap(); + let steps = app.session.active().unwrap().history.undo.len(); + app.run("tool.options", json!({"tool": "symbolSprayer"})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("density".into(), json!(9)); + d.fields.insert("diameter".into(), json!(30)); + super::super::confirm(&mut app).unwrap(); + assert_eq!(app.session.active().unwrap().history.undo.len(), steps); + let o = app.session.tool_options_of("symbolSizer"); + assert_eq!((o["density"].as_f64(), o["diameter"].as_f64()), (Some(9.0), Some(30.0))); + } } diff --git a/crates/ui-egui/src/dialogs/tests_hpgl.rs b/crates/ui-egui/src/dialogs/tests_hpgl.rs index 238a254cfb..77e4071f74 100644 --- a/crates/ui-egui/src/dialogs/tests_hpgl.rs +++ b/crates/ui-egui/src/dialogs/tests_hpgl.rs @@ -1,28 +1,266 @@ -//! Export As → HP-GL, drawn headlessly: listed with the other formats, written straight away (no -//! options dialog), one plot per artboard with Use Artboards. +//! Export As → HP-GL, drawn headlessly: listed with the other formats, then HP-GL Options (version, +//! curve tolerance, origin, pens, path order), remembered for the next export, and one plot per +//! artboard with Use Artboards. use serde_json::json; +use vectorcraft_engine::cmd::fileio; use super::tests_export::{app, frame, kind, names, set}; use super::*; #[test] -fn export_as_lists_hpgl_and_writes_plots() { +fn export_as_hpgl_shows_hpgl_options_then_writes_and_remembers_them() { let (mut app, written) = app(2); app.run("file.exportAs", json!({"format": "hpgl"})).unwrap(); assert_eq!(kind(&app), Some("exportAs")); assert_eq!(app.ui.dialog.as_ref().unwrap().str("format"), "hpgl"); frame(&mut app); + confirm(&mut app).unwrap(); + assert_eq!(kind(&app), Some("hpglOptions"), "HP-GL Options follow"); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.str("path"), d.str("hpglVersion"), d.str("origin")), ("/out/Untitled-1.plt".into(), "hpgl".into(), "bottomLeft".into())); + assert_eq!((d.f64("curveTolerance", 0.0), d.fields["pens"].is_null(), d.bool("sortPaths"), d.bool("insideFirst")), (0.1, true, false, false)); + frame(&mut app); + // The defaults write the plot an export with this artboard choice and no HP-GL options writes. + let fields = &app.ui.dialog.as_ref().unwrap().fields; + let choice: serde_json::Map = fields + .iter() + .filter(|(k, _)| ["useArtboards", "range", "artboard", "artboards"].contains(&k.as_str())) + .map(|(k, v)| (k.clone(), v.clone())) + .collect(); + let plain = fileio::encode(&app.session.active().unwrap().doc, "hpgl", &serde_json::Value::Object(choice)).unwrap(); let r = confirm(&mut app).unwrap(); - assert!(app.ui.dialog.is_none(), "no options dialog follows"); + assert!(app.ui.dialog.is_none()); assert_eq!(r["path"], "/out/Untitled-1.plt"); - assert!(written.borrow()[0].1.starts_with(b"IN;")); - assert!(written.borrow()[0].1.ends_with(b"PU;SP0;")); + assert_eq!(written.borrow()[0].1, plain); + assert!(plain.starts_with(b"IN;") && plain.ends_with(b"PU;SP0;")); + + // Every control draws, the pen table with a row per pen; OK writes the options given. + app.run("file.exportAs", json!({"format": "hpgl"})).unwrap(); + frame(&mut app); + confirm(&mut app).unwrap(); + set(&mut app, "hpglVersion", json!("hpgl2")); + set(&mut app, "origin", json!("center")); + set(&mut app, "curveTolerance", json!(0.5)); + set(&mut app, "pens", json!(["#ff0000", "#000000"])); + set(&mut app, "sortPaths", json!(true)); + set(&mut app, "insideFirst", json!(true)); + frame(&mut app); + confirm(&mut app).unwrap(); + // HP-GL/2 with the pen table as its palette (the encoded polylines that follow are binary). + let plot = String::from_utf8_lossy(&written.borrow()[1].1).into_owned(); + assert!(plot.starts_with("IN;NP4;PC1,255,0,0;PC2,0,0,0;"), "{plot}"); + // The next HP-GL Options start from these choices, but not from this export's path. + crate::menus::invoke(&mut app, "ui.hpglOptionsDialog", json!({})); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.str("hpglVersion"), d.str("origin"), d.f64("curveTolerance", 0.0)), ("hpgl2".into(), "center".into(), 0.5)); + assert_eq!((d.fields["pens"].clone(), d.bool("sortPaths"), d.bool("insideFirst")), (json!(["#ff0000", "#000000"]), true, true)); + assert!(!d.fields.contains_key("path")); + assert!(app.ui.hpgl_options.get("useArtboards").is_none()); + app.ui.dialog = None; + // One plot per artboard. app.run("file.exportAs", json!({"format": "hpgl"})).unwrap(); set(&mut app, "useArtboards", json!(true)); frame(&mut app); confirm(&mut app).unwrap(); + assert_eq!(kind(&app), Some("hpglOptions")); + confirm(&mut app).unwrap(); let n = names(&written); - assert_eq!(&n[1..], ["/out/Untitled-1-Artboard-1.plt", "/out/Untitled-1-Artboard-2.plt"]); + assert_eq!(&n[2..], ["/out/Untitled-1-Artboard-1.plt", "/out/Untitled-1-Artboard-2.plt"]); +} + +#[test] +fn bad_hpgl_options_keep_the_dialog_open() { + let (mut app, written) = app(1); + app.run("ui.hpglOptionsDialog", json!({"path": "/out/a.plt"})).unwrap(); + frame(&mut app); + for (field, value, want) in [ + ("hpglVersion", json!("hpgl3"), "`hpglVersion`"), + ("curveTolerance", json!(20), "`curveTolerance`"), + ("origin", json!("top"), "`origin`"), + ("pens", json!(["#ff0000", "red"]), "`pens`"), + ("pens", json!([]), "`pens`"), + // More pens than a plot takes: drawn without rows, refused by OK. + ("pens", json!(vec!["#000000"; 300]), "`pens`"), + ("sortPaths", json!("yes"), "`sortPaths`"), + // An artboard the document doesn't have. + ("artboard", json!(3), "artboard"), + ("useArtboards", json!("yes"), "useArtboards"), + ] { + let before = app.ui.dialog.as_ref().unwrap().fields.get(field).cloned(); + set(&mut app, field, value.clone()); + frame(&mut app); + let e = confirm(&mut app).unwrap_err(); + assert!(e.contains(want), "{field} {value}: {e}"); + assert_eq!(kind(&app), Some("hpglOptions")); + set(&mut app, field, before.unwrap_or_default()); + } + assert!(written.borrow().is_empty()); + assert!(app.ui.hpgl_options.is_null(), "nothing is remembered from a refused OK"); + confirm(&mut app).unwrap(); + assert_eq!(names(&written), ["/out/a.plt"]); +} + +/// Pen Table starts from the pens the art gets, One Pen per Color sets the table aside, and Pen +/// Table shows it again; a document whose art draws nothing starts with one black pen. +#[test] +fn pen_table_starts_from_the_art_s_pens_and_comes_back() { + let (mut app, _) = app(1); + let automatic = fileio::hpgl::automatic_pens(&app.session.active().unwrap().doc, &json!({})).unwrap(); + assert_eq!(automatic.len(), 1, "the ellipse's fill is one pen"); + app.run("ui.hpglOptionsDialog", json!({})).unwrap(); + let none = || -> Result, String> { Ok(Vec::new()) }; + let d = app.ui.dialog.as_mut().unwrap(); + hpgl_options::set_pen_table(d, true, || Ok(automatic.clone())).unwrap(); + assert_eq!(d.fields["pens"], json!(automatic)); + d.fields.insert("pens".into(), json!(["#00ff00", "#0000ff"])); + hpgl_options::set_pen_table(d, false, none).unwrap(); + assert!(d.fields["pens"].is_null()); + // The table set aside is not an export option. + assert_eq!(d.fields["__pens"], json!(["#00ff00", "#0000ff"])); + assert!(form::params(d).get("__pens").is_none()); + // Choosing One Pen per Color again keeps the table set aside. + hpgl_options::set_pen_table(d, false, none).unwrap(); + hpgl_options::set_pen_table(d, true, || panic!("the table set aside comes back")).unwrap(); + assert_eq!(d.fields["pens"], json!(["#00ff00", "#0000ff"])); + // Nothing set aside and nothing drawn: one black pen. + d.fields.insert("pens".into(), serde_json::Value::Null); + d.fields.remove("__pens"); + hpgl_options::set_pen_table(d, true, none).unwrap(); + assert_eq!(d.fields["pens"], json!(["#000000"])); + frame(&mut app); +} + +/// Pen Table with options the export refuses keeps One Pen per Color and says why, rather than +/// starting from one black pen that the corrected options would keep. +#[test] +fn pen_table_with_refused_options_keeps_one_pen_per_color() { + let (mut app, _) = app(1); + app.run("ui.hpglOptionsDialog", json!({"curveTolerance": 20})).unwrap(); + let d = app.ui.dialog.clone().unwrap(); + let e = hpgl_options::automatic_pens(&app, &d).unwrap_err(); + assert!(e.contains("`curveTolerance`"), "{e}"); + let d = app.ui.dialog.as_mut().unwrap(); + assert_eq!(hpgl_options::set_pen_table(d, true, || Err(e.clone())), Err(e)); + assert!(d.fields["pens"].is_null(), "One Pen per Color stays chosen"); + frame(&mut app); + // With the tolerance corrected, Pen Table starts from the art's pen. + set(&mut app, "curveTolerance", json!(0.1)); + let d = app.ui.dialog.clone().unwrap(); + let pens = hpgl_options::automatic_pens(&app, &d).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + hpgl_options::set_pen_table(d, true, || Ok(pens.clone())).unwrap(); + assert_eq!(d.fields["pens"], json!(pens)); + assert_eq!(pens.len(), 1, "the ellipse's fill is one pen"); +} + +/// Export Selection to HP-GL checks, lists the pens of and writes the selection alone, and the next +/// whole-document export is not a selection export. +#[test] +fn export_selection_to_hpgl_uses_the_selection_and_is_not_remembered() { + let (mut app, written) = app(1); + // A blue outline that is the selection; the ellipse stays out of the file. + app.run("shape.rectangle", json!({"x": 40, "y": 30, "width": 10, "height": 5})).unwrap(); + app.run("paint.setFill", json!({"none": true})).unwrap(); + app.run("paint.setStroke", json!({"color": "#0000ff"})).unwrap(); + app.services.pick_save = Some(Box::new(|_: &crate::FilePick| Some("/out/sel.plt".to_string()))); + app.run("document.exportSelection", json!({})).unwrap(); + assert_eq!(kind(&app), Some("hpglOptions")); + let d = app.ui.dialog.clone().unwrap(); + assert!(d.bool(export_as::SELECTION_FIELD) && !d.fields.contains_key(crate::io::EXPORT_SELECTION)); + assert_eq!(hpgl_options::automatic_pens(&app, &d).unwrap(), ["#0000ff"], "the selection's pen only"); + // An artboard choice the whole document would refuse is not this export's. + set(&mut app, "artboard", json!(5)); + frame(&mut app); + confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(names(&written), ["/out/sel.plt"]); + let plot = String::from_utf8_lossy(&written.borrow()[0].1).into_owned(); + assert_eq!(plot.matches("PD").count(), 1, "the rectangle alone: {plot}"); + assert!(app.ui.hpgl_options.get(export_as::SELECTION_FIELD).is_none()); + // A selection export asked for by its param is not remembered either. + app.run("ui.hpglOptionsDialog", json!({"path": "/out/b.plt", "exportSelection": true})).unwrap(); + confirm(&mut app).unwrap(); + assert!(app.ui.hpgl_options.get(crate::io::EXPORT_SELECTION).is_none()); + app.run("select.none", json!({})).unwrap(); + app.run("ui.hpglOptionsDialog", json!({"path": "/out/c.plt"})).unwrap(); + confirm(&mut app).unwrap(); + assert_eq!(names(&written).last().map(String::as_str), Some("/out/c.plt"), "the whole document, with nothing selected"); +} + +/// A save panel that is canceled keeps HP-GL Options open, with the options remembered before. +#[test] +fn a_canceled_save_panel_keeps_hpgl_options_open() { + let (mut app, written) = app(1); + app.ui.hpgl_options = json!({"origin": "center"}); + app.services.pick_save = Some(Box::new(|_: &crate::FilePick| None)); + app.run("ui.hpglOptionsDialog", json!({})).unwrap(); + set(&mut app, "origin", json!("bottomLeft")); + frame(&mut app); + assert!(confirm(&mut app).is_err()); + assert_eq!(kind(&app), Some("hpglOptions")); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("origin"), "bottomLeft"); + assert_eq!(app.ui.hpgl_options, json!({"origin": "center"})); + assert!(written.borrow().is_empty()); + app.services.pick_save = Some(Box::new(|_: &crate::FilePick| Some("/out/d.plt".to_string()))); + confirm(&mut app).unwrap(); + assert_eq!(names(&written), ["/out/d.plt"]); + assert_eq!(app.ui.hpgl_options["origin"], "bottomLeft"); +} + +/// A save panel shown off the UI thread leaves the options remembered before until it answers: +/// canceled, they stay; answered, the export remembers the dialog's. +#[test] +fn an_off_thread_save_panel_remembers_hpgl_options_when_it_answers() { + let (mut app, _) = app(1); + let (shown, written) = crate::tests_picks::off_the_ui_thread(&mut app.services); + let poll = |app: &mut VectorcraftApp| crate::picks::poll(app, &egui::Context::default()); + app.ui.hpgl_options = json!({"origin": "center"}); + for answer in [&[][..], &["/out/e.plt"][..]] { + app.run("ui.hpglOptionsDialog", json!({})).unwrap(); + set(&mut app, "origin", json!("bottomLeft")); + frame(&mut app); + let _ = confirm(&mut app); + assert_eq!(shown.requests().len(), 1, "the save panel is showing"); + assert_eq!(app.ui.hpgl_options, json!({"origin": "center"}), "not remembered while the panel is open"); + shown.answer(answer); + poll(&mut app); + } + assert_eq!(*written.borrow(), ["/out/e.plt"], "the canceled panel wrote nothing"); + assert_eq!(app.ui.hpgl_options["origin"], "bottomLeft"); +} + +/// The pens Pen Table starts from are those of what this export plots: the art's bounds without +/// Use Artboards (art outside the artboard included), the selection with Export Selected Art Only, +/// and only the art on the artboard with Use Artboards. +#[test] +fn pen_table_starts_from_the_pens_of_what_the_export_plots() { + let (mut app, _) = app(1); + let on_board = fileio::hpgl::automatic_pens(&app.session.active().unwrap().doc, &json!({})).unwrap(); + assert_eq!(on_board.len(), 1, "the ellipse's fill is one pen"); + // A blue outline outside the artboard (the paint applies to the new rectangle, the selection). + app.run("shape.rectangle", json!({"x": 500, "y": 500, "width": 30, "height": 30})).unwrap(); + app.run("paint.setFill", json!({"none": true})).unwrap(); + app.run("paint.setStroke", json!({"color": "#0000ff"})).unwrap(); + app.run("file.exportAs", json!({"format": "hpgl"})).unwrap(); + set(&mut app, "useArtboards", json!(false)); + frame(&mut app); + confirm(&mut app).unwrap(); + assert_eq!(kind(&app), Some("hpglOptions")); + let seed = |app: &VectorcraftApp| hpgl_options::automatic_pens(app, app.ui.dialog.as_ref().unwrap()).unwrap(); + assert_eq!(seed(&app), [on_board[0].as_str(), "#0000ff"], "the art's bounds"); + // The rectangle is the selection. + set(&mut app, "selectedOnly", json!(true)); + assert_eq!(seed(&app), ["#0000ff"]); + set(&mut app, "selectedOnly", json!(false)); + set(&mut app, "useArtboards", json!(true)); + assert_eq!(seed(&app), on_board); +} + +#[test] +fn the_hpgl_options_dialog_needs_a_document() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + assert!(app.run("ui.hpglOptionsDialog", json!({})).is_err()); + assert!(!crate::menus::enabled(&app, "ui.hpglOptionsDialog")); } diff --git a/crates/ui-egui/src/dialogs/tests_track_cube.rs b/crates/ui-egui/src/dialogs/tests_track_cube.rs index 9b99efb105..9e36fb89f0 100644 --- a/crates/ui-egui/src/dialogs/tests_track_cube.rs +++ b/crates/ui-egui/src/dialogs/tests_track_cube.rs @@ -182,3 +182,37 @@ fn grips_follow_what_is_under_the_pointer() { let m = rotation([0.0, 0.0, 0.0]); assert_eq!(edges().filter(|&(i, _, axis)| edge_visible(m, i, axis)).count(), 4); } + +/// Map Art lists each document's own surfaces: after a switch to another document whose object has +/// the same id, effect settings and revision, the surfaces are those of the other document's object. +#[test] +fn map_art_surfaces_follow_the_active_document() { + let mut app = crate::VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + for d in ["M50 50L150 50L150 150L50 150Z", "M50 50L80 50L80 200L50 200Z"] { + app.run("file.new", json!({"width":300,"height":300})).unwrap(); + app.run("path.create", json!({"d": d})).unwrap(); + } + app.run("effect.dialog", json!({"effect":CLASSIC_EXTRUDE,"item":null})).unwrap(); + let d = app.ui.dialog.take().unwrap(); + let ctx = egui::Context::default(); + let key = |app: &crate::VectorcraftApp| { + let st = app.session.active().unwrap(); + (st.selection.objects.first().copied(), st.revision) + }; + let second = surfaces(&app, &ctx, &d).unwrap(); + let at_second = key(&app); + assert!(app.session.set_active(0)); + assert_eq!(key(&app), at_second, "both documents' objects have the same id and revision"); + let first = surfaces(&app, &ctx, &d).unwrap(); + let st = app.session.active().unwrap(); + let id = st.selection.objects[0]; + let own = vectorcraft_effects::map_surfaces_with( + Some(&st.doc), + st.doc.node(id).unwrap(), + (None, None), + CLASSIC_EXTRUDE, + &super::super::form::params(&d), + ); + assert_ne!(first, second, "the two objects' solids differ in size"); + assert_eq!(Some(first.as_ref()), own.as_ref(), "the first document's surfaces"); +} diff --git a/crates/ui-egui/src/dialogs/three_d_classic.rs b/crates/ui-egui/src/dialogs/three_d_classic.rs index e8c0e5c122..b3f1ebd3d9 100644 --- a/crates/ui-egui/src/dialogs/three_d_classic.rs +++ b/crates/ui-egui/src/dialogs/three_d_classic.rs @@ -7,7 +7,7 @@ use egui::{Color32, Id, Pos2, Rect, Sense, Stroke, Vec2, vec2}; use serde_json::{Value, json}; use vectorcraft_doc::Unit; -use vectorcraft_effects::{CLASSIC_EXTRUDE, CLASSIC_REVOLVE, CLASSIC_ROTATE}; +use vectorcraft_effects::{CLASSIC_EXTRUDE, CLASSIC_REVOLVE, CLASSIC_ROTATE, MAP_ART, MAP_INVISIBLE, MAP_SHADE, MapSurface, SurfaceMap}; use super::revolve::{c3, choice, heading, label, light_list, light_record, number, reset_dot, selected_light, store_selected, toggle}; use crate::state::Dialog; @@ -26,6 +26,359 @@ pub(super) fn object_controls(ui: &mut egui::Ui, d: &mut Dialog, unit: Unit) { number(ui, d, "bevelHeight", tl!("Height"), (1.0, 100.0), "", 1, Some(unit)); toggle(ui, d, "bevelInside", tl!("Bevel Inside"), false); }); + map_art_button(ui, d); +} + +/// The field of [`Dialog::fields`] that is true while the dialog shows Map Art in place of its +/// tabs. It is UI state and never enters the effect's parameters. +pub(super) const MAP_ART_OPEN: &str = "__mapArt"; +/// The field that holds the number of the surface Map Art shows. +const MAP_SURFACE: &str = "__mapSurface"; + +/// Map Art…, which opens [`map_art_controls`]. The 3D and Materials panel has no such button. +fn map_art_button(ui: &mut egui::Ui, d: &mut Dialog) { + if d.bool("__panel") { + return; + } + ui.add_space(10.0); + if ui.button(tl!("Map Art…")).clicked() { + d.fields.insert(MAP_ART_OPEN.into(), json!(true)); + } +} + +/// Is Map Art open in the dialog? +pub(super) fn map_art_open(d: &Dialog) -> bool { + d.bool(MAP_ART_OPEN) && vectorcraft_effects::takes_map_art(&d.str("__effect")) +} + +/// The numbered surfaces of the first selected object with the dialog's effect and settings +/// ([`vectorcraft_effects::map_surfaces_with`]), kept until the object, the document or a setting +/// that shapes the solid changes. +fn surfaces(app: &crate::VectorcraftApp, ctx: &egui::Context, d: &Dialog) -> Option>> { + use std::hash::{Hash, Hasher}; + let st = app.session.active()?; + let id = *st.selection.objects.first()?; + let effect = d.str("__effect"); + // The maps themselves do not change the surfaces. + let mut p = super::form::params(d); + if let Some(m) = p.as_object_mut() { + for key in [MAP_ART, MAP_SHADE, MAP_INVISIBLE] { + m.remove(key); + } + } + let item = d.fields.get("__item").and_then(Value::as_u64).map(|i| i as usize); + // The effect being edited, when the dialog edits one already on the object. + let index = d.fields.get("__index").and_then(Value::as_u64).map(|i| i as usize); + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + (st.uid, id.0, item, index, &effect, p.to_string(), st.revision).hash(&mut hasher); + let key = hasher.finish(); + let cache = egui::Id::unique("map-art-surfaces"); + if let Some((at, kept)) = ctx.data(|m| m.get_temp::<(u64, std::sync::Arc>)>(cache)) + && at == key + { + return Some(kept); + } + let listed = std::sync::Arc::new(vectorcraft_effects::map_surfaces_with(Some(&st.doc), st.doc.node(id)?, (item, index), &effect, &p)?); + ctx.data_mut(|m| m.insert_temp(cache, (key, listed.clone()))); + Some(listed) +} + +/// The dialog's maps, read as the effect reads them. +fn maps_of(d: &Dialog) -> Vec { + vectorcraft_effects::surface_maps(&json!({ MAP_ART: d.fields.get(MAP_ART).cloned().unwrap_or(Value::Null) })) +} + +/// The surface Map Art shows, from 1, among `count` surfaces. +fn shown_surface(d: &Dialog, count: usize) -> usize { + (d.f64(MAP_SURFACE, 1.0).round().max(1.0) as usize).min(count.max(1)) +} + +/// Map Art: the surface (first, previous, its number, next, last, and whether the viewer sees +/// it), the symbol mapped onto it, the surface laid out flat with the art's box to move, scale and +/// rotate, the same values as numbers, Scale to Fit, Clear, Clear All, Shade Artwork and Invisible +/// Geometry. Edits the effect's `mapArt`, `mapShade` and `mapInvisible` in `d.fields`, which the +/// dialog previews and applies with its other settings. Done, beside the heading, goes back to the +/// effect's options. +pub(super) fn map_art_controls(app: &crate::VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { + ui.horizontal(|ui| { + heading(ui, tl!("Map Art")); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.button(tl!("Done")).clicked() { + d.fields.remove(MAP_ART_OPEN); + } + }); + }); + let listed = surfaces(app, ui.ctx(), d).filter(|s| !s.is_empty()); + let Some(listed) = listed else { return }; + let count = listed.len(); + let mut current = shown_surface(d, count); + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 4.0; + label(ui, tl!("Surface")); + let step = |ui: &mut egui::Ui, text: &str, tip: &str, enabled: bool| { + let r = ui.add_enabled(enabled, egui::Button::new(text).min_size(egui::vec2(26.0, 24.0))); + r.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, enabled, tip)); + r.on_hover_text(tip).clicked() + }; + let mut next = None; + if step(ui, "|<", tl!("First Surface"), current > 1) { + next = Some(1); + } + if step(ui, "<", tl!("Previous Surface"), current > 1) { + next = Some(current - 1); + } + let mut typed = current; + let field = ui.add_sized([44.0, 24.0], egui::DragValue::new(&mut typed).range(1..=count).speed(0.1)); + field.widget_info(|| egui::WidgetInfo::labeled(egui::Role::SpinButton, true, tl!("Surface"))); + if field.changed() { + next = Some(typed); + } + ui.label(format!("/ {count}")); + if step(ui, ">", tl!("Next Surface"), current < count) { + next = Some(current + 1); + } + if step(ui, ">|", tl!("Last Surface"), current < count) { + next = Some(count); + } + if let Some(n) = next { + current = n.clamp(1, count); + } + // A light mark for a surface the viewer sees, a dark one for a hidden surface. + let seen = listed.get(current - 1).is_some_and(|s| s.visible); + let (mark, _) = ui.allocate_exact_size(egui::vec2(14.0, 14.0), egui::Sense::hover()); + ui.painter().rect_filled(mark, 2.0, if seen { egui::Color32::from_gray(205) } else { egui::Color32::from_gray(90) }); + if !seen { + crate::widgets::dim_label(ui, "Hidden"); + } + }); + d.fields.insert(MAP_SURFACE.into(), json!(current)); + let Some(surface) = listed.get(current - 1) else { return }; + let maps = maps_of(d); + let map = maps.iter().find(|m| m.surface == current).cloned(); + let mut edited = map.clone(); + let names: Vec = app.session.active().map(|st| st.doc.symbols.iter().map(|s| s.name.clone()).collect()).unwrap_or_default(); + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 6.0; + label(ui, tl!("Symbol")); + let none = tl!("None"); + let options: Vec<&str> = std::iter::once(none).chain(names.iter().map(String::as_str)).collect(); + let shown = map.as_ref().map_or(none, |m| m.symbol.as_str()); + // With every map the object takes in use, a surface without one cannot be given one. + let room = map.is_some() || maps.len() < vectorcraft_effects::MAX_MAPS; + let picked = ui.add_enabled_ui(room, |ui| crate::widgets::dropdown_names(ui, "map-art-symbol", shown, &options, 190.0)).inner; + if let Some(k) = picked.filter(|_| room) { + edited = k.checked_sub(1).and_then(|k| names.get(k)).map(|name| match &map { + Some(m) => SurfaceMap { symbol: name.clone(), ..m.clone() }, + None => SurfaceMap { surface: current, symbol: name.clone(), x: 0.0, y: 0.0, scale_x: 100.0, scale_y: 100.0, rotation: 0.0 }, + }); + } + }); + ui.add_space(6.0); + let art = edited.as_ref().and_then(|m| app.session.active().and_then(|st| vectorcraft_effects::graphic_bounds(&st.doc, &m.symbol))); + flat_view(app, ui, surface, &mut edited, art); + ui.add_space(6.0); + ui.add_enabled_ui(edited.is_some(), |ui| { + let shown = edited.clone().unwrap_or(SurfaceMap { + surface: current, + symbol: String::new(), + x: 0.0, + y: 0.0, + scale_x: 100.0, + scale_y: 100.0, + rotation: 0.0, + }); + let unit = app.session.general_unit(); + let mut fields = Dialog { kind: "mapArt".into(), fields: Default::default() }; + fields.fields.insert("__defaults".into(), json!({"mapX": 0.0, "mapY": 0.0, "mapScaleX": 100.0, "mapScaleY": 100.0, "mapRotation": 0.0})); + for (key, value) in + [("mapX", shown.x), ("mapY", shown.y), ("mapScaleX", shown.scale_x), ("mapScaleY", shown.scale_y), ("mapRotation", shown.rotation)] + { + fields.fields.insert(key.into(), json!(value)); + } + let offsets = (-vectorcraft_effects::GRAPHIC_MAX_OFFSET, vectorcraft_effects::GRAPHIC_MAX_OFFSET); + number(ui, &mut fields, "mapX", "X", offsets, "", 1, Some(unit)); + number(ui, &mut fields, "mapY", "Y", offsets, "", 1, Some(unit)); + number(ui, &mut fields, "mapScaleX", tl!("Horizontal Scale"), vectorcraft_effects::GRAPHIC_SCALE_RANGE, "%", 1, None); + number(ui, &mut fields, "mapScaleY", tl!("Vertical Scale"), vectorcraft_effects::GRAPHIC_SCALE_RANGE, "%", 1, None); + number(ui, &mut fields, "mapRotation", tl!("Rotation"), (-360.0, 360.0), "°", 1, None); + if let Some(m) = edited.as_mut() { + m.x = fields.f64("mapX", m.x); + m.y = fields.f64("mapY", m.y); + m.scale_x = fields.f64("mapScaleX", m.scale_x); + m.scale_y = fields.f64("mapScaleY", m.scale_y); + m.rotation = fields.f64("mapRotation", m.rotation); + } + }); + let mut clear_all = false; + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 6.0; + if ui.add_enabled(edited.is_some() && art.is_some(), egui::Button::new(tl!("Scale to Fit"))).clicked() + && let (Some(m), Some(art)) = (edited.as_mut(), art) + { + let (scale_x, scale_y) = m.fitting_scales(art, (surface.width, surface.height)).unwrap_or((m.scale_x, m.scale_y)); + *m = SurfaceMap { x: 0.0, y: 0.0, scale_x, scale_y, ..m.clone() }; + } + if ui.add_enabled(edited.is_some(), egui::Button::new(tl!("Clear"))).clicked() { + edited = None; + } + clear_all = ui.add_enabled(!maps.is_empty(), egui::Button::new(tl!("Clear All"))).clicked(); + }); + ui.add_space(4.0); + toggle(ui, d, MAP_SHADE, tl!("Shade Artwork"), false); + toggle(ui, d, MAP_INVISIBLE, tl!("Invisible Geometry"), false); + if clear_all { + d.fields.insert(MAP_ART.into(), json!([])); + } else if edited != map { + let raw = json!({ MAP_ART: d.fields.get(MAP_ART).cloned().unwrap_or(Value::Null) }); + let next = vectorcraft_effects::with_surface_map(&raw, current, edited.as_ref()); + d.fields.insert(MAP_ART.into(), next.get(MAP_ART).cloned().unwrap_or_else(|| json!([]))); + } +} + +/// What a drag in the flat view changes. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Grab { + Move, + /// A handle of the art's box: -1, 0 or 1 across and down, from its center. + Scale(f32, f32), + Rotate, +} + +/// A drag in the flat view: what it changes, the map as it was when the drag began and where the +/// pointer was then. +#[derive(Clone, Debug)] +struct MapDrag { + grab: Grab, + from: SurfaceMap, + origin: egui::Pos2, +} + +/// The surface laid out flat, as large as fits the view, in a light gray when the viewer sees it +/// and a dark gray when it is hidden, with the box of the mapped art `art` (its bounds at its own +/// size) on it: the art's thumbnail while it is not turned, its outline and its eight handles. A +/// drag inside the box moves the art, a drag of a handle scales it about its center, and a drag +/// just outside the box turns it. +fn flat_view( + app: &crate::VectorcraftApp, + ui: &mut egui::Ui, + surface: &MapSurface, + map: &mut Option, + art: Option, +) { + let t = crate::theme::Tokens::get(ui.ctx()); + let (view, response) = ui.allocate_exact_size(egui::vec2(ui.available_width().clamp(120.0, 330.0), 150.0), egui::Sense::click_and_drag()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Image, true, tl!("Surface"))); + ui.painter().rect_filled(view, 3.0, t.input); + ui.painter().rect_stroke(view, 3.0, egui::Stroke::new(1.0, t.input_border), egui::StrokeKind::Inside); + let (width, height) = (surface.width.max(1e-6), surface.height.max(1e-6)); + // Screen points for each point of the surface. + let scale = ((f64::from(view.width()) - 28.0) / width).min((f64::from(view.height()) - 28.0) / height).max(1e-6); + let flat = egui::Rect::from_center_size(view.center(), egui::vec2((width * scale) as f32, (height * scale) as f32)); + let painter = ui.painter().with_clip_rect(view.intersect(ui.clip_rect())); + painter.rect_filled(flat, 0.0, if surface.visible { egui::Color32::from_gray(205) } else { egui::Color32::from_gray(90) }); + let drag_id = egui::Id::unique("map-art-drag"); + let (Some(m), Some(art)) = (map.as_mut(), art) else { + ui.data_mut(|d| d.remove::(drag_id)); + return; + }; + let box_of = |m: &SurfaceMap| { + let center = view.center() + egui::vec2((m.x * scale) as f32, (m.y * scale) as f32); + let half = egui::vec2((art.width() * m.scale_x / 100.0 * scale / 2.0) as f32, (art.height() * m.scale_y / 100.0 * scale / 2.0) as f32); + // Counterclockwise on a screen whose y runs down. + let (sin, cos) = (-m.rotation.to_radians() as f32).sin_cos(); + (center, half, sin, cos) + }; + let (center, half, sin, cos) = box_of(m); + let handles: Vec<(f32, f32)> = + [-1.0f32, 0.0, 1.0].iter().flat_map(|y| [-1.0f32, 0.0, 1.0].map(|x| (x, *y))).filter(|h| *h != (0.0, 0.0)).collect(); + if response.drag_started() + && let Some(origin) = ui.input(|i| i.pointer.press_origin()) + { + // The pointer in the box's own frame. + let local = egui::vec2((origin - center).x * cos + (origin - center).y * sin, -(origin - center).x * sin + (origin - center).y * cos); + let handle = handles.iter().copied().find(|(x, y)| (local - egui::vec2(x * half.x, y * half.y)).length() <= 7.0); + let grab = if let Some((x, y)) = handle { + Some(Grab::Scale(x, y)) + } else if local.x.abs() <= half.x && local.y.abs() <= half.y { + Some(Grab::Move) + } else if local.x.abs() <= half.x + 18.0 && local.y.abs() <= half.y + 18.0 { + Some(Grab::Rotate) + } else { + None + }; + match grab { + Some(grab) => { + ui.data_mut(|d| d.insert_temp(drag_id, MapDrag { grab, from: m.clone(), origin })); + } + None => ui.data_mut(|d| d.remove::(drag_id)), + } + } + if let (Some(drag), Some(p)) = (ui.data(|d| d.get_temp::(drag_id)), response.interact_pointer_pos().filter(|_| response.dragged())) { + let (from_center, _, from_sin, from_cos) = box_of(&drag.from); + let round = |v: f64, places: i32| (v * 10f64.powi(places)).round() / 10f64.powi(places); + let limit = vectorcraft_effects::GRAPHIC_MAX_OFFSET; + let (lo, hi) = vectorcraft_effects::GRAPHIC_SCALE_RANGE; + match drag.grab { + Grab::Move => { + m.x = round(drag.from.x + f64::from(p.x - drag.origin.x) / scale, 2).clamp(-limit, limit); + m.y = round(drag.from.y + f64::from(p.y - drag.origin.y) / scale, 2).clamp(-limit, limit); + } + Grab::Scale(x, y) => { + let v = p - from_center; + let local = egui::vec2(v.x * from_cos + v.y * from_sin, -v.x * from_sin + v.y * from_cos); + if x != 0.0 && art.width() > 0.0 { + m.scale_x = round(f64::from(local.x.abs()) * 2.0 / (art.width() * scale) * 100.0, 2).clamp(lo, hi); + } + if y != 0.0 && art.height() > 0.0 { + m.scale_y = round(f64::from(local.y.abs()) * 2.0 / (art.height() * scale) * 100.0, 2).clamp(lo, hi); + } + } + Grab::Rotate => { + let angle = |q: egui::Pos2| f64::from((q - from_center).y.atan2((q - from_center).x)).to_degrees(); + // The screen's angles run clockwise. + let rotation = drag.from.rotation - (angle(p) - angle(drag.origin)); + m.rotation = round((rotation + 180.0).rem_euclid(360.0) - 180.0, 1); + } + } + } + if response.drag_stopped() { + ui.data_mut(|d| d.remove::(drag_id)); + } + let (center, half, sin, cos) = box_of(m); + let turned_now = |v: egui::Vec2| egui::vec2(v.x * cos - v.y * sin, v.x * sin + v.y * cos); + if m.rotation.abs() < 0.01 + && let Some(st) = app.session.active() + { + let keys = crate::panels::symbols::document_symbols(st); + let mut inner = ui.new_child(egui::UiBuilder::new().max_rect(view)); + inner.set_clip_rect(view.intersect(ui.clip_rect())); + let r = egui::Rect::from_center_size(center, half * 2.0); + crate::panels::symbols::art_chip(&inner, &st.doc, &keys, r, &m.symbol, art); + } + let corners: Vec = [(-1.0f32, -1.0f32), (1.0, -1.0), (1.0, 1.0), (-1.0, 1.0)] + .iter() + .map(|(x, y)| center + turned_now(egui::vec2(x * half.x, y * half.y))) + .collect(); + painter.add(egui::Shape::closed_line(corners, egui::Stroke::new(1.0, t.accent))); + for (x, y) in handles { + let at = center + turned_now(egui::vec2(x * half.x, y * half.y)); + let handle = egui::Rect::from_center_size(at, egui::vec2(6.0, 6.0)); + painter.rect_filled(handle, 0.0, egui::Color32::WHITE); + painter.rect_stroke(handle, 0.0, egui::Stroke::new(1.0, t.accent), egui::StrokeKind::Inside); + } +} + +/// While Map Art is open with Preview on, the surface it shows, outlined in red on the artboard. +pub(super) fn surface_outline(app: &crate::VectorcraftApp, ctx: &egui::Context, d: &Dialog) { + if !map_art_open(d) || !d.bool("preview") { + return; + } + let (Some(listed), Some(xf)) = (surfaces(app, ctx, d), app.canvas_xf()) else { return }; + let Some(surface) = listed.get(shown_surface(d, listed.len()).saturating_sub(1)) else { return }; + let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Middle, egui::Id::unique("map-art-outline"))).with_clip_rect(xf.rect); + for [a, b] in &surface.outline { + painter.line_segment([xf.to_screen(*a), xf.to_screen(*b)], egui::Stroke::new(1.5, egui::Color32::RED)); + } } /// Revolve (Classic)'s angle, cap and offset, and the edge of the profile's bounds the axis is at. @@ -40,6 +393,7 @@ pub(super) fn revolve_controls(ui: &mut egui::Ui, d: &mut Dialog, unit: Unit) { .map(|(label, value)| (json!(value), label)) .collect(); choice(ui, d, "edge", tl!("Axis side"), &sides); + map_art_button(ui, d); } /// The surface, then for Diffuse and Plastic the lighting sphere, the lights, Ambient Light, the diff --git a/crates/ui-egui/src/dialogs/width_point.rs b/crates/ui-egui/src/dialogs/width_point.rs index b0881b9082..56caf05845 100644 --- a/crates/ui-egui/src/dialogs/width_point.rs +++ b/crates/ui-egui/src/dialogs/width_point.rs @@ -16,10 +16,27 @@ //! `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. +//! +//! Opened on several selected width points (`indices`), the dialog edits all of them. Side 1, +//! Side 2 and Total Width show a value only where every point has it, and are blank otherwise. A +//! side width typed in sets that side of every point (both sides with the link on) and leaves the +//! other side of each point as it was; Total Width scales each point's own two sides to that total. +//! Turning the link on changes no width. When the points include a discontinuous one, Incoming +//! edits the incoming halves and Outgoing the outgoing halves, and both edit the continuous points. +//! With Adjust Adjoining Width Points, each changed point changes the nearest unselected point +//! before and after it in proportion, measured from the widths the points had when the dialog +//! opened. OK sets them all in one `stroke.widthProfile.set` (one undo step, none when nothing +//! changed), and Delete removes them all. The fields are `id`, `indices` (every selected profile +//! entry, both halves of a discontinuous point), `side1`, `side2`, `totalWidth` (null when the +//! points differ), `linked`, `adjustAdjoining`, and with a discontinuous point `outSide1`, +//! `outSide2`, `outTotalWidth` and `outLinked`. +//! +//! OK and Delete on existing points, one or several, are refused when those points changed since +//! the dialog opened or another document is active. use egui::vec2; use serde_json::{Value, json}; -use vectorcraft_doc::Unit; +use vectorcraft_doc::{Unit, WidthProfile}; use vectorcraft_engine::doc::NodeId; use vectorcraft_engine::width_point_pair; @@ -31,6 +48,30 @@ use crate::{VectorcraftApp, widgets}; /// The dialog kind of Width Point Edit. pub const KIND: &str = "widthPoint"; +/// Width points closer than this (in t) are at the same place, as the engine counts them. +const SAME_T: f64 = 1e-6; + +/// Side widths (points) closer than this show as one value. +const SAME_WIDTH: f64 = 1e-6; + +/// The working side widths of several points being edited. +const POINTS: &str = "__points"; +/// Their side widths when the dialog opened. +const OPEN: &str = "__open"; +/// Whether they include a discontinuous point (two sets of side widths shown). +const DISCONTINUOUS: &str = "__discontinuous"; +/// The uid of the document the dialog opened in. +const DOC: &str = "__doc"; +/// The place and side widths `[t, left, right]` (points) of the existing point the one-point dialog +/// opened on, and of the outgoing half of a discontinuous point. +const AT: &str = "__at"; + +/// The fields of each set of side widths of several points: Side 1, Side 2, Total Width and the +/// link, for the incoming set and the outgoing set. +const MANY: [[&str; 4]; 2] = [["side1", "side2", "totalWidth", "linked"], ["outSide1", "outSide2", "outTotalWidth", "outLinked"]]; +/// The number fields that show them. +const MANY_IDS: [[&str; 3]; 2] = [["wp-side1", "wp-side2", "wp-total"], ["wp-out-side1", "wp-out-side2", "wp-out-total"]]; + pub(super) const SPEC: DialogSpec = DialogSpec { heading: |_| tl!("Width Point Edit").into(), body, confirm, discard: Some("Delete"), min_width: 300.0, ..DialogSpec::FORM }; @@ -41,6 +82,11 @@ 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)) } +/// Width point `index` of `id` as [`point`] reads it, as an array. +fn entry_at(app: &VectorcraftApp, id: u64, index: usize) -> Option<[f64; 3]> { + point(app, id, index).map(|(t, l, r)| [t, l, r]) +} + /// 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. @@ -51,18 +97,283 @@ fn halves(app: &VectorcraftApp, id: u64, index: usize) -> Option<(usize, usize)> pair(index).or_else(|| index.checked_sub(1).and_then(pair)) } +/// One of several width points being edited: its profile index, its place, its side widths +/// (points) and the sets of side widths that edit it, `[incoming, outgoing]` (both for a continuous +/// point). +#[derive(Clone, Copy, Debug, PartialEq)] +struct Entry { + index: usize, + t: f64, + left: f64, + right: f64, + sets: [bool; 2], +} + +/// The entries held in field `key`. +fn entries(d: &Dialog, key: &str) -> Vec { + let entry = |e: &Value| { + let e = e.as_array()?; + let index = usize::try_from(e.first()?.as_u64()?).ok()?; + let (t, left, right) = (e.get(1)?.as_f64()?, e.get(2)?.as_f64()?, e.get(3)?.as_f64()?); + Some(Entry { index, t, left, right, sets: [e.get(4)?.as_bool()?, e.get(5)?.as_bool()?] }) + }; + d.fields.get(key).and_then(Value::as_array).map_or_else(Vec::new, |a| a.iter().filter_map(entry).collect()) +} + +fn entries_json(es: &[Entry]) -> Value { + json!(es.iter().map(|e| json!([e.index, e.t, e.left, e.right, e.sets[0], e.sets[1]])).collect::>()) +} + +/// What set `set` of `es` shows: Side 1, Side 2 and Total Width, each none where the points differ. +fn shown(es: &[Entry], set: usize) -> [Option; 3] { + let common = |f: fn(&Entry) -> f64| { + let mut values = es.iter().filter(|e| e.sets[set]).map(f); + let first = values.next()?; + values.all(|v| (v - first).abs() <= SAME_WIDTH).then_some(first) + }; + [common(|e| e.left), common(|e| e.right), common(|e| e.left + e.right)] +} + +/// Keep `es` as the working widths of `d`, and show them in its fields. A value set straight into a +/// field other than `typed` that OK refuses, and that is not the value the field showed, stays for +/// OK to refuse. +fn store(d: &mut Dialog, es: &[Entry], typed: Option<&str>) { + let old = entries(d, POINTS); + d.fields.insert(POINTS.into(), entries_json(es)); + let sets = if d.bool(DISCONTINUOUS) { 2 } else { 1 }; + for (set, keys) in MANY.iter().enumerate().take(sets) { + for ((key, value), was) in keys.iter().zip(shown(es, set)).zip(shown(&old, set)) { + let showed = reading(d, key).ok().flatten().zip(was).is_some_and(|(v, s)| (v - s).abs() <= SAME_WIDTH); + if Some(*key) != typed && number(d, key).is_err() && !showed { + continue; + } + d.fields.insert((*key).into(), json!(value)); + } + } +} + +/// A change typed into one set of side widths of several points. +#[derive(Clone, Copy, Debug)] +enum Edit { + Side1(f64), + Side2(f64), + Total(f64), +} + +/// Apply `edit` to every point that set `set` edits: a side width replaces that side (both sides +/// with `linked`), and Total Width scales each point's two sides to it (equal halves from nothing). +fn apply(es: &mut [Entry], set: usize, edit: Edit, linked: bool) { + for e in es.iter_mut().filter(|e| e.sets[set]) { + let (l, r) = match edit { + Edit::Side1(v) => (v, if linked { v } else { e.right }), + Edit::Side2(v) => (if linked { v } else { e.left }, v), + Edit::Total(v) => { + let sum = e.left + e.right; + if sum > 1e-9 { (e.left / sum * v, e.right / sum * v) } else { (v / 2.0, v / 2.0) } + } + }; + (e.left, e.right) = (l.max(0.0), r.max(0.0)); + } +} + +/// The width in field `key`, any finite width from nothing up (none when it is null or absent). +fn reading(d: &Dialog, key: &str) -> Result, String> { + let v = match d.fields.get(key) { + None | Some(Value::Null) => return Ok(None), + Some(Value::Number(n)) => n.as_f64(), + Some(Value::String(s)) => Unit::Points.parse(s), + Some(_) => None, + }; + match v { + Some(v) if v.is_finite() && v >= 0.0 => Ok(Some(v)), + _ => Err("invalid stroke widths".into()), + } +} + +/// The largest side width or Total Width a value typed in can set (points). +const MAX_WIDTH: f64 = 1.0e5; + +/// The number in field `key` that a value typed in can set (none when it is null or absent). +fn number(d: &Dialog, key: &str) -> Result, String> { + match reading(d, key)? { + Some(v) if v > MAX_WIDTH => Err("invalid stroke widths".into()), + v => Ok(v), + } +} + +/// The widths OK sets on several points: the working widths, with any value set straight into a +/// field (`ui.dialog.set`) that they do not show yet applied as typing it would, Total Width before +/// the sides. A value the field shows changes nothing, even a Total Width above [`MAX_WIDTH`]. +fn edited(d: &Dialog) -> Result, String> { + let mut es = entries(d, POINTS); + let sets = if d.bool(DISCONTINUOUS) { 2 } else { 1 }; + let before: Vec<_> = (0..sets).map(|set| shown(&es, set)).collect(); + for (set, shown) in before.iter().enumerate() { + let [k1, k2, kt, kl] = MANY[set]; + for (key, at) in [(kt, 2), (k1, 0), (k2, 1)] { + let Some(v) = reading(d, key)? else { continue }; + let same = shown[at].filter(|s| (s - v).abs() <= SAME_WIDTH); + // Only a value above the limit that the points already have passes it. + if v > MAX_WIDTH && !same.is_some_and(|s| s > MAX_WIDTH) { + return Err("invalid stroke widths".into()); + } + if same.is_some() { + continue; + } + let edit = match at { + 0 => Edit::Side1(v), + 1 => Edit::Side2(v), + _ => Edit::Total(v), + }; + apply(&mut es, set, edit, d.bool(kl)); + } + } + Ok(es) +} + +/// After `ui.dialog.set` sets `field` of several points' dialog: a side width or Total Width applies +/// as typing it does, so a value equal to the one shown still sets that side of every point (both +/// sides with the link on). A null or unreadable value is left for OK to skip or refuse, and a value +/// set later into another field keeps it. +pub(super) fn note_set(d: &mut Dialog, field: &str) { + if !d.fields.contains_key(OPEN) { + return; + } + let sets = if d.bool(DISCONTINUOUS) { 2 } else { 1 }; + for (set, keys) in MANY.iter().enumerate().take(sets) { + let Some(at) = keys[..3].iter().position(|k| *k == field) else { continue }; + let Ok(Some(v)) = number(d, field) else { return }; + let edit = match at { + 0 => Edit::Side1(v), + 1 => Edit::Side2(v), + _ => Edit::Total(v), + }; + let mut es = entries(d, POINTS); + apply(&mut es, set, edit, d.bool(keys[3])); + store(d, &es, Some(field)); + return; + } +} + +/// Width `v` of a point next to one whose width changes from `o` to `n`: in proportion, or by as +/// much from nothing, as `stroke.widthPoint.set` changes adjoining points. +fn scale(v: f64, o: f64, n: f64) -> f64 { + let width = if o > 1e-9 { + let product = v * n; + if product.is_finite() { product / o } else { (v.max(n) / o) * v.min(n) } + } else { + v + n - o + }; + width.max(0.0) +} + +/// What the width points `indices` (a JSON array) of `id` name. +enum Target { + /// One point, or the two halves of one discontinuous point: its first profile index. + One(usize), + /// Several places: every profile entry, in order. + Several(Vec), +} + +/// The outgoing half that pairs with each width point, as [`width_point_pair`] pairs them: point +/// `a` and the next one are the two halves of a discontinuous point when they are the only points +/// within [`SAME_T`] of `a`'s place. Each point counts the points at its place in the sorted +/// places, stopping at three. +fn pairs(points: &[(f64, f64, f64)]) -> Vec> { + let mut ts: Vec = points.iter().map(|q| q.0).filter(|t| !t.is_nan()).collect(); + ts.sort_by(f64::total_cmp); + let near = |a: usize, b: usize| (points[b].0 - points[a].0).abs() <= SAME_T; + (0..points.len()) + .map(|a| { + if a + 1 >= points.len() || !near(a, a + 1) || (a > 0 && near(a, a - 1)) { + return None; + } + let t = points[a].0; + let from = ts.partition_point(|&s| s < t - 2.0 * SAME_T); + let at = ts[from..].iter().take_while(|&&s| s <= t + 2.0 * SAME_T).filter(|&&s| (s - t).abs() <= SAME_T).take(3).count(); + (at == 2).then_some(a + 1) + }) + .collect() +} + +/// The width points `indices` of `id` names, each discontinuous point's two halves together. +fn target(app: &VectorcraftApp, id: u64, indices: &Value) -> Result { + const NONE: &str = "no such width point"; + let st = app.session.active().and_then(|s| s.doc.node(NodeId(id))).and_then(|n| n.appearance.stroke()).ok_or(NONE)?; + let points = st.profile.as_ref().map_or(&[][..], |p| &p.points[..]); + let list = indices.as_array().filter(|a| !a.is_empty()).ok_or(NONE)?; + let mut picked = list + .iter() + .map(|v| v.as_u64().and_then(|i| usize::try_from(i).ok()).filter(|i| *i < points.len())) + .collect::>>() + .ok_or(NONE)?; + picked.sort_unstable(); + picked.dedup(); + // The other half of each discontinuous point, paired as `stroke.widthPoint.set` pairs them. + let pairs = pairs(points); + let outgoing = |i: usize| i.checked_sub(1).is_some_and(|a| pairs[a] == Some(i)); + let halves: Vec = picked.iter().flat_map(|&i| [pairs[i], i.checked_sub(1).filter(|_| outgoing(i))]).flatten().collect(); + picked.extend(halves); + picked.sort_unstable(); + picked.dedup(); + // One point, or the two halves of one discontinuous point. + if picked.len() == 1 || (picked.len() == 2 && pairs[picked[0]] == Some(picked[1])) { + return Ok(Target::One(picked[0])); + } + if !(st.width.is_finite() && st.width > 0.0) { + return Err("object has no weighted stroke".into()); + } + let half = st.width / 2.0; + let entry = |i: usize| { + let (t, l, r) = points[i]; + Entry { index: i, t, left: l * half, right: r * half, sets: [!outgoing(i), pairs[i].is_none()] } + }; + Ok(Target::Several(picked.into_iter().map(entry).collect())) +} + +/// Open Width Point Edit on the several width points `es` of `id`. +fn open_several(app: &mut VectorcraftApp, id: u64, es: &[Entry], adjust: bool) { + let discontinuous = es.iter().any(|e| e.sets != [true, true]); + let indices: Vec = es.iter().map(|e| e.index).collect(); + let doc = app.session.active().map(|st| st.uid); + let mut d = Dialog::new( + KIND, + json!({"id": id, "indices": indices, "adjustAdjoining": adjust, DISCONTINUOUS: discontinuous, OPEN: entries_json(es), DOC: doc}), + ); + for (set, keys) in MANY.iter().enumerate().take(if discontinuous { 2 } else { 1 }) { + let linked = es.iter().filter(|e| e.sets[set]).all(|e| (e.left - e.right).abs() < 1e-9); + d.fields.insert(keys[3].into(), json!(linked)); + } + store(&mut d, es, None); + app.ui.dialog = Some(d); +} + /// 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. Either half of a discontinuous point opens -/// both. +/// (`{id, index?, t?, adjustAdjoining?}`), or for several existing points (`{id, indices, +/// adjustAdjoining?}`). Opening only samples the stroke: confirmation creates 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; let id = vectorcraft_tools::distort::stroke_owner(doc, NodeId(id)).0; - let index = match p.get("index").filter(|v| !v.is_null()) { + let given = |key: &str| p.get(key).is_some_and(|v| !v.is_null()); + let mut index = match p.get("index").filter(|v| !v.is_null()) { Some(v) => Some(v.as_u64().and_then(|i| usize::try_from(i).ok()).ok_or("no such width point")?), None => None, }; + if ["index", "indices", "t"].iter().filter(|key| given(key)).count() > 1 { + return Err("give only one of `index`, `indices` and `t`".into()); + } + if let Some(indices) = p.get("indices").filter(|v| !v.is_null()) { + match target(app, id, indices)? { + Target::One(i) => index = Some(i), + Target::Several(es) => { + let adjust = p.get("adjustAdjoining").and_then(Value::as_bool).unwrap_or(false); + open_several(app, id, &es, adjust); + return Ok(Value::Null); + } + } + } 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 { @@ -82,7 +393,10 @@ 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 mut fields = json!({"id": id, "index": index, "t": t, "side1": l, "side2": r, "linked": (l - r).abs() < 1e-9, "adjustAdjoining": adjust}); + let doc = app.session.active().map(|st| st.uid); + let at: Vec<_> = index.into_iter().chain(pair.map(|(_, out)| out)).filter_map(|i| entry_at(app, id, i)).collect(); + let linked = (l - r).abs() < 1e-9; + let mut fields = json!({"id": id, "index": index, "t": t, "side1": l, "side2": r, "linked": linked, "adjustAdjoining": adjust, DOC: doc, AT: at}); if let Some((_, out)) = pair { let (_, l, r) = point(app, id, out).ok_or("no such width point")?; for (key, value) in [ @@ -143,10 +457,63 @@ fn sides(ui: &mut egui::Ui, d: &mut Dialog, unit: Unit, keys: [&str; 3], ids: [& } } +/// Set `set` of the side widths of several points: Side 1 with its link, Side 2 and Total Width, +/// blank where the points differ. A value typed in changes every point the set edits; the link only +/// changes how later values apply. +fn sides_of_several(ui: &mut egui::Ui, d: &mut Dialog, unit: Unit, set: usize) { + let [k1, k2, kt, kl] = MANY[set]; + let ids = MANY_IDS[set]; + let value = |key: &str| reading(d, key).ok().flatten(); + let (s1, s2, total, linked) = (value(k1), value(k2), value(kt), d.bool(kl)); + let mut edit = None; + grid(ui, |ui| { + label(ui, tl!("Side 1:")); + ui.horizontal(|ui| { + if let Some(v) = widgets::num_field(ui, ids[0], s1, unit, 90.0) { + edit = Some((Edit::Side1(v), k1)); + } + 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(kl.into(), json!(!linked)); + } + }); + ui.end_row(); + label(ui, tl!("Side 2:")); + if let Some(v) = widgets::num_field(ui, ids[1], s2, unit, 90.0) { + edit = Some((Edit::Side2(v), k2)); + } + ui.end_row(); + label(ui, tl!("Total Width:")); + if let Some(v) = widgets::num_field(ui, ids[2], total, unit, 90.0) { + edit = Some((Edit::Total(v), kt)); + } + ui.end_row(); + }); + if let Some((Edit::Side1(v) | Edit::Side2(v) | Edit::Total(v), key)) = edit + && !(0.0..=MAX_WIDTH).contains(&v) + { + // Not a width it can set: the field keeps it for OK to refuse. + d.fields.insert(key.into(), if v.is_finite() { json!(v) } else { json!(v.to_string()) }); + } else if let Some((edit, key)) = edit { + // Values set straight into the fields count first, so typing does not lose them. + let mut es = edited(d).unwrap_or_else(|_| entries(d, POINTS)); + apply(&mut es, set, edit, linked); + store(d, &es, Some(key)); + } +} + 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) { + if d.fields.contains_key(OPEN) { + if d.bool(DISCONTINUOUS) { + widgets::section_header(ui, tl!("Incoming")); + ui.push_id("wp-incoming", |ui| sides_of_several(ui, d, unit, 0)); + widgets::section_header(ui, tl!("Outgoing")); + ui.push_id("wp-outgoing", |ui| sides_of_several(ui, d, unit, 1)); + } else { + sides_of_several(ui, d, unit, 0); + } + } else 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")); @@ -172,15 +539,150 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { false } +/// Whether the document the dialog opened in is still the active one. +fn same_document(app: &VectorcraftApp, d: &Dialog) -> Result<(), String> { + match (d.fields.get(DOC).and_then(Value::as_u64), app.session.active()) { + (Some(uid), Some(st)) if st.uid == uid => Ok(()), + _ => Err("no such width point".into()), + } +} + +/// `id`'s width profile and the stroke's half weight, when the points `open` are still where and as +/// wide as when the dialog opened, exactly. +fn opened_profile(app: &VectorcraftApp, id: u64, open: &[Entry]) -> Result<(WidthProfile, f64), String> { + const NONE: &str = "no such width point"; + let st = app.session.active().and_then(|s| s.doc.node(NodeId(id))).and_then(|n| n.appearance.stroke()).ok_or(NONE)?; + let half = st.width / 2.0; + if !(half.is_finite() && half > 0.0) { + return Err("object has no weighted stroke".into()); + } + let profile = st.profile.clone().ok_or(NONE)?; + if open.is_empty() || !open.windows(2).all(|w| w[0].index < w[1].index) { + return Err(NONE.into()); + } + for o in open { + let &(t, l, r) = profile.points.get(o.index).ok_or(NONE)?; + // The entries were read from this profile at this weight, so an unchanged point compares equal. + if t != o.t || l * half != o.left || r * half != o.right { + return Err(NONE.into()); + } + } + Ok((profile, half)) +} + +/// `id`'s width profile, as width factors `[t, left, right]`, with the selected points `open` set to +/// `new` (side widths in points). With `adjust`, each changed point also changes the nearest +/// unselected point at another place before it (unless it is the outgoing half of a discontinuous +/// point) and after it (unless it is the incoming half) in proportion. Every change is measured +/// from the widths when the dialog opened, and a point next to two changed points takes both +/// changes, in path order. +fn edited_profile(app: &VectorcraftApp, id: u64, open: &[Entry], new: &[Entry], adjust: bool) -> Result, String> { + let (WidthProfile { points: old }, half) = opened_profile(app, id, open)?; + if open.len() != new.len() || open.iter().zip(new).any(|(o, e)| o.index != e.index) { + return Err("no such width point".into()); + } + let mut points = old.clone(); + let selected = |j: usize| open.binary_search_by_key(&j, |o| o.index).is_ok(); + // The nearest unselected point before and after each point. + let (mut prev, mut next) = (vec![None; old.len()], vec![None; old.len()]); + let mut last = None; + for (j, p) in prev.iter_mut().enumerate() { + *p = last; + if !selected(j) { + last = Some(j); + } + } + last = None; + for (j, n) in next.iter_mut().enumerate().rev() { + *n = last; + if !selected(j) { + last = Some(j); + } + } + for (o, e) in open.iter().zip(new).filter(|_| adjust) { + if o.left == e.left && o.right == e.right { + continue; + } + // The point's place; both halves of a discontinuous point measure from the incoming half's. + let t = old[if o.sets[0] { o.index } else { o.index.saturating_sub(1) }].0; + // The nearest unselected point farther than SAME_T from that place on one side. + let nearest = |side: &[Option]| { + let mut j = side[o.index]; + while let Some(k) = j + && (old[k].0 - t).abs() <= SAME_T + { + j = side[k]; + } + j + }; + let before = nearest(&prev).filter(|_| o.sets[0]); + let after = nearest(&next).filter(|_| o.sets[1]); + for j in before.into_iter().chain(after) { + let q = &mut points[j]; + (q.1, q.2) = (scale(q.1, o.left / half, e.left / half), scale(q.2, o.right / half, e.right / half)); + } + } + for e in new { + (points[e.index].1, points[e.index].2) = (e.left / half, e.right / half); + } + if points.iter().any(|q| !q.1.is_finite() || !q.2.is_finite()) { + return Err("invalid stroke widths".into()); + } + Ok(points.into_iter().map(|(t, l, r)| [t, l, r]).collect()) +} + +/// OK or Delete on several width points. +fn confirm_several(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let id = d.fields.get("id").and_then(Value::as_u64).ok_or("no such width point")?; + let open = entries(d, OPEN); + same_document(app, d)?; + opened_profile(app, id, &open)?; + if d.bool("discard") { + let indices: Vec = open.iter().map(|e| e.index).collect(); + return run_and_close(app, "stroke.widthPoint.remove", json!({"id": id, "indices": indices})); + } + let new = edited(d)?; + if open.len() == new.len() && open.iter().zip(&new).all(|(o, e)| o.index == e.index && o.left == e.left && o.right == e.right) { + // Nothing changed: no command and no undo step. + app.ui.dialog = None; + return Ok(Value::Null); + } + let points = edited_profile(app, id, &open, &new, d.bool("adjustAdjoining"))?; + run_and_close(app, "stroke.widthProfile.set", json!({"ids": [id], "points": points})) +} + +/// Whether width point `index` of the one-point dialog's stroke, and the outgoing half `out` of a +/// discontinuous point, are still as they were when the dialog opened, and still pair. +fn unchanged_point(app: &VectorcraftApp, d: &Dialog, index: usize, out: Option) -> Result<(), String> { + const NONE: &str = "no such width point"; + let id = d.fields.get("id").and_then(Value::as_u64).ok_or(NONE)?; + let at: Vec<[f64; 3]> = d.fields.get(AT).cloned().and_then(|v| serde_json::from_value(v).ok()).ok_or(NONE)?; + let now: Vec<_> = std::iter::once(index).chain(out).map(|i| entry_at(app, id, i)).collect::>().ok_or(NONE)?; + // The widths are read at the stroke's current weight, so a changed weight changes them too, and + // a continuous point must still be one. + if now != at || halves(app, id, index) != out.map(|o| (index, o)) { + return Err(NONE.into()); + } + Ok(()) +} + fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + if d.fields.contains_key(OPEN) { + return confirm_several(app, d); + } 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") && index.is_null() { + // Deleting a prospective point discards the dialog; no document point exists yet. + app.ui.dialog = None; + return Ok(Value::Null); + } + // OK and Delete act only on the document and the points the dialog opened on. + same_document(app, d)?; + if let Some(index) = index.as_u64().and_then(|i| usize::try_from(i).ok()) { + unchanged_point(app, d, index, out.as_ref().and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok()))?; + } 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); - } let p = match out { Some(out) => json!({"id": id, "indices": [index, out]}), None => json!({"id": id, "index": index}), diff --git a/crates/ui-egui/src/dialogs/width_point/tests.rs b/crates/ui-egui/src/dialogs/width_point/tests.rs index bf32a6124f..0653c5fb19 100644 --- a/crates/ui-egui/src/dialogs/width_point/tests.rs +++ b/crates/ui-egui/src/dialogs/width_point/tests.rs @@ -573,3 +573,477 @@ fn a_compound_member_edits_both_halves_of_its_owners_point() { // 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)]); } + +/// [`app`]'s line with width points at a quarter (4 + 2 pt), the middle (4 + 4 pt) and three +/// quarters (2 + 6 pt). +fn three_app() -> (VectorcraftApp, u64) { + let (mut app, id) = app(); + let points = json!([[0, 1, 1], [0.25, 0.8, 0.4], [0.5, 0.8, 0.8], [0.75, 0.4, 1.2], [1, 1, 1]]); + app.run("stroke.widthProfile.set", json!({"ids": [id], "points": points})).unwrap(); + app.session.doc_mut().unwrap().mark_saved(); + (app, id) +} + +/// Open Width Point Edit on the points at a quarter and three quarters, set `fields` and press OK. +fn ok_on_two(fields: &[(&str, Value)]) -> (VectorcraftApp, u64) { + let (mut app, id) = three_app(); + app.run("ui.widthPointEdit", json!({"id": id, "indices": [3, 1, 3]})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + for (key, value) in fields { + d.fields.insert((*key).into(), value.clone()); + } + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + (app, id) +} + +#[test] +fn several_points_show_blank_fields_where_they_differ() { + let (mut app, id) = three_app(); + app.run("ui.widthPointEdit", json!({"id": id, "indices": [3, 1, 3]})).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(d.fields["indices"], json!([1, 3])); + for key in ["side1", "side2", "totalWidth"] { + assert!(d.fields[key].is_null(), "{key}: {:?}", d.fields[key]); + } + assert!(!d.bool("linked")); + assert!(d.fields.get("outSide1").is_none()); + let shown = frame(&mut app); + for s in ["Side 1:", "Side 2:", "Total Width:", "Adjust Adjoining Width Points", "Delete"] { + assert_eq!(shown.iter().filter(|t| *t == s).count(), 1, "{s} in {shown:?}"); + } + // Points with the same widths show them. + app.run("ui.widthPointEdit", json!({"id": id, "indices": [1, 2]})).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.fields["side1"].clone(), d.fields["side2"].clone(), d.fields["totalWidth"].clone()), (json!(4.0), Value::Null, Value::Null)); +} + +#[test] +fn a_side_width_sets_that_side_of_every_selected_point() { + let (app, id) = ok_on_two(&[("side1", json!(5))]); + assert_eq!(points(&app, id), vec![(0.0, 1.0, 1.0), (0.25, 1.0, 0.4), (0.5, 0.8, 0.8), (0.75, 1.0, 1.2), (1.0, 1.0, 1.0)]); + let (app, id) = ok_on_two(&[("side2", json!("3 pt"))]); + assert_eq!(points(&app, id), vec![(0.0, 1.0, 1.0), (0.25, 0.8, 0.6), (0.5, 0.8, 0.8), (0.75, 0.4, 0.6), (1.0, 1.0, 1.0)]); + // With the link on, a side width sets both sides. + let (app, id) = ok_on_two(&[("linked", json!(true)), ("side1", json!(3))]); + assert_eq!(points(&app, id), vec![(0.0, 1.0, 1.0), (0.25, 0.6, 0.6), (0.5, 0.8, 0.8), (0.75, 0.6, 0.6), (1.0, 1.0, 1.0)]); + // Total Width scales each point's own two sides. + let (app, id) = ok_on_two(&[("totalWidth", json!(12))]); + assert_eq!(points(&app, id), vec![(0.0, 1.0, 1.0), (0.25, 1.6, 0.8), (0.5, 0.8, 0.8), (0.75, 0.6, 1.8), (1.0, 1.0, 1.0)]); +} + +#[test] +fn ok_on_several_points_is_one_undo_step() { + let (mut app, id) = three_app(); + app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 20, "height": 20})).unwrap(); + app.run("edit.undo", json!({})).unwrap(); + let before = app.session.doc().unwrap().doc.clone(); + let history = creation_history(&app); + // Cancel, and OK with nothing changed, change nothing and keep redo. + for ok in [false, true] { + app.run("ui.widthPointEdit", json!({"id": id, "indices": [1, 3]})).unwrap(); + if ok { + super::super::confirm(&mut app).unwrap(); + } else { + app.ui.dialog.as_mut().unwrap().fields.insert("side1".into(), json!(9)); + super::super::cancel(&mut app); + } + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.doc().unwrap().doc, before); + assert_eq!(creation_history(&app), history); + } + app.run("ui.widthPointEdit", json!({"id": id, "indices": [1, 3]})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("side1".into(), json!(5)); + super::super::confirm(&mut app).unwrap(); + 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); +} + +#[test] +fn a_side_width_set_by_control_applies_even_when_it_is_the_value_shown() { + // Side 1 is 4 pt at both points; with the link on, setting it to 4 pt sets Side 2 to 4 pt too. + let (mut app, id) = three_app(); + app.run("ui.widthPointEdit", json!({"id": id, "indices": [1, 2]})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + super::super::set_field(d, "linked".into(), json!(true)); + super::super::set_field(d, "side1".into(), json!(4)); + assert_eq!((d.fields["side1"].clone(), d.fields["side2"].clone()), (json!(4.0), json!(4.0))); + super::super::confirm(&mut app).unwrap(); + assert_eq!(points(&app, id), vec![(0.0, 1.0, 1.0), (0.25, 0.8, 0.8), (0.5, 0.8, 0.8), (0.75, 0.4, 1.2), (1.0, 1.0, 1.0)]); +} + +#[test] +fn adjoining_points_follow_every_changed_point_once() { + // Side 1 doubles at a quarter and quadruples at three quarters: the start doubles, the end + // quadruples and the middle, next to both, takes both. + let (app, id) = ok_on_two(&[("adjustAdjoining", json!(true)), ("side1", json!(8))]); + assert_eq!(points(&app, id), vec![(0.0, 2.0, 1.0), (0.25, 1.6, 0.4), (0.5, 6.4, 0.8), (0.75, 1.6, 1.2), (1.0, 4.0, 1.0)]); +} + +#[test] +fn delete_removes_every_selected_point() { + let (mut app, id) = three_app(); + let before = app.session.doc().unwrap().doc.clone(); + let history = creation_history(&app); + app.run("ui.widthPointEdit", json!({"id": id, "indices": [1, 3]})).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), (0.5, 0.8, 0.8), (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); +} + +#[test] +fn several_points_with_a_discontinuous_one_edit_each_set() { + let (mut app, id) = app(); + let profile = json!([[0, 1, 1], [0.25, 0.8, 0.4], [0.5, 0.8, 0.8], [0.5, 0.4, 1.2], [1, 1, 1]]); + app.run("stroke.widthProfile.set", json!({"ids": [id], "points": profile})).unwrap(); + // One half of the discontinuous point brings the other. + app.run("ui.widthPointEdit", json!({"id": id, "indices": [1, 2]})).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(d.fields["indices"], json!([1, 2, 3])); + // Incoming: the quarter (4 + 2) and the incoming half (4 + 4); outgoing: the quarter and the + // outgoing half (2 + 6). + assert_eq!((d.fields["side1"].clone(), d.fields["side2"].clone()), (json!(4.0), Value::Null)); + assert_eq!((d.fields["outSide1"].clone(), d.fields["outSide2"].clone()), (Value::Null, Value::Null)); + let shown = frame(&mut app); + for s in ["Incoming", "Outgoing"] { + assert!(shown.iter().any(|t| t == s), "{s} in {shown:?}"); + } + assert_eq!(shown.iter().filter(|t| *t == "Side 1:").count(), 2); + app.ui.dialog.as_mut().unwrap().fields.insert("outSide2".into(), json!(5)); + super::super::confirm(&mut app).unwrap(); + assert_eq!(points(&app, id), vec![(0.0, 1.0, 1.0), (0.25, 0.8, 1.0), (0.5, 0.8, 0.8), (0.5, 0.4, 1.0), (1.0, 1.0, 1.0)]); +} + +/// Three width points each within 1e-6 of the next, but the outer two farther apart: with several +/// points selected, the first two are the halves of one discontinuous point and the third is a +/// continuous point, as `stroke.widthPoint.set` pairs them. +#[test] +fn several_points_in_a_chain_pair_as_the_engine_pairs_them() { + let (mut app, id) = app(); + 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]]); + app.run("stroke.widthProfile.set", json!({"ids": [id], "points": chain})).unwrap(); + app.run("ui.widthPointEdit", json!({"id": id, "indices": [2, 3]})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + assert_eq!(d.fields["indices"], json!([1, 2, 3])); + d.fields.insert("side1".into(), json!(5)); + d.fields.insert("outSide2".into(), json!(5)); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + // Incoming: the incoming half and the continuous point, both linked; outgoing: the outgoing + // half and the continuous point. + assert_eq!(points(&app, id), vec![(0.0, 1.0, 1.0), (0.5, 1.0, 1.0), (0.50000075, 0.4, 1.0), (0.5000015, 1.0, 1.0), (1.0, 1.0, 1.0)]); +} + +/// Three width points within 1e-6 of one another are no discontinuous point: selected together, +/// the dialog edits all three, and a discontinuous point alone still opens the one-point dialog. +#[test] +fn several_points_at_nearly_one_place_edit_them_all() { + let (mut app, id) = app(); + let profile = json!([[0, 1, 1], [0.5, 0.8, 0.8], [0.5000005, 0.4, 0.4], [0.5000009, 0.6, 0.6], [1, 1, 1]]); + app.run("stroke.widthProfile.set", json!({"ids": [id], "points": profile})).unwrap(); + app.run("ui.widthPointEdit", json!({"id": id, "indices": [1, 2, 3]})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + assert_eq!(d.fields["indices"], json!([1, 2, 3])); + d.fields.insert("linked".into(), json!(false)); + d.fields.insert("side2".into(), json!(5)); + 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, 0.8, 1.0), (0.5000005, 0.4, 1.0), (0.5000009, 0.6, 1.0), (1.0, 1.0, 1.0)]); + let (mut app, id) = pair_app(); + let pair = app.session.active().unwrap().doc.node(NodeId(id)).unwrap().appearance.stroke().unwrap().profile.clone().unwrap(); + let a = (0..pair.points.len()).find(|&a| width_point_pair(&pair.points, a).is_some()).unwrap(); + app.run("ui.widthPointEdit", json!({"id": id, "indices": [a + 1, a]})).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.fields["index"].clone(), d.fields["outIndex"].clone()), (json!(a), json!(a + 1))); +} + +/// With Adjust Adjoining Width Points, the outgoing half of a discontinuous point measures its +/// neighbors from the point's place, as `stroke.widthPoint.set` does: a point within 1e-6 of the +/// outgoing half but not of the place is the point after the pair. +#[test] +fn several_points_adjust_the_point_after_a_pair_from_its_place() { + let (mut app, id) = app(); + let profile = json!([[0, 1, 1], [0.25, 0.8, 0.8], [0.5, 0.8, 0.8], [0.5000009, 0.4, 0.4], [0.5000018, 0.6, 0.6], [1, 1, 1]]); + app.run("stroke.widthProfile.set", json!({"ids": [id], "points": profile})).unwrap(); + app.run("ui.widthPointEdit", json!({"id": id, "indices": [1, 3], "adjustAdjoining": true})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + assert_eq!(d.fields["indices"], json!([1, 2, 3])); + d.fields.insert("outSide1".into(), json!(4)); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + // The outgoing set is linked, so both sides of the outgoing half double, and so do both sides + // of the point after the pair; the end keeps its widths. + assert_eq!( + points(&app, id), + vec![(0.0, 1.0, 1.0), (0.25, 0.8, 0.8), (0.5, 0.8, 0.8), (0.5000009, 0.8, 0.8), (0.5000018, 1.2, 1.2), (1.0, 1.0, 1.0)] + ); +} + +#[test] +fn pairs_match_the_engine() { + let profiles: [&[(f64, f64, f64)]; 5] = [ + &[], + &[(0.5, 1.0, 1.0)], + &[(0.0, 1.0, 1.0), (0.5, 1.0, 1.0), (0.5, 1.0, 1.0), (1.0, 1.0, 1.0)], + &[(0.0, 1.0, 1.0), (0.5, 1.0, 1.0), (0.5, 1.0, 1.0), (0.5, 1.0, 1.0), (1.0, 1.0, 1.0)], + &[ + (0.5, 1.0, 1.0), + (0.50000075, 1.0, 1.0), + (0.5000015, 1.0, 1.0), + (0.5000024, 1.0, 1.0), + (f64::NAN, 1.0, 1.0), + (0.7, 1.0, 1.0), + (0.7, 1.0, 1.0), + ], + ]; + for points in profiles { + let engine: Vec> = (0..points.len()).map(|a| width_point_pair(points, a)).collect(); + assert_eq!(pairs(points), engine, "{points:?}"); + } +} + +#[test] +fn double_clicking_one_of_several_selected_points_and_typing_edits_them_all() { + let (mut app, id) = three_app(); + let view = app.view_info(); + app.select_tool("width"); + let send = |app: &mut VectorcraftApp, kind: PointerKind, x: f64, shift: bool| { + let mut ev = PointerEvent::new(kind, x, 150.0); + ev.mods.shift = shift; + crate::canvas::dispatch(app, &ev, view); + }; + for (x, shift) in [(150.0, false), (250.0, true)] { + send(&mut app, PointerKind::Down, x, shift); + send(&mut app, PointerKind::Up, x, shift); + } + for kind in [PointerKind::Down, PointerKind::Up, PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick] { + send(&mut app, kind, 150.0, false); + } + assert_eq!(app.ui.dialog.as_ref().expect("Width Point Edit opened").fields["indices"], json!([1, 3])); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + crate::theme::apply(&ctx, Default::default()); + for _ in 0..5 { + creation_dialog_frame(&mut app, &ctx, vec![]); + } + // The blank Side 1 has the focus: typing sets Side 1 of both points. + creation_dialog_frame(&mut app, &ctx, vec![egui::Event::Text("5 pt".into())]); + creation_dialog_click(&mut app, &ctx, "OK"); + assert!(app.ui.dialog.is_none()); + assert_eq!(points(&app, id), vec![(0.0, 1.0, 1.0), (0.25, 1.0, 0.4), (0.5, 0.8, 0.8), (0.75, 1.0, 1.2), (1.0, 1.0, 1.0)]); +} + +#[test] +fn a_negative_width_typed_for_several_points_is_refused() { + let (mut app, id) = three_app(); + let before = app.session.doc().unwrap().doc.clone(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + crate::theme::apply(&ctx, Default::default()); + app.run("ui.widthPointEdit", json!({"id": id, "indices": [1, 3]})).unwrap(); + for _ in 0..5 { + creation_dialog_frame(&mut app, &ctx, vec![]); + } + // The blank Side 1 has the focus. + creation_dialog_frame(&mut app, &ctx, vec![egui::Event::Text("-3 pt".into())]); + creation_dialog_click(&mut app, &ctx, "OK"); + assert!(app.ui.dialog.is_some(), "OK refuses it and the dialog stays open"); + assert_eq!(app.session.doc().unwrap().doc, before); +} + +#[test] +fn several_points_refuse_bad_indices() { + let (mut app, id) = three_app(); + let before = app.session.doc().unwrap().doc.clone(); + let history = creation_history(&app); + for p in [ + json!({"id": id, "indices": []}), + json!({"id": id, "indices": [1, -1]}), + json!({"id": id, "indices": [1, 1.5]}), + json!({"id": id, "indices": [1, "3"]}), + json!({"id": id, "indices": [1, 99]}), + json!({"id": id, "indices": 1}), + json!({"id": id, "indices": [1, 3], "index": 1}), + json!({"id": id, "indices": [1, 3], "t": 0.5}), + json!({"id": id, "index": 1, "t": 0.5}), + ] { + assert!(app.run("ui.widthPointEdit", p.clone()).is_err(), "{p}"); + assert!(app.ui.dialog.is_none(), "{p}"); + assert_eq!(app.session.doc().unwrap().doc, before); + assert_eq!(creation_history(&app), history); + } + // A point moved since the dialog opened is refused at OK, even with its widths unchanged. + app.run("ui.widthPointEdit", json!({"id": id, "indices": [1, 3]})).unwrap(); + app.run("stroke.widthPoint.set", json!({"id": id, "index": 1, "t": 0.3, "left": 4, "right": 2})).unwrap(); + let moved = app.session.doc().unwrap().doc.clone(); + app.ui.dialog.as_mut().unwrap().fields.insert("side1".into(), json!(5)); + assert!(super::super::confirm(&mut app).is_err()); + assert_eq!(app.session.doc().unwrap().doc, moved); + app.run("edit.undo", json!({})).unwrap(); + // So is Delete after a point was added before them. + app.run("ui.widthPointEdit", json!({"id": id, "indices": [1, 3]})).unwrap(); + app.run("stroke.widthPoint.set", json!({"id": id, "t": 0.1, "left": 5, "right": 5})).unwrap(); + let added = app.session.doc().unwrap().doc.clone(); + app.ui.dialog.as_mut().unwrap().fields.insert("discard".into(), json!(true)); + assert!(super::super::confirm(&mut app).is_err()); + assert_eq!(app.session.doc().unwrap().doc, added); + app.run("edit.undo", json!({})).unwrap(); + // A value that is not a width is refused at OK, and the dialog stays open. + app.run("ui.widthPointEdit", json!({"id": id, "indices": [1, 3]})).unwrap(); + for bad in [json!(-1), json!("wide"), json!(1.0e6)] { + app.ui.dialog.as_mut().unwrap().fields.insert("side1".into(), bad.clone()); + assert!(super::super::confirm(&mut app).is_err(), "{bad}"); + assert!(app.ui.dialog.is_some()); + assert_eq!(app.session.doc().unwrap().doc, before); + } +} + +#[test] +fn a_total_width_above_the_side_limit_does_not_block_ok() { + // Two points of 60000 + 60000 pt on the 10 pt stroke: Total Width shows 120000 pt. + let (mut app, id) = three_app(); + let wide = json!([[0, 1, 1], [0.25, 12000, 12000], [0.5, 0.8, 0.8], [0.75, 12000, 12000], [1, 1, 1]]); + app.run("stroke.widthProfile.set", json!({"ids": [id], "points": wide})).unwrap(); + let before = app.session.doc().unwrap().doc.clone(); + app.run("ui.widthPointEdit", json!({"id": id, "indices": [1, 3]})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["totalWidth"], json!(120000.0)); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.doc().unwrap().doc, before); + // A side width typed in applies with the total shown. + app.run("ui.widthPointEdit", json!({"id": id, "indices": [1, 3]})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("linked".into(), json!(false)); + super::super::set_field(d, "side1".into(), json!(5)); + 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.25, 1.0, 12000.0), (0.5, 0.8, 0.8), (0.75, 1.0, 12000.0), (1.0, 1.0, 1.0)]); + // A value set above the limit is refused even next to the 100000 pt shown. + let (mut app, id) = three_app(); + let edge = json!([[0, 1, 1], [0.25, 20000, 0.4], [0.5, 0.8, 0.8], [0.75, 20000, 1.2], [1, 1, 1]]); + app.run("stroke.widthProfile.set", json!({"ids": [id], "points": edge})).unwrap(); + app.run("ui.widthPointEdit", json!({"id": id, "indices": [1, 3]})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("side1".into(), json!(100000.0000005)); + assert!(super::super::confirm(&mut app).is_err()); +} + +#[test] +fn an_invalid_width_stays_for_ok_to_refuse() { + let (mut app, id) = three_app(); + let before = app.session.doc().unwrap().doc.clone(); + app.run("ui.widthPointEdit", json!({"id": id, "indices": [1, 3]})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + super::super::set_field(d, "side1".into(), json!("wide")); + super::super::set_field(d, "side2".into(), json!("3 pt")); + assert_eq!(d.fields["side1"], json!("wide")); + assert!(super::super::confirm(&mut app).is_err()); + assert!(app.ui.dialog.is_some()); + assert_eq!(app.session.doc().unwrap().doc, before); + // Corrected, it applies with the Side 2 already set. + super::super::set_field(app.ui.dialog.as_mut().unwrap(), "side1".into(), json!(5)); + super::super::confirm(&mut app).unwrap(); + assert_eq!(points(&app, id), vec![(0.0, 1.0, 1.0), (0.25, 1.0, 0.6), (0.5, 0.8, 0.8), (0.75, 1.0, 0.6), (1.0, 1.0, 1.0)]); +} + +#[test] +fn several_points_refuse_any_change_since_the_dialog_opened() { + let (mut app, id) = three_app(); + // A change too small to show in the fields. + app.run("ui.widthPointEdit", json!({"id": id, "indices": [1, 3]})).unwrap(); + let nudged = json!([[0, 1, 1], [0.25, 0.8000001, 0.4], [0.5, 0.8, 0.8], [0.75, 0.4, 1.2], [1, 1, 1]]); + app.run("stroke.widthProfile.set", json!({"ids": [id], "points": nudged})).unwrap(); + let changed = app.session.doc().unwrap().doc.clone(); + for field in ["side2", "discard"] { + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert(field.into(), if field == "discard" { json!(true) } else { json!(5) }); + assert!(super::super::confirm(&mut app).is_err(), "{field}"); + assert_eq!(app.session.doc().unwrap().doc, changed); + } + app.run("edit.undo", json!({})).unwrap(); + // OK with no width changed still checks the points. + app.run("ui.widthPointEdit", json!({"id": id, "indices": [1, 3]})).unwrap(); + app.run("stroke.widthPoint.set", json!({"id": id, "index": 1, "t": 0.3, "left": 4, "right": 2})).unwrap(); + assert!(super::super::confirm(&mut app).is_err()); + assert!(app.ui.dialog.is_some()); +} + +/// Open a second document holding [`three_app`]'s line with the same id, and make it active. +fn second_document(app: &mut VectorcraftApp, id: u64) { + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let other = app.run("shape.line", json!({"x1": 100, "y1": 150, "x2": 300, "y2": 150})).unwrap()["id"].as_u64().unwrap(); + assert_eq!(other, id, "the same id in both documents"); + app.run("stroke.set", json!({"ids": [other], "weight": 10})).unwrap(); + let points = json!([[0, 1, 1], [0.25, 0.8, 0.4], [0.5, 0.8, 0.8], [0.75, 0.4, 1.2], [1, 1, 1]]); + app.run("stroke.widthProfile.set", json!({"ids": [other], "points": points})).unwrap(); +} + +#[test] +fn ok_and_delete_act_only_in_the_document_the_dialog_opened_in() { + for opened in [json!({"indices": [1, 3]}), json!({"index": 2})] { + for field in ["side1", "discard"] { + let (mut app, id) = three_app(); + let mut p = opened.clone(); + p["id"] = json!(id); + app.run("ui.widthPointEdit", p).unwrap(); + let d = app.ui.dialog.take(); + second_document(&mut app, id); + let other = app.session.doc().unwrap().doc.clone(); + app.ui.dialog = d; + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert(field.into(), if field == "discard" { json!(true) } else { json!(5) }); + assert!(super::super::confirm(&mut app).is_err(), "{opened} {field}"); + assert_eq!(app.session.doc().unwrap().doc, other, "{opened} {field}"); + } + } +} + +#[test] +fn one_point_refuses_a_change_since_the_dialog_opened() { + for field in ["side1", "discard"] { + // A point added before the opened one moves it to the next index. + let (mut app, id) = app(); + app.run("ui.widthPointEdit", json!({"id": id, "index": 1})).unwrap(); + app.run("stroke.widthPoint.set", json!({"id": id, "t": 0.25, "left": 3, "right": 3})).unwrap(); + let added = app.session.doc().unwrap().doc.clone(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert(field.into(), if field == "discard" { json!(true) } else { json!(5) }); + assert!(super::super::confirm(&mut app).is_err(), "{field}"); + assert_eq!(app.session.doc().unwrap().doc, added, "{field}"); + // The outgoing half of a discontinuous point changed. + let (mut app, id) = pair_app(); + app.run("ui.widthPointEdit", json!({"id": id, "index": 1})).unwrap(); + app.run("stroke.widthProfile.set", json!({"ids": [id], "points": [[0, 1, 1], [0.5, 0.8, 0.8], [0.5, 0.2, 1.2], [1, 1, 1]]})).unwrap(); + let changed = app.session.doc().unwrap().doc.clone(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert(field.into(), if field == "discard" { json!(true) } else { json!(5) }); + assert!(super::super::confirm(&mut app).is_err(), "{field}"); + assert_eq!(app.session.doc().unwrap().doc, changed, "{field}"); + // The stroke weight changed. + let (mut app, id) = self::app(); + app.run("ui.widthPointEdit", json!({"id": id, "index": 1})).unwrap(); + app.run("stroke.set", json!({"ids": [id], "weight": 20})).unwrap(); + let heavier = app.session.doc().unwrap().doc.clone(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert(field.into(), if field == "discard" { json!(true) } else { json!(5) }); + assert!(super::super::confirm(&mut app).is_err(), "{field}"); + assert_eq!(app.session.doc().unwrap().doc, heavier, "{field}"); + // A later point moved onto the opened one makes it one half of a discontinuous point. + let (mut app, id) = self::app(); + app.run("stroke.widthPoint.set", json!({"id": id, "t": 0.75, "left": 3, "right": 3})).unwrap(); + app.run("ui.widthPointEdit", json!({"id": id, "index": 1})).unwrap(); + app.run("stroke.widthPoint.set", json!({"id": id, "index": 2, "t": 0.5, "left": 3, "right": 3})).unwrap(); + let paired = app.session.doc().unwrap().doc.clone(); + assert_eq!(points(&app, id)[1], (0.5, 0.8, 0.8), "the opened point keeps its index"); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert(field.into(), if field == "discard" { json!(true) } else { json!(5) }); + assert!(super::super::confirm(&mut app).is_err(), "{field}"); + assert_eq!(app.session.doc().unwrap().doc, paired, "{field}"); + } +} diff --git a/crates/ui-egui/src/edit_toolbar/tests.rs b/crates/ui-egui/src/edit_toolbar/tests.rs index 17d605936a..570ccc2549 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", "circle", "star"]); + assert_eq!(slots(&app)[ellipse], ["ellipse", "circle", "curvatureCircle", "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], ["circle", "star"]); + assert_eq!(slots(&app)[ellipse], ["circle", "curvatureCircle", "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", "circle", "slice"]); + assert_eq!(slots(&app)[ellipse], ["ellipse", "circle", "curvatureCircle", "slice"]); // A dimmed tool (in the toolbar already) doesn't drag. let before = slots(&app); let shown = frame(&mut app, &ctx, 2.9, vec![]); @@ -761,6 +761,7 @@ fn addon_tools_are_in_the_drawer_not_the_toolbars() { "cornerTool", "slideAnchor", "sharedEdge", + "tangentCircle", "smartPen", contour, box3d, @@ -776,7 +777,7 @@ fn addon_tools_are_in_the_drawer_not_the_toolbars() { let listed = |id: &str| { sections().iter().find(|(_, tools)| tools.iter().any(|t| t.id == id)).map(|(h, tools)| (*h, tools.iter().map(|t| t.id).collect::>())) }; - assert_eq!(listed("extendPath"), Some(("Path Precision Tools", addon[..7].to_vec()))); + assert_eq!(listed("extendPath"), Some(("Path Precision Tools", addon[..8].to_vec()))); assert_eq!(listed("smartPen"), Some(("Smart Pen", vec!["smartPen"]))); assert_eq!(listed(contour), Some(("Contour", vec![contour]))); assert_eq!(listed(box3d), Some(("3D Box", vec![box3d]))); diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index a88c0d0e1c..11e63b9a6a 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -478,6 +478,9 @@ font-technology Variable Променливи Check Spelling… Проверка на правописа… Choose a folder Избор на папка Choose… Избор… + Curvature Circle Tool Инструмент Кръг на кривината + Cusp Връх + Straight segment Прав сегмент Circle Кръг Circle Tool Инструмент Кръг Circle too large Кръгът е твърде голям @@ -581,6 +584,9 @@ font-technology Variable Променливи Box Channel Канал на квадрата Color box Цветови квадрат Color Wheel Options Опции на цветното колело + Show Harmony Показване на хармонията + Harmony Rule Правило за хармония + Harmony color Цвят от хармонията Color Type: Цветен тип: Color: Цвят: Colorize Оцветяване @@ -999,10 +1005,25 @@ font-technology Variable Променливи Duplicate Symbol Дублиране на символ Duplicate {kind} Style Дублиране на стил ({kind}) Dutch Нідерландски + PSD Import Options Опции за импортиране на PSD + Place PSD Вмъкване на PSD + Convert Layers to Objects Преобразуване на слоевете в обекти + Import Hidden Layers Импортиране на скритите слоеве + Flatten Layers to a Single Image Сплескване на слоевете в едно изображение + Import Slices Импортиране на отрязаните части DXF Import Options Опции за импортиране на DXF DXF Info Информация за DXF DXF Options Опции за DXF DXF Options Dialog Диалогов прозорец с опции за DXF + HP-GL Options Опции за HP-GL + HP-GL Options Dialog Диалогов прозорец с опции за HP-GL + Curve Tolerance: Толеранс на кривите: + Origin: Начало на координатите: + Pens: Писци: + One Pen per Color Един писец за всеки цвят + Pen Table Таблица на писците + Draw the Nearest Path Next Следващ да се чертае най-близкият път + Draw Inner Paths First Първо да се чертаят вътрешните пътища e.g. 1-3, 5 напр. 1-3, 5 Each page prints as one image, at the document's raster effects resolution. Всяка страница се отпечатва като едно изображение при разделителната способност на растерните ефекти на документа. Earth Tones Земни тонове @@ -1216,6 +1237,17 @@ font-technology Variable Променливи Shading Color Цвят на засенчването Black Overprint Черно с напечатване Draw Hidden Faces Изчертаване на скритите страни + Map Art… Картографиране на графика… + Map Art Картографиране на графика + First Surface Първа повърхност + Previous Surface Предишна повърхност + Next Surface Следваща повърхност + Last Surface Последна повърхност + Horizontal Scale Хоризонтален мащаб + Vertical Scale Вертикален мащаб + Scale to Fit Мащабиране до побиране + Shade Artwork Засенчване на графиката + Invisible Geometry Невидима геометрия Eyedropper Пипета Eyedropper Applies: Пипетата прилага: Eyedropper Options Опции за пипетата @@ -1320,6 +1352,17 @@ font-technology Variable Променливи Largest: Най-голям: Direction: Посока: Symbolism Tools Options Опции на символогичните инструменти + Tool: Инструмент: + Symbol Set Density Плътност на набор от символи + Symbol Sprayer Options Опции за разпръскване на символи + Scrunch: Свиване: + Spin: Завъртане: + Screen: Филтър: + Stain: Оцветяване: + Symbol Sizer Options Опции за мащабиране на символи + Proportional Resizing Пропорционално мащабиране + Resizing Affects Density Мащабирането влияе на плътността + Show Brush Size and Intensity Показване на размера и интензивността на четката Symbol Set Density: Плътност на набор от символи: Flat Image Плоско изображение Flat Logo Плоско лого @@ -1589,6 +1632,8 @@ font-technology Variable Променливи More Options Още опции Show Properties Panel Показване на панела със свойства Hide Corner Widget Скриване на приспособлението за ъгли + Hide Shape Widgets Скриване на приспособленията за фигури + Show Shape Widgets Показване на приспособленията за фигури Hide Corner Widget for angles greater than Скриване на приспособлението за ъгли за ъгли, по-големи от Hide Edges Скриване на ръбовете Hide Gradient Annotator Скриване на анотатора за градиент @@ -2128,6 +2173,15 @@ font-technology Variable Променливи YakumonoZenkaku YakumonoZenkaku Kinsoku Set Набор Kinsoku Kinsoku Shori Type Тип Kinsoku Shori + Kinsoku Shori Settings… Настройки на Kinsoku Shori… + Kinsoku Shori Settings Настройки на Kinsoku Shori + Kinsoku Sets Набори Kinsoku + Kinsoku Set Base Основа на набор Kinsoku + Based on: Въз основа на: + Cannot Start Line Не може да започва ред + Cannot End Line Не може да завършва ред + Hanging Punctuation Висяща пунктуация + Inseparable Characters Неразделими знаци Push In First Първо прибиране Push Out First Първо изтласкване Push Out Only Само изтласкване @@ -2244,6 +2298,7 @@ font-technology Variable Променливи Pressure Натиск Tilt Наклон Bearing Азимут + Stylus Wheel Колелце на писалката Shape: Форма: Bristle Length: Дължина на косъма: Bristle Density: Плътност на косъмчетата: @@ -2274,6 +2329,9 @@ font-technology Variable Променливи embedding for preview and print вграждане за преглед и печат embedding allowed вграждането е разрешено {file}; {embedding} {file}; {embedding} + unknown type неизвестен тип + {type}; {uses} {type}; {uses} +@plural {n} use|{n} uses {n} употреба|{n} употреби substituted: shown in {family} {style} ({detail}) заместен: показан с {family} {style} ({detail}) missing: shown in {family} {style} липсва: показан с {family} {style} missing липсва @@ -2544,6 +2602,8 @@ font-technology Variable Променливи Overprint and Transparency Flattener Options Опции за сплескване на надпечатването и прозрачността Custom… Потребителски… Custom Transparency Flattener Options Потребителски опции за сплескване на прозрачността + The PDF preset keeps the flattener preset but not the Custom… settings. PDF наборът запазва набора за сплескване, но не и настройките от „Потребителски…“. + PDF 1.3 files clip rasterized areas to their regions, and Overprint sets whether overprints are kept. Файловете PDF 1.3 изрязват растеризираните области по техните очертания, а „Надпечат“ определя дали надпечатванията се запазват. EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS няма алфа прозрачност, а „Надпечати“ определя дали надпечатванията се запазват. Overprint Black… Напечатване на черното върху друго… Overprint Fill Напечатване на запълването върху друго @@ -3047,6 +3107,9 @@ digits Malayalam Малаялам Rotate View to Selection Завъртане на изгледа спрямо селекцията Reset the rows to the artwork's colors Нулиране на редовете към цветовете на илюстрацията Color Theme Picker Избор на цветова тема + Undo Changes Отмяна на промените + Redo Changes Повторение на промените +@msg Recolor Artwork is not open „Преоцветяване на илюстрацията“ не е отворено Click or drag across the art to pick its colors; Shift adds more Щракнете или плъзнете през илюстрацията, за да вземете цветовете ѝ; Shift добавя още Prominent Colors Преобладаващи цветове Save All Colors Запази всички цветове @@ -3101,6 +3164,7 @@ digits Malayalam Малаялам A live rectangle's properties show one Corner Radius field for all four corners; off, each corner has its own field. Свойствата на динамичен правоъгълник показват едно поле „Радиус на ъгъла“ за четирите ъгъла; ако е изключено, всеки ъгъл има свое поле. What edits in the Transform panel transform: the object, its pattern tiles or both; Default follows Transform Pattern Tiles. Какво трансформират промените в панела „Трансформиране“: обекта, плочките на мострата му или и двете; „По подразбиране“ следва „Трансформиране на плочките на мострата“. With one symbol instance selected, the Transform panel uses the symbol's registration point as its reference point. Когато е избран един екземпляр на символ, панелът „Трансформиране“ използва регистрационната точка на символа като опорна точка. + Drawing a rectangle, ellipse, polygon, star or line opens the Transform panel if it is closed. Рисуването на правоъгълник, елипса, многоъгълник, звезда или линия отваря панела „Трансформиране“, ако е затворен. Darkens the canvas outside the artboards while the Artboard tool is active. Затъмнява платното извън работните области, докато инструментът „Работна област“ е активен. With Fade Region Outside Artboard on, the area outside the artboards stays dark while you drag with the Artboard tool. Когато „Затъмняване на областта извън работната област“ е включено, областта извън работните области остава тъмна, докато влачите с инструмента „Работна област“. How near, in pixels, the pointer must be to an object, anchor or handle for a click to select it. Колко близо в пиксели трябва да е показалецът до обект, опорна точка или дръжка, за да го избере щракване. @@ -3280,6 +3344,7 @@ digits Malayalam Малаялам Save Preset Запази предварителна настройка Save Document Preset Запази предварителна настройка на документа Save Preset… Запази предварителна настройка… + Save Summary… Запази обобщението… Save Print Preset Запази предварителна настройка за печат Save Recovery Data Запази данни за възстановяване Save Save for Web Preset Запази предварителна настройка за „Запази за уеб“ @@ -3573,6 +3638,7 @@ digits Malayalam Малаялам Show Modified Показване на променените Show Note Показване на бележка Show Options Показване на опциите + Show on Shape Creation Показване при създаване на фигура Show Recent Colors Показване на скорошните цветове Toggle RGB Percent Превключване на RGB в проценти Show Original Path Показване на оригиналния път @@ -3598,6 +3664,7 @@ digits Malayalam Малаялам Show Thumbnails Показване на миниатюри Show Tile Edge Показване на ръба на плочката Show Tints/Shades Показване на нюанси/затъмнения + Show Tool Cards Показване на карти на инструментите Show Tool Tips Показване на подсказки Show Transparency Grid Показване на шахматна дъска за прозрачност Show Video Rulers Показване на видеолинийки @@ -3681,6 +3748,8 @@ digits Malayalam Малаялам Outlines Контури Outlines with Source Image Контури с изходно изображение Source Image Изходно изображение + Split View Разделен изглед + Divider Разделител Press and hold to view the source image Задръжте натиснато, за да видите изходното изображение Image Trace View Изглед на трасиране на изображение Snap Options Опции за прилепване @@ -4096,6 +4165,8 @@ digits Malayalam Малаялам Unembed… Премахване на връзка… Ungroup Разгрупиране Ungroup Color Group Разгрупиране на цветова група + Color Group Options Опции за цветова група + Color Group Options… Опции за цветова група… Unicode Уникод Unicode (UTF-16) Уникод (UTF-16) Unicode (UTF-8) Уникод (UTF-8) @@ -5003,6 +5074,7 @@ axis Both И двете @msg the PDF is password-protected: give its password PDF файлът е защитен с парола: въведете паролата му @msg the PDF password is wrong паролата за PDF файла е грешна @msg the Save PDF dialog didn't open диалоговият прозорец за запазване на PDF не се отвори +@msg the Save PDF dialog is not open диалоговият прозорец за запазване на PDF не е отворен @msg the WMF header is damaged WMF заглавната част е повредена @msg the art could not be sampled графиката не можа да бъде проучена @msg the art has no bounds графиката няма граници @@ -5203,6 +5275,7 @@ axis Both И двете @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 +@msg give only one of `index`, `indices` and `t` задайте само едно от `index`, `indices` и `t` @msg column must be true or a number from 1 column трябва да е true или число от 1 нататък @msg x and y must both be numbers x и y трябва да са числа @msg "{0}" is not a colour: write it as #rrggbb "{0}" не е цвят: запишете го като #rrggbb @@ -5366,6 +5439,25 @@ axis Both И двете Preserve Embedded Profiles Запазване на вградените профили Convert to Working Space Преобразуване в работното пространство Preserve Numbers Запазване на числата + Profile Mismatches: Несъответствия на профила: + Ask When Opening Питане при отваряне + Ask When Pasting Питане при поставяне + Missing Profiles: Липсващи профили: + Embedded Profile Mismatch Несъответствие с вградения профил + Missing Profile Липсващ профил + Paste Profile Mismatch Несъответствие на профила при поставяне + “{name}” is not tagged with a {model} profile. „{name}“ няма {model} профил. + “{name}” is tagged with the {model} profile “{profile}”, which is not the {model} working space “{working}”. „{name}“ има {model} профил „{profile}“, който не е {model} работното пространство „{working}“. + Use the embedded profile Използване на вградения профил + Convert the colors to the working space Преобразуване на цветовете в работното пространство + Discard the embedded profile Отхвърляне на вградения профил + Leave as is Оставяне без промяна + Assign the working space Задаване на работното пространство + Assign profile: Задаване на профил: + Preserve the color numbers Запазване на цветовите стойности + Convert to keep the colors' appearance Преобразуване със запазване на вида на цветовете +@msg `{path}` goes with `{key}`: "assign" only `{path}` се използва само с `{key}`: "assign" + The pasted colors come from a document whose {model} profile is “{from}”; this document's is “{to}”. Поставените цветове идват от документ с {model} профил „{from}“; профилът на този документ е „{to}“. Texture Текстура Craquelure… Кракелюр… Grain… Зърнистост… @@ -7350,6 +7442,8 @@ breakText Glyphs Глифи # Path Precision Tools add-on: Tangent Circle. Tangent Circle… Допирателна окръжност… Tangent Circle Допирателна окръжност + Tangent Circle Tool Инструмент „Допирателна окръжност“ + No tangent circle here Тук няма допирателна окръжност Circle: Окръжност: @msg `ids` names an object twice `ids` посочва обект два пъти @msg select two or three paths or compound paths изберете два или три пътя или съставни пътя @@ -7365,6 +7459,16 @@ breakText Glyphs Глифи @msg `circle` is past the last circle found ({found}) `circle` е след последната намерена окръжност ({found}) @msg object {value} is not a path or compound path обект {value} не е път или съставен път @msg these shapes are too small to measure тези форми са твърде малки, за да бъдат измерени +# Path Precision Tools add-on: Add Bounding Rectangle and Add Bounding Circle. + Add Bounding Rectangle Добавяне на ограничаващ правоъгълник + Add Bounding Circle Добавяне на ограничаваща окръжност + Add Bounding Rectangle… Добавяне на ограничаващ правоъгълник… + Add Bounding Circle… Добавяне на ограничаваща окръжност… + One per Object По една за всеки обект +@msg nothing to enclose няма какво да се огради +@msg `offset` must be 0 or more `offset` трябва да е 0 или повече +@msg the shape would have no size фигурата няма да има размер +@msg the shape would reach past the edge of the canvas фигурата би излязла извън ръба на работната площ # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Инструменти за документи Save a Timestamped Copy Запазване на копие с дата и час @@ -7686,6 +7790,50 @@ breakText Glyphs Глифи @msg A joint does not close by {gap} pt. Една връзка не се затваря с {gap} pt. @msg Two panels pass through each other. Два панела минават един през друг. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer трябва да е "singleLine", "everyLine", "standardSingleLine" или "standardEveryLine" + Fine Stipple Фина точкова текстура + Dense Stipple Гъста точкова текстура + Soft Stipple Мека точкова текстура + Bold Stipple Едра точкова текстура + Paper Cutouts Хартиени изрезки + Coral Layers Коралови слоеве + Mint Layers Ментови слоеве + Midnight Layers Среднощни слоеве + Sunflower Sheet Слънчогледов лист + Rose Layers Розови слоеве + Monochrome Stack Монохромен стек +# Tool cards (General › Show Tool Cards): one sentence on what each tool does. + Shows a card with what a toolbar tool does and what its keys do instead of its tip; it needs Show Tool Tips. Показва карта с това какво прави инструментът от лентата и какво правят клавишите му вместо подсказката му; изисква Показване на подсказки. + Selects whole objects and groups to move, resize or rotate them. Избира цели обекти и групи, за да ги премествате, оразмерявате или завъртате. + Selects anchor points and path segments to reshape a path. Избира опорни точки и сегменти от път, за да промените формата на пътя. + Draws paths point by point, with straight segments and smooth curves. Рисува пътища точка по точка, с прави сегменти и плавни криви. + Draws smooth curves through the points you click. Рисува плавни криви през точките, върху които щраквате. + Adds text at a point, or in a frame you drag. Добавя текст в точка или в рамка, която изтегляте. + Draws rectangles and squares. Рисува правоъгълници и квадрати. + Draws rectangles with rounded corners. Рисува правоъгълници със закръглени ъгли. + Draws ellipses and circles. Рисува елипси и окръжности. + Draws polygons with sides of equal length. Рисува многоъгълници с равни страни. + Draws stars. Рисува звезди. + Turns objects around a reference point. Завърта обекти около опорна точка. + Flips objects across an axis through a reference point. Огледално обръща обекти спрямо ос през опорна точка. + Resizes objects from a reference point. Оразмерява обекти от опорна точка. + Slants objects from a reference point. Наклонява обекти от опорна точка. + Moves the view of the document. Премества изгледа на документа. + Magnifies or reduces the view. Увеличава или намалява изгледа. + Copies the color and other attributes of one object to the selection. Копира цвета и другите атрибути на един обект върху избраното. + Sets the direction and length of a gradient. Задава посоката и дължината на градиент. + Creates, selects and resizes artboards. Създава, избира и оразмерява работни площи. + Changes the width of a stroke along its length. Променя ширината на щрих по дължината му. + Bends art by dragging pins placed on it. Огъва графиката чрез плъзгане на поставени върху нея карфици. + Pushes the outlines of paths in the direction you drag. Избутва очертанията на пътищата в посоката на плъзгане. + Twists the outlines of paths into swirls. Усуква очертанията на пътищата във вихри. + Pulls the outlines of paths in toward the brush. Придърпва очертанията на пътищата към четката. + Pushes the outlines of paths out from the brush. Избутва очертанията на пътищата навън от четката. + Adds curved details along the outlines of paths. Добавя извити детайли по очертанията на пътищата. + Adds spiky details along the outlines of paths. Добавя остри детайли по очертанията на пътищата. + Adds wrinkles along the outlines of paths. Добавя гънки по очертанията на пътищата. + Moves, copies and resizes objects on the perspective grid. Премества, копира и оразмерява обекти в перспективната мрежа. + Makes a series of steps between two or more objects. Създава поредица от стъпки между два или повече обекта. + Places dimension lines that show measured lengths. Поставя размерни линии, които показват измерени дължини. Tap Кратко натискане Clear Hold Изчистване на задържането Hold Shortcuts Комбинации със задържане @@ -7702,3 +7850,7 @@ breakText Glyphs Глифи Pulse Stroke Пулсиращ щрих Round Flow Кръгъл поток Chisel Flow Скосен поток + +# #5804 native-picked raster editor (draft translations; native review welcome). + Edit Original with: Редактиране на оригинала с: +file-filter Applications Приложения diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 89c07a8fca..5f174c52e4 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -549,6 +549,17 @@ Shading Color Boja sjenčenja Black Overprint Crni pretisak Draw Hidden Faces Crtaj skrivene strane + Map Art… Mapiranje crteža… + Map Art Mapiranje crteža + First Surface Prva površina + Previous Surface Prethodna površina + Next Surface Sljedeća površina + Last Surface Posljednja površina + Horizontal Scale Horizontalna skala + Vertical Scale Vertikalna skala + Scale to Fit Skaliraj da stane + Shade Artwork Osjenči crtež + Invisible Geometry Nevidljiva geometrija Revolve… Rotaciono tijelo… Inflate… Napuhni… Materials… Materijali… @@ -673,6 +684,8 @@ Hide Gradient Annotator Sakrij anotator gradijenta Show Gradient Annotator Prikaži anotator gradijenta Hide Corner Widget Sakrij widget ugla + Hide Shape Widgets Sakrij widgete oblika + Show Shape Widgets Prikaži widgete oblika Show Corner Widget Prikaži widget ugla Guides Vodilice Hide Guides Sakrij vodilice @@ -793,6 +806,9 @@ Box Channel Kanal kvadrata Color box Kvadrat boje Color Wheel Options Opcije kotača boja + Show Harmony Prikaži harmoniju + Harmony Rule Pravilo harmonije + Harmony color Boja harmonije CSS Properties CSS svojstva Document Info Informacije o dokumentu Flattener Preview Pregled spljoštavanja @@ -1040,6 +1056,25 @@ Preserve Embedded Profiles Zadrži ugrađene profile Convert to Working Space Pretvori u radni prostor Preserve Numbers Zadrži brojeve + Profile Mismatches: Neusklađenost profila: + Ask When Opening Pitaj pri otvaranju + Ask When Pasting Pitaj pri lijepljenju + Missing Profiles: Nedostajući profili: + Embedded Profile Mismatch Neusklađenost ugrađenog profila + Missing Profile Nedostaje profil + Paste Profile Mismatch Neusklađenost profila pri lijepljenju + “{name}” is not tagged with a {model} profile. „{name}” nema {model} profil. + “{name}” is tagged with the {model} profile “{profile}”, which is not the {model} working space “{working}”. „{name}” ima {model} profil „{profile}”, koji nije {model} radni prostor „{working}”. + Use the embedded profile Koristi ugrađeni profil + Convert the colors to the working space Pretvori boje u radni prostor + Discard the embedded profile Odbaci ugrađeni profil + Leave as is Ostavi kako jeste + Assign the working space Dodijeli radni prostor + Assign profile: Dodijeli profil: + Preserve the color numbers Zadrži brojeve boja + Convert to keep the colors' appearance Pretvori da boje zadrže izgled +@msg `{path}` goes with `{key}`: "assign" only `{path}` ide samo uz `{key}`: "assign" + The pasted colors come from a document whose {model} profile is “{from}”; this document's is “{to}”. Zalijepljene boje dolaze iz dokumenta čiji je {model} profil „{from}”; profil ovog dokumenta je „{to}”. CMYK CMYK Texture Tekstura Craquelure… Krakelura… @@ -1122,6 +1157,15 @@ lighting Light Svjetlo Document Raster Effects Settings Dialog Dijalog postavki rasterskih efekata dokumenta Drop Shadow Sjena DXF Options Dialog Dijalog DXF opcija + HP-GL Options HP-GL opcije + HP-GL Options Dialog Dijalog HP-GL opcija + Curve Tolerance: Tolerancija krivulja: + Origin: Ishodište: + Pens: Pera: + One Pen per Color Jedno pero po boji + Pen Table Tabela pera + Draw the Nearest Path Next Sljedeću crtaj najbližu putanju + Draw Inner Paths First Prvo crtaj unutrašnje putanje Edit Toolbar Uredi traku s alatima Edit Views Uredi poglede Effect… Efekat… @@ -1697,6 +1741,7 @@ digits Malayalam Malajalam Roman Baseline Latinična osnovna linija Select a text object to edit its character attributes. Odaberite tekstualni objekat da uredite njegove atribute znakova. Show Options Prikaži opcije + Show on Shape Creation Prikaži pri kreiranju oblika Show Recent Colors Prikaži nedavne boje Toggle RGB Percent Uključi/isključi RGB u postocima Color Panel Options Opcije panela boja @@ -2003,6 +2048,8 @@ digits Malayalam Malajalam Snap Curves To Lines Hvataj krive na linije Tracing Result with Outlines Rezultat praćenja s obrisima Source Image Izvorna slika + Split View Podijeljeni prikaz + Divider Razdjelnik Threshold Prag Trace Prati Trace the image with the Default preset Prati sliku zadanim predloškom @@ -2152,6 +2199,15 @@ digits Malayalam Malajalam YakumonoZenkaku YakumonoZenkaku Kinsoku Set Kinsoku skup Kinsoku Shori Type Vrsta Kinsoku Shori + Kinsoku Shori Settings… Postavke Kinsoku Shori… + Kinsoku Shori Settings Postavke Kinsoku Shori + Kinsoku Sets Kinsoku skupovi + Kinsoku Set Base Osnova Kinsoku skupa + Based on: Zasnovano na: + Cannot Start Line Ne može početi red + Cannot End Line Ne može završiti red + Hanging Punctuation Viseća interpunkcija + Inseparable Characters Neodvojivi znakovi Push In First Prvo uvlačenje Push Out First Prvo izbacivanje Push Out Only Samo izbacivanje @@ -2552,6 +2608,12 @@ digits Malayalam Malajalam Units: Jedinice: Use Typographer's Quotes Koristi tipografske navodnike Center Artwork Centriraj crtež + PSD Import Options Opcije uvoza PSD + Place PSD Postavi PSD + Convert Layers to Objects Pretvori slojeve u objekte + Import Hidden Layers Uvezi skrivene slojeve + Flatten Layers to a Single Image Spljošti slojeve u jednu sliku + Import Slices Uvezi isječke DXF Import Options Opcije uvoza DXF Layout: Raspored: Merge Layers Spoji slojeve @@ -2698,6 +2760,7 @@ digits Malayalam Malajalam Rasters Rasteri Replaces the saved preset of that name. Zamjenjuje sačuvani predložak tog naziva. Save Preset… Sačuvaj postavku… + Save Summary… Sačuvaj sažetak… Vectors Vektori A saved copy of the selected preset Sačuvana kopija odabranog predloška Built-in presets don't change: New makes a copy you can edit. Ugrađeni predlošci se ne mijenjaju: Novo pravi kopiju koju možete uređivati. @@ -2943,6 +3006,8 @@ digits Malayalam Malajalam Overprint and Transparency Flattener Options Opcije pretiska i spljoštavanja prozirnosti Custom… Prilagođeno… Custom Transparency Flattener Options Prilagođene opcije spljoštavanja prozirnosti + The PDF preset keeps the flattener preset but not the Custom… settings. PDF postavka zadržava postavku spljoštavanja, ali ne i postavke iz Prilagođeno…. + PDF 1.3 files clip rasterized areas to their regions, and Overprint sets whether overprints are kept. PDF 1.3 datoteke isijecaju rasterizirana područja po njihovim regijama, a Pretisak određuje da li se pretisci zadržavaju. EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS nema alfa prozirnost, a Pretisci određuju da li se pretisci zadržavaju. Place the pages with the placement again Ponovo postavi stranice s postavljanjem Placement: Postavljanje: @@ -3037,6 +3102,9 @@ digits Malayalam Malajalam Recolor this row Ponovo oboji ovaj red Reset the rows to the artwork's colors Vrati redove na boje crteža Color Theme Picker Birač teme boja + Undo Changes Poništi promjene + Redo Changes Ponovi promjene +@msg Recolor Artwork is not open Ponovo oboji crtež nije otvoreno Click or drag across the art to pick its colors; Shift adds more Kliknite ili prevucite preko crteža da uzmete njegove boje; Shift dodaje još Prominent Colors Istaknute boje Save All Colors Sačuvaj sve boje @@ -3324,6 +3392,17 @@ antiAlias Sharp Oštro Swatch Name: Naziv uzorka boje: Diameter: Prečnik: Symbolism Tools Options Opcije alata simbolizam + Tool: Alat: + Symbol Set Density Gustoća skupa simbola + Symbol Sprayer Options Opcije raspršivača simbola + Scrunch: Sabijanje: + Spin: Okretanje: + Screen: Prozirnost: + Stain: Bojenje: + Symbol Sizer Options Opcije mijenjača veličine simbola + Proportional Resizing Proporcionalna promjena veličine + Resizing Affects Density Promjena veličine utiče na gustoću + Show Brush Size and Intensity Prikaži veličinu i intenzitet četke Symbol Set Density: Gustoća skupa simbola: Intensity: Intenzitet: Place PDF Postavi PDF @@ -3420,6 +3499,7 @@ antiAlias Sharp Oštro Pressure Pritisak Tilt Nagib Bearing Smjer + Stylus Wheel Kotačić olovke Random Nasumično Scatter Raspršeno Color Burn Tamnjenje boje @@ -3549,6 +3629,9 @@ theme Appearance Izgled embedding for preview and print ugrađivanje za pregled i štampu embedding allowed ugrađivanje dozvoljeno {file}; {embedding} {file}; {embedding} + unknown type nepoznata vrsta + {type}; {uses} {type}; {uses} +@plural {n} use|{n} uses {n} upotreba|{n} upotrebe|{n} upotreba substituted: shown in {family} {style} ({detail}) zamijenjen: prikazan fontom {family} {style} ({detail}) missing: shown in {family} {style} nedostaje: prikazan fontom {family} {style} missing nedostaje @@ -4134,6 +4217,7 @@ theme Appearance Izgled Show Pixel Grid (Above 600% Zoom) Prikaži mrežu piksela (iznad 600% zumiranja) Show Slice Numbers Prikaži brojeve isječaka Show The Home Screen When No Documents Are Open Prikaži početni ekran kad nijedan dokument nije otvoren + Show Tool Cards Prikaži kartice alata Show Tool Tips Prikaži opise alata Size/Leading Veličina/prored Snapping Tolerance Tolerancija hvatanja @@ -4259,6 +4343,8 @@ theme Appearance Izgled Spot Colors (0) Spot boje (0) Swatch Options Opcije uzorka boje Ungroup Color Group Razgrupiši grupu boja + Color Group Options Opcije grupe boja + Color Group Options… Opcije grupe boja… Copy to User Defined Kopiraj u korisnički definisano Swatch Library Biblioteka uzoraka boja Clear All Tabs Očisti sve tabulatore @@ -4568,6 +4654,7 @@ font-technology Variable Varijabilni A live rectangle's properties show one Corner Radius field for all four corners; off, each corner has its own field. Svojstva dinamičnog pravougaonika prikazuju jedno polje Poluprečnik ugla za sva četiri ugla; kada je isključeno, svaki ugao ima svoje polje. What edits in the Transform panel transform: the object, its pattern tiles or both; Default follows Transform Pattern Tiles. Šta transformišu izmjene u panelu Transformiši: objekat, pločice njegovog uzorka ili oboje; Zadano prati Transformiši pločice uzorka. With one symbol instance selected, the Transform panel uses the symbol's registration point as its reference point. Kada je odabrana jedna instanca simbola, panel Transformiši koristi tačku registracije simbola kao referentnu tačku. + Drawing a rectangle, ellipse, polygon, star or line opens the Transform panel if it is closed. Crtanje pravougaonika, elipse, poligona, zvijezde ili linije otvara panel Transformiši ako je zatvoren. Darkens the canvas outside the artboards while the Artboard tool is active. Zatamnjuje platno izvan radnih ploča dok je alat Radna ploča aktivan. With Fade Region Outside Artboard on, the area outside the artboards stays dark while you drag with the Artboard tool. Kada je uključeno Zatamni područje izvan radne ploče, područje izvan radnih ploča ostaje tamno dok prevlačite alatom Radna ploča. How near, in pixels, the pointer must be to an object, anchor or handle for a click to select it. Koliko blizu, u pikselima, pokazivač mora biti objektu, sidrenoj tački ili ručki da bi ga klik odabrao. @@ -4660,6 +4747,9 @@ font-technology Variable Varijabilni Couldn't copy to the system clipboard: {e} Nije moguće kopirati u sistemski međuspremnik: {e} Couldn't paste from the clipboard: {e} Nije moguće zalijepiti iz međuspremnika: {e} Channel Kanal + Curvature Circle Tool Alat Krug zakrivljenosti + Cusp Šiljak + Straight segment Ravan segment Circle Krug Circle Tool Alat za krug Circle too large Krug je prevelik @@ -5428,6 +5518,7 @@ imageTrace Outline Obris @msg the PDF is password-protected: give its password PDF je zaštićen lozinkom: navedite njegovu lozinku @msg the PDF password is wrong PDF lozinka je pogrešna @msg the Save PDF dialog didn't open dijalog Sačuvaj PDF se nije otvorio +@msg the Save PDF dialog is not open dijalog Sačuvaj PDF nije otvoren @msg the WMF header is damaged WMF zaglavlje je oštećeno @msg the art could not be sampled crtež nije moguće uzorkovati @msg the art has no bounds crtež nema granice @@ -5632,6 +5723,7 @@ imageTrace Outline Obris @msg onto must name a panel floating in another group onto mora navesti panel koji pluta u drugoj grupi @msg below and above must name a panel floating in another group below i above moraju navesti panel koji pluta u drugoj grupi @msg give only one of onto, below and above navedite samo jedno od onto, below i above +@msg give only one of `index`, `indices` and `t` navedite samo jedno od `index`, `indices` i `t` @msg column must be true or a number from 1 column mora biti true ili broj od 1 @msg x and y must both be numbers x i y moraju oba biti brojevi @msg "{0}" is not a colour: write it as #rrggbb "{0}" nije boja: napišite je kao #rrggbb @@ -7399,6 +7491,8 @@ shape Open Otvoren # Path Precision Tools add-on: Tangent Circle. Tangent Circle… Tangentna kružnica… Tangent Circle Tangentna kružnica + Tangent Circle Tool Alat tangentna kružnica + No tangent circle here Ovdje nema tangentne kružnice Circle: Kružnica: @msg `ids` names an object twice `ids` navodi objekat dvaput @msg select two or three paths or compound paths odaberite dvije ili tri putanje ili složene putanje @@ -7414,6 +7508,16 @@ shape Open Otvoren @msg `circle` is past the last circle found ({found}) `circle` je iza posljednje pronađene kružnice ({found}) @msg object {value} is not a path or compound path objekat {value} nije putanja ni složena putanja @msg these shapes are too small to measure ovi oblici su premali za mjerenje +# Path Precision Tools add-on: Add Bounding Rectangle and Add Bounding Circle. + Add Bounding Rectangle Dodaj granični pravougaonik + Add Bounding Circle Dodaj granični krug + Add Bounding Rectangle… Dodaj granični pravougaonik… + Add Bounding Circle… Dodaj granični krug… + One per Object Jedan po objektu +@msg nothing to enclose nema ničega za obuhvatiti +@msg `offset` must be 0 or more `offset` mora biti 0 ili više +@msg the shape would have no size oblik ne bi imao veličinu +@msg the shape would reach past the edge of the canvas oblik bi prešao rub radne površine # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Alati za dokument Save a Timestamped Copy Sačuvaj kopiju s datumom i vremenom @@ -7741,6 +7845,50 @@ shape Open Otvoren @msg A joint does not close by {gap} pt. Spoj se ne zatvara za {gap} pt. @msg Two panels pass through each other. Dva panela prolaze jedan kroz drugi. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer mora biti "singleLine", "everyLine", "standardSingleLine" ili "standardEveryLine" + Fine Stipple Fino tačkasto sjenčenje + Dense Stipple Gusto tačkasto sjenčenje + Soft Stipple Meko tačkasto sjenčenje + Bold Stipple Krupno tačkasto sjenčenje + Paper Cutouts Papirni izrezi + Coral Layers Koraljni slojevi + Mint Layers Mentini slojevi + Midnight Layers Ponoćni slojevi + Sunflower Sheet List suncokreta + Rose Layers Ružičasti slojevi + Monochrome Stack Jednobojni slojevi +# Tool cards (General › Show Tool Cards): one sentence on what each tool does. + Shows a card with what a toolbar tool does and what its keys do instead of its tip; it needs Show Tool Tips. Prikazuje karticu s onim što alat s trake radi i što rade njegove tipke, umjesto njegovog opisa; potrebno je Prikaži opise alata. + Selects whole objects and groups to move, resize or rotate them. Odabire cijele objekte i grupe radi pomjeranja, promjene veličine ili rotacije. + Selects anchor points and path segments to reshape a path. Odabire sidrene tačke i segmente putanje radi promjene oblika putanje. + Draws paths point by point, with straight segments and smooth curves. Crta putanje tačku po tačku, s ravnim segmentima i glatkim krivuljama. + Draws smooth curves through the points you click. Crta glatke krivulje kroz tačke na koje kliknete. + Adds text at a point, or in a frame you drag. Dodaje tekst u tački ili u okviru koji povučete. + Draws rectangles and squares. Crta pravougaonike i kvadrate. + Draws rectangles with rounded corners. Crta pravougaonike sa zaobljenim uglovima. + Draws ellipses and circles. Crta elipse i krugove. + Draws polygons with sides of equal length. Crta mnogouglove sa stranicama jednake dužine. + Draws stars. Crta zvijezde. + Turns objects around a reference point. Rotira objekte oko referentne tačke. + Flips objects across an axis through a reference point. Zrcali objekte preko ose koja prolazi kroz referentnu tačku. + Resizes objects from a reference point. Mijenja veličinu objekata od referentne tačke. + Slants objects from a reference point. Naginje objekte od referentne tačke. + Moves the view of the document. Pomjera prikaz dokumenta. + Magnifies or reduces the view. Uvećava ili umanjuje prikaz. + Copies the color and other attributes of one object to the selection. Kopira boju i druge atribute jednog objekta na odabir. + Sets the direction and length of a gradient. Postavlja smjer i dužinu gradijenta. + Creates, selects and resizes artboards. Kreira i odabire radne površine i mijenja im veličinu. + Changes the width of a stroke along its length. Mijenja širinu poteza duž njegove dužine. + Bends art by dragging pins placed on it. Savija crtež povlačenjem pribadača postavljenih na njega. + Pushes the outlines of paths in the direction you drag. Gura obrise putanja u smjeru u kojem povlačite. + Twists the outlines of paths into swirls. Uvija obrise putanja u vrtloge. + Pulls the outlines of paths in toward the brush. Privlači obrise putanja prema četkici. + Pushes the outlines of paths out from the brush. Gura obrise putanja prema van od četkice. + Adds curved details along the outlines of paths. Dodaje zakrivljene detalje duž obrisa putanja. + Adds spiky details along the outlines of paths. Dodaje šiljaste detalje duž obrisa putanja. + Adds wrinkles along the outlines of paths. Dodaje bore duž obrisa putanja. + Moves, copies and resizes objects on the perspective grid. Pomjera, kopira i mijenja veličinu objekata na mreži perspektive. + Makes a series of steps between two or more objects. Pravi niz koraka između dva ili više objekata. + Places dimension lines that show measured lengths. Postavlja kotne linije koje prikazuju izmjerene dužine. Tap Kratki pritisak Clear Hold Očisti zadržavanje Hold Shortcuts Prečice zadržavanjem @@ -7757,3 +7905,7 @@ shape Open Otvoren Pulse Stroke Pulsirajući potez Round Flow Okrugli tok Chisel Flow Kosi tok + +# #5804 native-picked raster editor (draft translations; native review welcome). + Edit Original with: Uredi original pomoću: +file-filter Applications Aplikacije diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 72ae5a5384..40f622a5d5 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -490,6 +490,7 @@ antiAlias Sharp Nítid Batch Lot Batch… Lot… Bearing Orientació + Stylus Wheel Roda del llapis Before Last: Abans de l’últim: Begin Recording Comença a enregistrar Exclude from playback Exclou de la reproducció @@ -721,6 +722,9 @@ antiAlias Sharp Nítid Chrome… Crom… Circle Cercle Circle Tool Eina de cercle + Curvature Circle Tool Eina Cercle de curvatura + Cusp Punta + Straight segment Segment recte Circle too large El cercle és massa gran Circle (open) Cercle (obert) Classic Clàssic @@ -792,6 +796,25 @@ antiAlias Sharp Nítid Preserve Embedded Profiles Conserva els perfils incrustats Convert to Working Space Converteix a l'espai de treball Preserve Numbers Conserva els números + Profile Mismatches: Discrepàncies de perfil: + Ask When Opening Pregunta en obrir + Ask When Pasting Pregunta en enganxar + Missing Profiles: Perfils que falten: + Embedded Profile Mismatch Discrepància del perfil incrustat + Missing Profile Falta el perfil + Paste Profile Mismatch Discrepància de perfil en enganxar + “{name}” is not tagged with a {model} profile. “{name}” no té cap perfil {model}. + “{name}” is tagged with the {model} profile “{profile}”, which is not the {model} working space “{working}”. “{name}” té el perfil {model} “{profile}”, que no és l’espai de treball {model} “{working}”. + Use the embedded profile Utilitza el perfil incrustat + Convert the colors to the working space Converteix els colors a l’espai de treball + Discard the embedded profile Descarta el perfil incrustat + Leave as is Deixa-ho tal com està + Assign the working space Assigna l’espai de treball + Assign profile: Assigna el perfil: + Preserve the color numbers Conserva els valors dels colors + Convert to keep the colors' appearance Converteix per conservar l’aspecte dels colors +@msg `{path}` goes with `{key}`: "assign" only `{path}` només va amb `{key}`: "assign" + The pasted colors come from a document whose {model} profile is “{from}”; this document's is “{to}”. Els colors enganxats provenen d’un document amb el perfil {model} “{from}”; el d’aquest document és “{to}”. Coarse Dots Punts gruixuts Collapse Panel Group Replega el grup de panells Cycle Display Sizes Alterna les mides de visualització @@ -859,6 +882,9 @@ antiAlias Sharp Nítid Box Channel Canal del quadre Color box Quadre de color Color Wheel Options Opcions de la roda de colors + Show Harmony Mostra l’harmonia + Harmony Rule Regla d’harmonia + Harmony color Color de l’harmonia Color Type: Tipus de color: Color wheel Roda de color Color: Color: @@ -1465,10 +1491,25 @@ antiAlias Sharp Nítid Duplication Duplicació Dutch Neerlandès DWG (use DXF) DWG (feu servir DXF) + PSD Import Options Opcions d’importació de PSD + Place PSD Col·loca un PSD + Convert Layers to Objects Converteix les capes en objectes + Import Hidden Layers Importa les capes amagades + Flatten Layers to a Single Image Aplana les capes en una sola imatge + Import Slices Importa els talls DXF Import Options Opcions d’importació de DXF DXF Info Informació del DXF DXF Options Opcions del DXF DXF Options Dialog Diàleg d’opcions del DXF + HP-GL Options Opcions de l’HP-GL + HP-GL Options Dialog Diàleg d’opcions de l’HP-GL + Curve Tolerance: Tolerància de les corbes: + Origin: Origen: + Pens: Plomes: + One Pen per Color Una ploma per color + Pen Table Taula de plomes + Draw the Nearest Path Next Dibuixa després el traçat més proper + Draw Inner Paths First Dibuixa primer els traçats interiors e.g. 1-3, 5 p. ex. 1-3, 5 Each Design Represents: Cada disseny representa: Each entry of the file is matched to a VectorCraft tool, command or panel. Check the matches and answer what is left. Cada entrada del fitxer s’associa a una eina, una ordre o un panell del VectorCraft. Comprova les coincidències i respon a les que quedin. @@ -1717,6 +1758,15 @@ antiAlias Sharp Nítid Shading Color Color de l’ombra Black Overprint Negre en sobreimpressió Draw Hidden Faces Dibuixa les cares ocultes + Map Art… Mapatge d’art… + Map Art Mapatge d’art + First Surface Primera superfície + Previous Surface Superfície anterior + Next Surface Superfície següent + Last Surface Última superfície + Scale to Fit Escala per ajustar + Shade Artwork Ombreja l’art + Invisible Geometry Geometria invisible Eyedropper Comptagotes Eyedropper Applies: El comptagotes aplica: Eyedropper Options Opcions del comptagotes @@ -2410,6 +2460,15 @@ digits Malayalam Malaiàlam Kind Tipus Kinsoku Set Conjunt Kinsoku Kinsoku Shori Type Tipus de Kinsoku Shori + Kinsoku Shori Settings… Configuració de Kinsoku Shori… + Kinsoku Shori Settings Configuració de Kinsoku Shori + Kinsoku Sets Conjunts Kinsoku + Kinsoku Set Base Base del conjunt Kinsoku + Based on: Basat en: + Cannot Start Line No pot començar la línia + Cannot End Line No pot acabar la línia + Hanging Punctuation Puntuació penjant + Inseparable Characters Caràcters inseparables Kite Estel Knife Ganivet Knockout Group Grup knockout @@ -3228,6 +3287,8 @@ digits Malayalam Malaiàlam Overprint and Transparency Flattener Options Opcions de l’aplanador de sobremipressió i transparència Custom… Personalitzat… Custom Transparency Flattener Options Opcions personalitzades de l’aplanador de transparència + The PDF preset keeps the flattener preset but not the Custom… settings. El preajust PDF conserva el preajust d’aplanament, però no la configuració de Personalitzat…. + PDF 1.3 files clip rasterized areas to their regions, and Overprint sets whether overprints are kept. Els fitxers PDF 1.3 retallen les àrees rasteritzades a les seves regions, i Sobrimpressió determina si es conserven les sobreimpressions. EPS has no alpha transparency, and Overprints sets whether overprints are kept. L’EPS no té transparència alfa, i Sobreimpressions determina si es conserven les sobreimpressions. Overprint Black… Sobrimpressió del negre… Overprint Fill Sobrimpressió del farciment @@ -3317,6 +3378,9 @@ digits Malayalam Malaiàlam embedding for preview and print incrustació per a la visualització i la impressió embedding allowed incrustació permesa {file}; {embedding} {file}; {embedding} + unknown type tipus desconegut + {type}; {uses} {type}; {uses} +@plural {n} use|{n} uses {n} ús|{n} usos substituted: shown in {family} {style} ({detail}) substituït: es mostra amb {family} {style} ({detail}) missing: shown in {family} {style} absent: es mostra amb {family} {style} missing absent @@ -3883,6 +3947,9 @@ digits Malayalam Malaiàlam Reset Ruler Origin Restableix l’origen de les regles Reset the rows to the artwork's colors Restableix les files als colors de l’obra Color Theme Picker Selector de tema de colors + Undo Changes Desfés els canvis + Redo Changes Refés els canvis +@msg Recolor Artwork is not open Recoloreix la il·lustració no és obert Click or drag across the art to pick its colors; Shift adds more Feu clic o arrossegueu sobre l’obra per agafar-ne els colors; Maj n’afegeix més Prominent Colors Colors predominants Save All Colors Desa tots els colors @@ -3952,6 +4019,7 @@ digits Malayalam Malaiàlam A live rectangle's properties show one Corner Radius field for all four corners; off, each corner has its own field. Les propietats d’un rectangle dinàmic mostren un sol camp Radi de cantonada per a les quatre cantonades; desactivada, cada cantonada té el seu propi camp. What edits in the Transform panel transform: the object, its pattern tiles or both; Default follows Transform Pattern Tiles. Què transformen els canvis al panell Transforma: l’objecte, les peces del seu motiu o tots dos; Predeterminat segueix Transforma les peces del motiu. With one symbol instance selected, the Transform panel uses the symbol's registration point as its reference point. Amb una instància de símbol seleccionada, el panell Transforma fa servir el punt de registre del símbol com a punt de referència. + Drawing a rectangle, ellipse, polygon, star or line opens the Transform panel if it is closed. Dibuixar un rectangle, una el·lipse, un polígon, una estrella o una línia obre el panell Transforma si està tancat. Darkens the canvas outside the artboards while the Artboard tool is active. Enfosqueix el llenç fora dels taulers mentre l’eina Tauler està activa. With Fade Region Outside Artboard on, the area outside the artboards stays dark while you drag with the Artboard tool. Amb Enfosqueix la regió fora del tauler activat, l’àrea fora dels taulers continua fosca mentre arrossegueu amb l’eina Tauler. How near, in pixels, the pointer must be to an object, anchor or handle for a click to select it. A quina distància, en píxels, ha d’estar el punter d’un objecte, punt d’ancoratge o tirador perquè un clic el seleccioni. @@ -4182,6 +4250,7 @@ digits Malayalam Malaiàlam Save Preset Desa el preajust Save Document Preset Desa el preajust de document Save Preset… Desa el preajust… + Save Summary… Desa el resum… Save Print Preset Desa el preajust d’impressió Save Recovery Data Desa les dades de recuperació Save Save for Web Preset Desa el preajust Desa per a web @@ -4862,6 +4931,8 @@ digits Malayalam Malaiàlam Show Color Groups Mostra els grups de colors Show Color Swatches Mostra les mostres de color Show Corner Widget Mostra el giny de cantonada + Hide Shape Widgets Amaga els ginys de forma + Show Shape Widgets Mostra els ginys de forma Show Cross Hairs Mostra la retícula Show East Asian Options Mostra les opcions d’Àsia oriental Show Edges Mostra les vores @@ -4888,6 +4959,7 @@ digits Malayalam Malaiàlam Show Modified Mostra els modificats Show Note Mostra la nota Show Options Mostra les opcions + Show on Shape Creation Mostra en crear formes Show Recent Colors Mostra els colors recents Toggle RGB Percent Commuta RGB en percentatge Show Original Path Mostra el traçat original @@ -4913,6 +4985,7 @@ digits Malayalam Malaiàlam Show Tile Edge Mostra la vora del mosaic Show Tints/Shades Mostra els tons/ombres Show Tool Group Labels Mostra les etiquetes dels grups d’eines + Show Tool Cards Mostra les fitxes d’eines Show Tool Tips Mostra els consells d’eines Show Transparency Grid Mostra la quadrícula de transparència Show Video Rulers Mostra les regles de vídeo @@ -5040,6 +5113,8 @@ digits Malayalam Malaiàlam Source code on GitHub Codi font a GitHub Source Folder: Carpeta d’origen: Source Image Imatge d’origen + Split View Vista dividida + Divider Divisor Source Sans 3 Source Sans 3 Space After Paragraph Espai després del paràgraf Space Before Paragraph Espai abans del paràgraf @@ -5229,6 +5304,17 @@ digits Malayalam Malaiàlam Symbol Screener Tool Eina de filtre de símbols Symbol Scruncher Compressor de símbols Symbol Scruncher Tool Eina de compressor de símbols + Tool: Eina: + Symbol Set Density Densitat del conjunt de símbols + Symbol Sprayer Options Opcions del ruixador de símbols + Scrunch: Compressió: + Spin: Gir: + Screen: Filtre: + Stain: Tint: + Symbol Sizer Options Opcions de l’escalador de símbols + Proportional Resizing Canvi de mida proporcional + Resizing Affects Density El canvi de mida afecta la densitat + Show Brush Size and Intensity Mostra la mida i la intensitat del pinzell Symbol Set Density: Densitat del conjunt de símbols: Symbol Shifter Desplaçador de símbols Symbol Shifter Tool Eina de desplaçador de símbols @@ -5583,6 +5669,8 @@ digits Malayalam Malaiàlam Unembed… Desincrusta… Ungroup Desagrupa Ungroup Color Group Desagrupa el grup de colors + Color Group Options Opcions del grup de colors + Color Group Options… Opcions del grup de colors… Unicode Unicode Unicode (UTF-16) Unicode (UTF-16) Unicode (UTF-8) Unicode (UTF-8) @@ -6042,6 +6130,9 @@ digits Malayalam Malaiàlam @msg a freeform gradient keeps at least one point un degradat de forma lliure conserva com a mínim un punt @msg a gradient needs at least two stops un degradat necessita com a mínim dues parades @msg a graphic style named `{to}` already exists ja existeix un estil gràfic anomenat `{to}` +@msg a swatch or color group named `{name}` already exists ja existeix una mostra o un grup de colors anomenat `{name}` +@msg missing `group` falta `group` +@msg no colour group `{group}` no hi ha el grup de colors `{group}` @msg a key object sits on that point hi ha un objecte clau en aquest punt @msg a layer couldn't be read no s’ha pogut llegir una capa @msg a linked image can't become a gradient mesh: embed it first una imatge enllaçada no pot esdevenir una malla de degradat: incrusteu-la primer @@ -6462,6 +6553,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg give corners of the path: anchors where its sides meet at an angle doneu les cantonades del traçat: punts d’ancoratge on els seus costats es troben en angle @msg give horizontal or vertical doneu horitzontal o vertical @msg give only one of onto, below and above doneu només un de onto, below i above +@msg give only one of `index`, `indices` and `t` doneu només un de `index`, `indices` i `t` @msg give the path `id` doneu l’`id` del traçat @msg give the path `id` and the width point `index` doneu el `id` del traçat i l’`index` del punt d’amplada @msg Global Edit works on paths, compound paths, symbol instances and groups of them L’edició global funciona amb traçats, traçats compostos, instàncies de símbol i grups d’aquests objectes @@ -6576,6 +6668,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg missing `library` (see brush.libraries) falta `library` (vegeu brush.libraries) @msg missing `library` (see symbol.libraries) falta `library` (vegeu symbol.libraries) @msg missing `name` falta `name` +@msg missing `path` falta `path` @msg missing `tool` falta `tool` @msg missing index falta l’index @msg missing integer `{key}` falta el nombre enter `{key}` @@ -6608,6 +6701,11 @@ liquify-list-end {0}, {1} {0} i {1} @msg no anchor points selected no hi ha cap punt d’ancoratge seleccionat @msg `points` must be two or three [x, y] pairs of numbers `points` han de ser dos o tres parells de nombres [x, y] @msg direct-select two or three anchor points, or give `points` seleccioneu directament dos o tres punts d’ancoratge o indiqueu `points` +@msg the path is straight there, so no circle matches its curvature el traçat és recte en aquest punt, així que cap cercle no coincideix amb la seva curvatura +@msg the path has a cusp there, so it has no single curvature el traçat té una punta en aquest punt, així que no té una curvatura única +@msg the path has a corner there, so it has no single curvature el traçat té un vèrtex en aquest punt, així que no té una curvatura única +@msg a guide has no curvature circle una guia no té cercle de curvatura +@msg the circle that matches the path there would reach past the canvas el cercle que coincideix amb el traçat en aquest punt sortiria del llenç @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 @@ -7182,6 +7280,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg the PSD file's image data uses an unknown compression ({m}) les dades d’imatge del fitxer PSD utilitzen una compressió desconeguda ({m}) @msg the PSD image is too large to read ({_1} × {_2} pixels) la imatge PSD és massa gran per llegir-la ({_1} × {_2} píxels) @msg the Save PDF dialog didn't open el diàleg Desa PDF no s’ha obert +@msg the Save PDF dialog is not open el diàleg Desa PDF no està obert @msg the scale is not a usable number l’escala no és un nombre utilitzable @msg the screen color sampler is already open el mostrejador de color de pantalla ja és obert @msg the search couldn't start: try again in a moment la cerca no s’ha pogut iniciar: torna-ho a provar d’aquí a un moment @@ -7339,6 +7438,49 @@ variable-list-end {0}, {1} {0} i {1} @msg the PSD file's layer groups are nested too deeply els grups de capes del fitxer PSD estan imbricats massa profundament @msg a layer of the PSD file is too large to read una capa del fitxer PSD és massa gran per llegir-la @msg the PSD file's layers take more memory to read than allowed les capes del fitxer PSD necessiten més memòria de la permesa per llegir-les +@msg the file is no longer loaded el fitxer ja no està carregat +@msg the layers can't be read ({e}): the file was placed as its merged image no es poden llegir les capes ({e}): el fitxer s’ha col·locat com a imatge combinada +@msg 1 type layer came in as pixels: the text isn't editable 1 capa de text s’ha importat com a píxels: el text no és editable +@msg {n} type layers came in as pixels: the text isn't editable {n} capes de text s’han importat com a píxels: el text no és editable +@msg 1 adjustment layer was not applied no s’ha aplicat 1 capa d’ajust +@msg {n} adjustment layers were not applied no s’han aplicat {n} capes d’ajust +@msg 1 fill layer was not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels) no s’ha dibuixat 1 capa d’emplenament (un emplenament de degradat o de motiu, un color que no es pot llegir o una forma que no desa píxels) +@msg {n} fill layers were not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels) no s’han dibuixat {n} capes d’emplenament (un emplenament de degradat o de motiu, un color que no es pot llegir o una forma que no desa píxels) +@msg the layer effects of 1 layer weren't drawn no s’han dibuixat els efectes de capa d’1 capa +@msg the layer effects of {n} layers weren't drawn no s’han dibuixat els efectes de capa de {n} capes +@msg the vector masks of 1 layer weren't applied no s’han aplicat les màscares vectorials d’1 capa +@msg the vector masks of {n} layers weren't applied no s’han aplicat les màscares vectorials de {n} capes +@msg the knockout of 1 layer wasn't applied no s’ha aplicat el buidatge d’1 capa +@msg the knockout of {n} layers wasn't applied no s’ha aplicat el buidatge de {n} capes +@msg 1 layer was left out (hidden layers and the layers clipped to them) s’ha omès 1 capa (capes amagades i les capes retallades a elles) +@msg {n} layers were left out (hidden layers and the layers clipped to them) s’han omès {n} capes (capes amagades i les capes retallades a elles) +@msg 1 layer clipped to a fill layer that wasn't drawn was left out s’ha omès 1 capa retallada a una capa d’emplenament que no s’ha dibuixat +@msg {n} layers clipped to fill layers that weren't drawn were left out s’han omès {n} capes retallades a capes d’emplenament que no s’han dibuixat +@msg layers in blend modes VectorCraft doesn't have ({modes}) were merged with the layers below them les capes en modes de fusió que VectorCraft no té ({modes}) s’han combinat amb les capes de sota +@msg 1 layer in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed 1 capa en un mode de fusió que VectorCraft no té s’ha importat com a Normal: la combinació necessita més memòria de la permesa +@msg {n} layers in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed {n} capes en modes de fusió que VectorCraft no té s’han importat com a Normal: la combinació necessita més memòria de la permesa +@msg 1 layer clipped to the layer below came in unclipped: the merge needs more memory than allowed 1 capa retallada a la capa de sota s’ha importat sense retallar: la combinació necessita més memòria de la permesa +@msg {n} layers clipped to the layer below came in unclipped: the merge needs more memory than allowed {n} capes retallades a la capa de sota s’han importat sense retallar: la combinació necessita més memòria de la permesa +@msg hiddenLayers applies to a PSD file placed with layers: true hiddenLayers s’aplica a un fitxer PSD col·locat amb layers: true +@msg importSlices: a linked PSD file is placed as its flat image; give link: false to embed it with its slices importSlices: un fitxer PSD enllaçat es col·loca com a imatge aplanada; indiqueu link: false per incrustar-lo amb els seus talls +@msg layers: a linked PSD file is placed as its flat image; leave link out or give link: false layers: un fitxer PSD enllaçat es col·loca com a imatge aplanada; ometeu link o indiqueu link: false +@msg the slices can't be read ({e}) and were left out no es poden llegir els talls ({e}) i s’han omès +@msg 1 slice lies outside the canvas or has no size and was left out 1 tall és fora del llenç o no té mida i s’ha omès +@msg {n} slices lie outside the canvas or have no size and were left out {n} talls són fora del llenç o no tenen mida i s’han omès +@msg 1 slice would lie outside the canvas and was left out 1 tall quedaria fora del llenç i s’ha omès +@msg {n} slices would lie outside the canvas and were left out {n} talls quedarien fora del llenç i s’han omès +@msg the slices' descriptor holds too many values el descriptor dels talls conté massa valors +@msg the slices' descriptor has a version other than 16 el descriptor dels talls té una versió diferent de 16 +@msg the slices are stored in version {v}, which isn't read els talls estan desats a la versió {v}, que no es llegeix +@msg the file has {count} slices, more than the {MAX_SLICES} read el fitxer té {count} talls, més dels {MAX_SLICES} que es llegeixen +@msg the slices' descriptor has no list of slices el descriptor dels talls no té cap llista de talls +@msg the slices' descriptor lists something other than a slice el descriptor dels talls enumera una cosa que no és un tall +@msg a slice in the slices' descriptor has no bounds un tall del descriptor dels talls no té límits +@msg a slice's bounds in the slices' descriptor aren't numbers els límits d’un tall del descriptor dels talls no són nombres +@msg a text in the slices has more than the {MAX_TEXT} characters read un text dels talls té més dels {MAX_TEXT} caràcters que es llegeixen +@msg the slices' descriptor nests too deep el descriptor dels talls està imbricat massa a fons +@msg the slices' descriptor has a reference of an unknown kind ({_1}) el descriptor dels talls té una referència d’un tipus desconegut ({_1}) +@msg the slices' descriptor has a value of an unknown type ({_1}) el descriptor dels talls té un valor d’un tipus desconegut ({_1}) @msg the layers can't be read ({e}): the file opened as its merged image no es poden llegir les capes ({e}): el fitxer s’ha obert com a imatge combinada @msg zone must be a string zone ha de ser una cadena @msg zone must be tab, center, left, right, top or bottom zone ha de ser tab, center, left, right, top o bottom @@ -8143,6 +8285,8 @@ breakText Glyphs Glifs # Path Precision Tools add-on: Tangent Circle. Tangent Circle… Cercle tangent… Tangent Circle Cercle tangent + Tangent Circle Tool Eina de cercle tangent + No tangent circle here Aquí no hi ha cap cercle tangent Circle: Cercle: @msg `ids` names an object twice `ids` indica un objecte dues vegades @msg select two or three paths or compound paths seleccioneu dos o tres camins o camins compostos @@ -8158,6 +8302,16 @@ breakText Glyphs Glifs @msg `circle` is past the last circle found ({found}) `circle` passa de l’últim cercle trobat ({found}) @msg object {value} is not a path or compound path l’objecte {value} no és un camí ni un camí compost @msg these shapes are too small to measure aquestes formes són massa petites per mesurar-les +# Path Precision Tools add-on: Add Bounding Rectangle and Add Bounding Circle. + Add Bounding Rectangle Afegeix un rectangle delimitador + Add Bounding Circle Afegeix un cercle delimitador + Add Bounding Rectangle… Afegeix un rectangle delimitador… + Add Bounding Circle… Afegeix un cercle delimitador… + One per Object Un per objecte +@msg nothing to enclose no hi ha res per envoltar +@msg `offset` must be 0 or more `offset` ha de ser 0 o més +@msg the shape would have no size la forma no tindria mida +@msg the shape would reach past the edge of the canvas la forma sobrepassaria la vora del llenç # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Eines del document Save a Timestamped Copy Desa una còpia amb data i hora @@ -8643,6 +8797,50 @@ breakText Glyphs Glifs @msg A joint does not close by {gap} pt. Una unió no es tanca per {gap} pt. @msg Two panels pass through each other. Dos panells es travessen l’un a l’altre. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer ha de ser "singleLine", "everyLine", "standardSingleLine" o "standardEveryLine" + Fine Stipple Puntejat fi + Dense Stipple Puntejat dens + Soft Stipple Puntejat suau + Bold Stipple Puntejat gruixut + Paper Cutouts Retalls de paper + Coral Layers Capes de corall + Mint Layers Capes de menta + Midnight Layers Capes de mitjanit + Sunflower Sheet Full de gira-sol + Rose Layers Capes de rosa + Monochrome Stack Pila monocroma +# Tool cards (General › Show Tool Cards): one sentence on what each tool does. + Shows a card with what a toolbar tool does and what its keys do instead of its tip; it needs Show Tool Tips. Mostra una fitxa amb el que fa una eina de la barra i el que fan les seves tecles en lloc del seu consell; cal Mostra els consells d’eines. + Selects whole objects and groups to move, resize or rotate them. Selecciona objectes i grups sencers per moure’ls, canviar-ne la mida o girar-los. + Selects anchor points and path segments to reshape a path. Selecciona punts d’ancoratge i segments de traçat per canviar la forma d’un traçat. + Draws paths point by point, with straight segments and smooth curves. Dibuixa traçats punt a punt, amb segments rectes i corbes suaus. + Draws smooth curves through the points you click. Dibuixa corbes suaus que passen pels punts on feu clic. + Adds text at a point, or in a frame you drag. Afegeix text en un punt o dins d’un marc que arrossegueu. + Draws rectangles and squares. Dibuixa rectangles i quadrats. + Draws rectangles with rounded corners. Dibuixa rectangles amb les cantonades arrodonides. + Draws ellipses and circles. Dibuixa el·lipses i cercles. + Draws polygons with sides of equal length. Dibuixa polígons amb els costats de la mateixa longitud. + Draws stars. Dibuixa estrelles. + Turns objects around a reference point. Gira objectes al voltant d’un punt de referència. + Flips objects across an axis through a reference point. Reflecteix objectes respecte d’un eix que passa per un punt de referència. + Resizes objects from a reference point. Canvia la mida d’objectes des d’un punt de referència. + Slants objects from a reference point. Inclina objectes des d’un punt de referència. + Moves the view of the document. Desplaça la vista del document. + Magnifies or reduces the view. Amplia o redueix la vista. + Copies the color and other attributes of one object to the selection. Copia el color i altres atributs d’un objecte a la selecció. + Sets the direction and length of a gradient. Defineix la direcció i la longitud d’un degradat. + Creates, selects and resizes artboards. Crea, selecciona i canvia la mida de les taules de treball. + Changes the width of a stroke along its length. Canvia l’amplada d’un traç al llarg de la seva longitud. + Bends art by dragging pins placed on it. Doblega la il·lustració arrossegant agulles col·locades a sobre. + Pushes the outlines of paths in the direction you drag. Empeny els contorns dels traçats en la direcció en què arrossegueu. + Twists the outlines of paths into swirls. Retorça els contorns dels traçats en remolins. + Pulls the outlines of paths in toward the brush. Atreu els contorns dels traçats cap al pinzell. + Pushes the outlines of paths out from the brush. Empeny els contorns dels traçats cap enfora des del pinzell. + Adds curved details along the outlines of paths. Afegeix detalls corbs al llarg dels contorns dels traçats. + Adds spiky details along the outlines of paths. Afegeix detalls punxeguts al llarg dels contorns dels traçats. + Adds wrinkles along the outlines of paths. Afegeix arrugues al llarg dels contorns dels traçats. + Moves, copies and resizes objects on the perspective grid. Mou, copia i canvia la mida d’objectes a la quadrícula de perspectiva. + Makes a series of steps between two or more objects. Crea una sèrie de passos entre dos o més objectes. + Places dimension lines that show measured lengths. Col·loca línies de cota que mostren longituds mesurades. Tap Pulsació breu Clear Hold Esborra la pulsació llarga Hold Shortcuts Dreceres de pulsació llarga @@ -8661,3 +8859,7 @@ breakText Glyphs Glifs Round Flow Flux rodó Chisel Flow Flux bisellat @msg text.{key} `{v}`: use "{_1}" or "{_2}" text.{key} `{v}`: utilitzeu "{_1}" o "{_2}" + +# #5804 native-picked raster editor (draft translations; native review welcome). + Edit Original with: Edita l’original amb: +file-filter Applications Aplicacions diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index c610d7c61c..315a6044f8 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -563,6 +563,15 @@ Shading Color Barva stínování Black Overprint Přetisk černou Draw Hidden Faces Kreslit skryté stěny + Map Art… Mapovat kresbu… + Map Art Mapovat kresbu + First Surface První povrch + Previous Surface Předchozí povrch + Next Surface Další povrch + Last Surface Poslední povrch + Scale to Fit Změnit velikost podle povrchu + Shade Artwork Stínovat kresbu + Invisible Geometry Neviditelná geometrie Revolve… Rotační těleso… Inflate… Nafouknutí… Materials… Materiály… @@ -687,6 +696,8 @@ Hide Gradient Annotator Skrýt ovladač přechodu Show Gradient Annotator Zobrazit ovladač přechodu Hide Corner Widget Skrýt ovladač rohů + Hide Shape Widgets Skrýt ovladače tvarů + Show Shape Widgets Zobrazit ovladače tvarů Show Corner Widget Zobrazit ovladač rohů Guides Vodítka Hide Guides Skrýt vodítka @@ -807,6 +818,9 @@ Box Channel Kanál čtverce Color box Barevný čtverec Color Wheel Options Možnosti barevného kola + Show Harmony Zobrazit harmonii + Harmony Rule Pravidlo harmonie + Harmony color Barva harmonie CSS Properties Vlastnosti CSS Document Info Informace o dokumentu Flattener Preview Náhled sloučení @@ -1060,6 +1074,25 @@ Preserve Embedded Profiles Zachovat vložené profily Convert to Working Space Převést do pracovního prostoru Preserve Numbers Zachovat čísla + Profile Mismatches: Nesoulad profilů: + Ask When Opening Ptát se při otevírání + Ask When Pasting Ptát se při vkládání + Missing Profiles: Chybějící profily: + Embedded Profile Mismatch Nesoulad vloženého profilu + Missing Profile Chybějící profil + Paste Profile Mismatch Nesoulad profilu při vkládání + “{name}” is not tagged with a {model} profile. „{name}“ nemá přiřazen profil {model}. + “{name}” is tagged with the {model} profile “{profile}”, which is not the {model} working space “{working}”. „{name}“ má profil {model} „{profile}“, který není pracovním prostorem {model} „{working}“. + Use the embedded profile Použít vložený profil + Convert the colors to the working space Převést barvy do pracovního prostoru + Discard the embedded profile Zahodit vložený profil + Leave as is Ponechat beze změny + Assign the working space Přiřadit pracovní prostor + Assign profile: Přiřadit profil: + Preserve the color numbers Zachovat hodnoty barev + Convert to keep the colors' appearance Převést a zachovat vzhled barev +@msg `{path}` goes with `{key}`: "assign" only `{path}` patří jen k `{key}`: "assign" + The pasted colors come from a document whose {model} profile is “{from}”; this document's is “{to}”. Vložené barvy pocházejí z dokumentu s profilem {model} „{from}“; tento dokument má „{to}“. CMYK CMYK Texture Textura Craquelure… Krakelování… @@ -1147,6 +1180,15 @@ lighting Light Světlo Document Raster Effects Settings Dialog Dialogové okno Nastavení rastrových efektů dokumentu Drop Shadow Vržený stín DXF Options Dialog Dialogové okno Možnosti DXF + HP-GL Options Možnosti HP-GL + HP-GL Options Dialog Dialogové okno Možnosti HP-GL + Curve Tolerance: Tolerance křivek: + Origin: Počátek: + Pens: Pera: + One Pen per Color Jedno pero pro každou barvu + Pen Table Tabulka per + Draw the Nearest Path Next Jako další kreslit nejbližší cestu + Draw Inner Paths First Nejdřív kreslit vnitřní cesty Edit Toolbar Upravit panel nástrojů Edit Views Upravit zobrazení Effect… Efekt… @@ -1727,6 +1769,7 @@ digits Malayalam Malajálamské Roman Baseline Latinková účaří Select a text object to edit its character attributes. Vyberte textový objekt, abyste mohli upravit atributy jeho znaků. Show Options Zobrazit možnosti + Show on Shape Creation Zobrazit při vytvoření tvaru Show Recent Colors Zobrazit nedávné barvy Toggle RGB Percent Přepnout RGB v procentech Color Panel Options Možnosti panelu Barva @@ -2077,6 +2120,8 @@ digits Malayalam Malajálamské Snap Curves To Lines Přichytit křivky k úsečkám Tracing Result with Outlines Výsledek vektorizace s obrysy Source Image Zdrojový obraz + Split View Rozdělené zobrazení + Divider Dělicí čára Threshold Práh Trace Vektorizovat Trace the image with the Default preset Vektorizovat obraz s přednastavením Výchozí @@ -2224,6 +2269,15 @@ digits Malayalam Malajálamské YakumonoZenkaku YakumonoZenkaku Kinsoku Set Sada Kinsoku Kinsoku Shori Type Typ Kinsoku Shori + Kinsoku Shori Settings… Nastavení Kinsoku Shori… + Kinsoku Shori Settings Nastavení Kinsoku Shori + Kinsoku Sets Sady Kinsoku + Kinsoku Set Base Základ sady Kinsoku + Based on: Založeno na: + Cannot Start Line Nemůže začínat řádek + Cannot End Line Nemůže končit řádek + Hanging Punctuation Visící interpunkce + Inseparable Characters Neoddělitelné znaky Push In First Nejprve vtáhnout Push Out First Nejprve vysunout Push Out Only Pouze vysunout @@ -2628,6 +2682,12 @@ digits Malayalam Malajálamské Units: Jednotky: Use Typographer's Quotes Používat typografické uvozovky Center Artwork Vystředit kresbu + PSD Import Options Možnosti importu PSD + Place PSD Umístit PSD + Convert Layers to Objects Převést vrstvy na objekty + Import Hidden Layers Importovat skryté vrstvy + Flatten Layers to a Single Image Sloučit vrstvy do jednoho obrazu + Import Slices Importovat řezy DXF Import Options Možnosti importu DXF Layout: Rozvržení: Merge Layers Sloučit vrstvy @@ -2783,6 +2843,7 @@ digits Malayalam Malajálamské Save As Preset… Uložit jako předvolbu… Save Changes Uložit změny Save Preset… Uložit přednastavení… + Save Summary… Uložit souhrn… Vectors Vektory A saved copy of the selected preset Uložená kopie vybraného přednastavení Built-in presets don't change: New makes a copy you can edit. Vestavěná přednastavení se nemění: tlačítko Nový vytvoří kopii, kterou lze upravit. @@ -3027,6 +3088,8 @@ digits Malayalam Malajálamské Overprint and Transparency Flattener Options Možnosti přetisku a sloučení průhlednosti Custom… Vlastní nastavení… Custom Transparency Flattener Options Vlastní možnosti sloučení průhlednosti + The PDF preset keeps the flattener preset but not the Custom… settings. Přednastavení PDF zachová přednastavení sloučení, ale ne nastavení z Vlastní nastavení…. + PDF 1.3 files clip rasterized areas to their regions, and Overprint sets whether overprints are kept. Soubory PDF 1.3 ořezávají rastrované oblasti podle jejich tvaru a Přetisk určuje, zda se přetisky zachovají. EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS nemá průhlednost alfa a Přetisky určují, zda se přetisky zachovají. Place the pages with the placement again Znovu rozmístit stránky podle umístění Placement: Umístění: @@ -3122,6 +3185,9 @@ digits Malayalam Malajálamské Recolor this row Přebarvit tento řádek Reset the rows to the artwork's colors Obnovit řádky na barvy kresby Color Theme Picker Výběr barevného motivu + Undo Changes Vrátit změny + Redo Changes Zopakovat změny +@msg Recolor Artwork is not open Přebarvit kresbu není otevřené Click or drag across the art to pick its colors; Shift adds more Klepnutím nebo tažením přes kresbu převezmete její barvy; Shift přidá další Prominent Colors Převládající barvy Save All Colors Uložit všechny barvy @@ -3409,6 +3475,17 @@ antiAlias Sharp Ostré Swatch Name: Název položky vzorníku: Diameter: Průměr: Symbolism Tools Options Možnosti nástrojů symbolů + Tool: Nástroj: + Symbol Set Density Hustota sady symbolů + Symbol Sprayer Options Volby rozprašovače symbolů + Scrunch: Zhuštění: + Spin: Otáčení: + Screen: Průhlednost: + Stain: Obarvení: + Symbol Sizer Options Volby velikosti symbolů + Proportional Resizing Proporcionální změna velikosti + Resizing Affects Density Změna velikosti ovlivňuje hustotu + Show Brush Size and Intensity Zobrazit velikost a intenzitu štětce Symbol Set Density: Hustota sady symbolů: Intensity: Intenzita: Place PDF Umístit PDF @@ -3507,6 +3584,7 @@ antiAlias Sharp Ostré # Command labels and other interface strings Art Obrazový Bearing Azimut + Stylus Wheel Kolečko pera Bristle Štětinový Calligraphic Kaligrafický Dots Body @@ -3652,6 +3730,9 @@ theme Appearance Motiv embedding for preview and print vkládání pro náhled a tisk embedding allowed vkládání povoleno {file}; {embedding} {file}; {embedding} + unknown type neznámý typ + {type}; {uses} {type}; {uses} +@plural {n} use|{n} uses {n} použití|{n} použití|{n} použití substituted: shown in {family} {style} ({detail}) nahrazeno: zobrazeno písmem {family} {style} ({detail}) missing: shown in {family} {style} chybí: zobrazeno písmem {family} {style} missing chybí @@ -4245,6 +4326,7 @@ theme Appearance Motiv Show Pixel Grid (Above 600% Zoom) Zobrazit mřížku obrazových bodů (nad 600 %) Show Slice Numbers Zobrazit čísla řezů Show The Home Screen When No Documents Are Open Zobrazit domovskou obrazovku, když nejsou otevřeny dokumenty + Show Tool Cards Zobrazovat karty nástrojů Show Tool Tips Zobrazovat popisky nástrojů Size/Leading Velikost/proklad Snapping Tolerance Tolerance přichytávání @@ -4370,6 +4452,8 @@ theme Appearance Motiv Spot Colors (0) Přímé barvy (0) Swatch Options Možnosti položky vzorníku Ungroup Color Group Zrušit skupinu barev + Color Group Options Možnosti skupiny barev + Color Group Options… Možnosti skupiny barev… Copy to User Defined Kopírovat do uživatelských Swatch Library Knihovna vzorníku Clear All Tabs Vymazat všechny tabulátory @@ -4679,6 +4763,7 @@ font-technology Variable Variabilní A live rectangle's properties show one Corner Radius field for all four corners; off, each corner has its own field. Vlastnosti živého obdélníku zobrazí jedno pole Poloměr rohu pro všechny čtyři rohy; když je vypnuto, má každý roh vlastní pole. What edits in the Transform panel transform: the object, its pattern tiles or both; Default follows Transform Pattern Tiles. Co úpravy v panelu Transformace transformují: objekt, dlaždice jeho vzorku nebo obojí; Výchozí se řídí volbou Transformovat dlaždice vzorku. With one symbol instance selected, the Transform panel uses the symbol's registration point as its reference point. Když je vybraná jedna instance symbolu, panel Transformace použije registrační bod symbolu jako referenční bod. + Drawing a rectangle, ellipse, polygon, star or line opens the Transform panel if it is closed. Nakreslení obdélníku, elipsy, mnohoúhelníku, hvězdy nebo čáry otevře panel Transformace, pokud je zavřený. Darkens the canvas outside the artboards while the Artboard tool is active. Ztmaví plátno mimo pracovní plochy, dokud je aktivní nástroj Pracovní plocha. With Fade Region Outside Artboard on, the area outside the artboards stays dark while you drag with the Artboard tool. Když je zapnuto Ztmavit oblast mimo pracovní plochu, zůstane oblast mimo pracovní plochy tmavá i při tažení nástrojem Pracovní plocha. How near, in pixels, the pointer must be to an object, anchor or handle for a click to select it. Jak blízko v obrazových bodech musí být ukazatel k objektu, kotevnímu bodu nebo úchytu, aby jej kliknutí vybralo. @@ -4773,6 +4858,9 @@ font-technology Variable Variabilní Channel Kanál Circle Kruh Circle Tool Nástroj Kruh + Curvature Circle Tool Nástroj Kružnice křivosti + Cusp Hrot + Straight segment Přímý segment Circle too large Kruh je příliš velký Clip to Art Oříznout podle kresby Colorize Obarvit @@ -5369,6 +5457,7 @@ liquify-list-end {0}, {1} {0} a {1} @msg a freeform gradient keeps at least one point volný přechod si ponechává alespoň jeden bod @msg a gradient needs at least two stops přechod potřebuje alespoň dvě zarážky @msg a graphic style named `{to}` already exists grafický styl s názvem `{to}` už existuje +@msg a swatch or color group named `{name}` already exists položka vzorníku nebo skupina barev s názvem `{name}` už existuje @msg a key object sits on that point na tomto bodě leží klíčový objekt @msg a page is missing chybí stránka @msg a page out of range stránka mimo rozsah @@ -5510,6 +5599,11 @@ liquify-list-end {0}, {1} {0} a {1} @msg no anchor points selected nejsou vybrány žádné kotevní body @msg `points` must be two or three [x, y] pairs of numbers `points` musí být dvě nebo tři dvojice čísel [x, y] @msg direct-select two or three anchor points, or give `points` vyberte přímým výběrem dva nebo tři kotevní body, nebo zadejte `points` +@msg the path is straight there, so no circle matches its curvature cesta je v tomto místě rovná, takže jejímu zakřivení neodpovídá žádná kružnice +@msg the path has a cusp there, so it has no single curvature cesta má v tomto místě hrot, takže nemá jediné zakřivení +@msg the path has a corner there, so it has no single curvature cesta má v tomto místě roh, takže nemá jediné zakřivení +@msg a guide has no curvature circle vodítko nemá kružnici křivosti +@msg the circle that matches the path there would reach past the canvas kružnice odpovídající cestě v tomto místě by přesáhla plátno @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 @@ -5765,6 +5859,7 @@ liquify-list-end {0}, {1} {0} a {1} @msg the PDF is password-protected: give its password PDF je chráněno heslem: zadejte heslo @msg the PDF password is wrong heslo k PDF je chybné @msg the Save PDF dialog didn't open dialogové okno Uložit PDF se neotevřelo +@msg the Save PDF dialog is not open dialogové okno Uložit PDF není otevřené @msg the WMF header is damaged hlavička WMF je poškozená @msg the art could not be sampled z kresby nelze nabrat vzorek @msg the art has no bounds kresba nemá hranice @@ -5988,6 +6083,7 @@ variable-list-end {0}, {1} {0} a {1} @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 +@msg give only one of `index`, `indices` and `t` zadejte jen jedno z `index`, `indices` a `t` @msg column must be true or a number from 1 column musí být true nebo číslo od 1 @msg x and y must both be numbers x i y musí být čísla @msg "{0}" is not a colour: write it as #rrggbb „{0}“ není barva: zapište ji jako #rrggbb @@ -6105,6 +6201,49 @@ variable-list-end {0}, {1} {0} a {1} @msg the PSD file's layer groups are nested too deeply skupiny vrstev souboru PSD jsou vnořené příliš hluboko @msg a layer of the PSD file is too large to read vrstva souboru PSD je příliš velká na přečtení @msg the PSD file's layers take more memory to read than allowed vrstvy souboru PSD potřebují ke čtení víc paměti, než je povoleno +@msg the file is no longer loaded soubor už není načtený +@msg the layers can't be read ({e}): the file was placed as its merged image vrstvy nelze přečíst ({e}): soubor byl umístěn jako sloučený obraz +@msg 1 type layer came in as pixels: the text isn't editable 1 textová vrstva byla načtena jako pixely: text nelze upravovat +@msg {n} type layers came in as pixels: the text isn't editable textové vrstvy načtené jako pixely: {n}; text nelze upravovat +@msg 1 adjustment layer was not applied 1 vrstva úprav nebyla použita +@msg {n} adjustment layers were not applied nepoužité vrstvy úprav: {n} +@msg 1 fill layer was not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels) 1 vrstva výplně nebyla vykreslena (přechodová nebo vzorková výplň, barva, kterou nelze přečíst, nebo tvar bez uložených pixelů) +@msg {n} fill layers were not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels) nevykreslené vrstvy výplně: {n} (přechodová nebo vzorková výplň, barva, kterou nelze přečíst, nebo tvar bez uložených pixelů) +@msg the layer effects of 1 layer weren't drawn efekty vrstvy u 1 vrstvy nebyly vykresleny +@msg the layer effects of {n} layers weren't drawn efekty vrstev nebyly vykresleny; počet vrstev: {n} +@msg the vector masks of 1 layer weren't applied vektorové masky 1 vrstvy nebyly použity +@msg the vector masks of {n} layers weren't applied vektorové masky vrstev nebyly použity; počet vrstev: {n} +@msg the knockout of 1 layer wasn't applied vykrojení 1 vrstvy nebylo použito +@msg the knockout of {n} layers wasn't applied vykrojení vrstev nebylo použito; počet vrstev: {n} +@msg 1 layer was left out (hidden layers and the layers clipped to them) 1 vrstva byla vynechána (skryté vrstvy a vrstvy k nim oříznuté) +@msg {n} layers were left out (hidden layers and the layers clipped to them) vynechané vrstvy: {n} (skryté vrstvy a vrstvy k nim oříznuté) +@msg 1 layer clipped to a fill layer that wasn't drawn was left out 1 vrstva oříznutá k nevykreslené vrstvě výplně byla vynechána +@msg {n} layers clipped to fill layers that weren't drawn were left out vynechané vrstvy oříznuté k nevykresleným vrstvám výplně: {n} +@msg layers in blend modes VectorCraft doesn't have ({modes}) were merged with the layers below them vrstvy v režimech prolnutí, které VectorCraft nemá ({modes}), byly sloučeny s vrstvami pod nimi +@msg 1 layer in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed 1 vrstva v režimu prolnutí, který VectorCraft nemá, byla načtena jako Normální: sloučení potřebuje víc paměti, než je povoleno +@msg {n} layers in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed vrstvy v režimech prolnutí, které VectorCraft nemá, načtené jako Normální: {n}; sloučení potřebuje víc paměti, než je povoleno +@msg 1 layer clipped to the layer below came in unclipped: the merge needs more memory than allowed 1 vrstva oříznutá k vrstvě pod ní byla načtena bez oříznutí: sloučení potřebuje víc paměti, než je povoleno +@msg {n} layers clipped to the layer below came in unclipped: the merge needs more memory than allowed vrstvy oříznuté k vrstvě pod nimi načtené bez oříznutí: {n}; sloučení potřebuje víc paměti, než je povoleno +@msg hiddenLayers applies to a PSD file placed with layers: true hiddenLayers platí pro soubor PSD umístěný s layers: true +@msg importSlices: a linked PSD file is placed as its flat image; give link: false to embed it with its slices importSlices: propojený soubor PSD se umístí jako plochý obraz; zadejte link: false, aby se vložil i s řezy +@msg layers: a linked PSD file is placed as its flat image; leave link out or give link: false layers: propojený soubor PSD se umístí jako plochý obraz; vynechte link nebo zadejte link: false +@msg the slices can't be read ({e}) and were left out řezy nelze přečíst ({e}) a byly vynechány +@msg 1 slice lies outside the canvas or has no size and was left out 1 řez leží mimo plátno nebo nemá velikost a byl vynechán +@msg {n} slices lie outside the canvas or have no size and were left out vynechané řezy, které leží mimo plátno nebo nemají velikost: {n} +@msg 1 slice would lie outside the canvas and was left out 1 řez by ležel mimo plátno a byl vynechán +@msg {n} slices would lie outside the canvas and were left out vynechané řezy, které by ležely mimo plátno: {n} +@msg the slices' descriptor holds too many values deskriptor řezů obsahuje příliš mnoho hodnot +@msg the slices' descriptor has a version other than 16 deskriptor řezů má jinou verzi než 16 +@msg the slices are stored in version {v}, which isn't read řezy jsou uložené ve verzi {v}, která se nečte +@msg the file has {count} slices, more than the {MAX_SLICES} read počet řezů v souboru je {count}, víc než čtených {MAX_SLICES} +@msg the slices' descriptor has no list of slices deskriptor řezů nemá seznam řezů +@msg the slices' descriptor lists something other than a slice deskriptor řezů uvádí něco jiného než řez +@msg a slice in the slices' descriptor has no bounds řez v deskriptoru řezů nemá hranice +@msg a slice's bounds in the slices' descriptor aren't numbers hranice řezu v deskriptoru řezů nejsou čísla +@msg a text in the slices has more than the {MAX_TEXT} characters read text v řezech má víc než čtených {MAX_TEXT} znaků +@msg the slices' descriptor nests too deep deskriptor řezů je vnořený příliš hluboko +@msg the slices' descriptor has a reference of an unknown kind ({_1}) deskriptor řezů má odkaz neznámého druhu ({_1}) +@msg the slices' descriptor has a value of an unknown type ({_1}) deskriptor řezů má hodnotu neznámého typu ({_1}) @msg the layers can't be read ({e}): the file opened as its merged image vrstvy nelze přečíst ({e}): soubor se otevřel jako sloučený obraz @msg {depth}-bit PSD files in this colour mode can't be read {depth}bitové soubory PSD v tomto barevném režimu nelze přečíst @msg the PSD file is cut short soubor PSD je useknutý @@ -8128,6 +8267,8 @@ breakText Glyphs Glyfy # Path Precision Tools add-on: Tangent Circle. Tangent Circle… Tečná kružnice… Tangent Circle Tečná kružnice + Tangent Circle Tool Nástroj Tečná kružnice + No tangent circle here Zde není žádná tečná kružnice Circle: Kružnice: @msg `ids` names an object twice `ids` uvádí některý objekt dvakrát @msg select two or three paths or compound paths vyberte dvě nebo tři cesty nebo složené cesty @@ -8143,6 +8284,16 @@ breakText Glyphs Glyfy @msg `circle` is past the last circle found ({found}) `circle` je za poslední nalezenou kružnicí ({found}) @msg object {value} is not a path or compound path objekt {value} není cesta ani složená cesta @msg these shapes are too small to measure tyto tvary jsou příliš malé na měření +# Path Precision Tools add-on: Add Bounding Rectangle and Add Bounding Circle. + Add Bounding Rectangle Přidat ohraničující obdélník + Add Bounding Circle Přidat ohraničující kružnici + Add Bounding Rectangle… Přidat ohraničující obdélník… + Add Bounding Circle… Přidat ohraničující kružnici… + One per Object Jeden pro každý objekt +@msg nothing to enclose není co ohraničit +@msg `offset` must be 0 or more `offset` musí být 0 nebo více +@msg the shape would have no size tvar by neměl žádnou velikost +@msg the shape would reach past the edge of the canvas tvar by přesáhl okraj plátna # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Nástroje dokumentu Save a Timestamped Copy Uložit kopii s datem a časem @@ -10408,6 +10559,39 @@ breakText Glyphs Glyfy No objects are selected. Nejsou vybrány žádné objekty. Open a document to mark its fold lines. Otevřete dokument, abyste označili jeho linie skladu. Remove Fold Line Role Odstranit typ linie +# Tool cards (General › Show Tool Cards): one sentence on what each tool does. + Shows a card with what a toolbar tool does and what its keys do instead of its tip; it needs Show Tool Tips. Místo popisku zobrazí kartu s tím, co dělá nástroj z panelu a co dělají jeho klávesy; vyžaduje Zobrazovat popisky nástrojů. + Selects whole objects and groups to move, resize or rotate them. Vybírá celé objekty a skupiny, abyste je mohli přesunout, změnit jejich velikost nebo je otočit. + Selects anchor points and path segments to reshape a path. Vybírá kotevní body a segmenty cesty, abyste mohli změnit tvar cesty. + Draws paths point by point, with straight segments and smooth curves. Kreslí cesty bod po bodu, s rovnými segmenty a hladkými křivkami. + Draws smooth curves through the points you click. Kreslí hladké křivky procházející body, na které kliknete. + Adds text at a point, or in a frame you drag. Přidá text v bodě nebo v rámečku, který natáhnete. + Draws rectangles and squares. Kreslí obdélníky a čtverce. + Draws rectangles with rounded corners. Kreslí obdélníky se zaoblenými rohy. + Draws ellipses and circles. Kreslí elipsy a kruhy. + Draws polygons with sides of equal length. Kreslí mnohoúhelníky se stejně dlouhými stranami. + Draws stars. Kreslí hvězdy. + Turns objects around a reference point. Otáčí objekty kolem referenčního bodu. + Flips objects across an axis through a reference point. Zrcadlí objekty podle osy procházející referenčním bodem. + Resizes objects from a reference point. Mění velikost objektů od referenčního bodu. + Slants objects from a reference point. Zkosí objekty od referenčního bodu. + Moves the view of the document. Posouvá zobrazení dokumentu. + Magnifies or reduces the view. Zvětšuje nebo zmenšuje zobrazení. + Copies the color and other attributes of one object to the selection. Zkopíruje barvu a další atributy jednoho objektu do výběru. + Sets the direction and length of a gradient. Nastaví směr a délku přechodu. + Creates, selects and resizes artboards. Vytváří, vybírá a mění velikost pracovních ploch. + Changes the width of a stroke along its length. Mění šířku tahu podél jeho délky. + Bends art by dragging pins placed on it. Ohýbá kresbu tažením špendlíků, které na ni umístíte. + Pushes the outlines of paths in the direction you drag. Posouvá obrysy cest ve směru tažení. + Twists the outlines of paths into swirls. Zkroutí obrysy cest do vírů. + Pulls the outlines of paths in toward the brush. Stahuje obrysy cest směrem ke štětci. + Pushes the outlines of paths out from the brush. Vytlačuje obrysy cest směrem od štětce. + Adds curved details along the outlines of paths. Přidává zaoblené detaily podél obrysů cest. + Adds spiky details along the outlines of paths. Přidává ostré detaily podél obrysů cest. + Adds wrinkles along the outlines of paths. Přidává vrásky podél obrysů cest. + Moves, copies and resizes objects on the perspective grid. Přesouvá, kopíruje a mění velikost objektů v perspektivní mřížce. + Makes a series of steps between two or more objects. Vytvoří řadu kroků mezi dvěma nebo více objekty. + Places dimension lines that show measured lengths. Umísťuje kótovací čáry, které ukazují naměřené délky. Tap Krátký stisk Clear Hold Vymazat podržení Hold Shortcuts Zkratky podržením @@ -10438,7 +10622,18 @@ breakText Glyphs Glyfy @msg A panel is not joined to the rest by a crease. Panel není se zbytkem spojen žádnou linií bigu. @msg A fold line is on a non-printing layer. Linie skladu je na netisknutelné vrstvě. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panely: {panels}, panty: {hinges}, chyby: {errors}, upozornění: {warnings} + Paper Cutouts Papírové výřezy + Coral Layers Korálové vrstvy + Mint Layers Mátové vrstvy + Midnight Layers Půlnoční vrstvy + Sunflower Sheet Slunečnicový list + Rose Layers Růžové vrstvy + Monochrome Stack Jednobarevná sada Dashed Arrow Přerušovaná šipka + Fine Stipple Jemné tečkování + Dense Stipple Husté tečkování + Soft Stipple Měkké tečkování + Bold Stipple Výrazné tečkování Pressure Sensitive Citlivé na tlak Flex Ribbon Pružná stuha Pulse Stroke Pulzující tah @@ -10454,3 +10649,7 @@ breakText Glyphs Glyfy @msg Other blanks not shown: {count} Další přířezy nejsou zobrazeny: {count} @msg A joint does not close by {gap} pt. Spoj se nezavírá o {gap} pt. @msg Two panels pass through each other. Dva panely procházejí jeden druhým. + +# #5804 native-picked raster editor (draft translations; native review welcome). + Edit Original with: Upravit originál v: +file-filter Applications Aplikace diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 2b01d857a3..9693d1d3e2 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -3252,6 +3252,17 @@ liquify-list-end {0}, {1} {0} og {1} Shading Color Skyggefarve Black Overprint Sort overprint Draw Hidden Faces Tegn skjulte flader + Map Art… Kortlæg grafik… + Map Art Kortlæg grafik + First Surface Første overflade + Previous Surface Forrige overflade + Next Surface Næste overflade + Last Surface Sidste overflade + Horizontal Scale Vandret skalering + Vertical Scale Lodret skalering + Scale to Fit Skalér til at passe + Shade Artwork Skyg grafik + Invisible Geometry Usynlig geometri Revolve… Omdrej… Inflate… Pust op… Materials… Materialer… @@ -3363,6 +3374,8 @@ liquify-list-end {0}, {1} {0} og {1} Hide Gradient Annotator Skjul gradientanmærkning Show Gradient Annotator Vis gradientanmærkning Hide Corner Widget Skjul hjørnehåndtag + Hide Shape Widgets Skjul formhåndtag + Show Shape Widgets Vis formhåndtag Show Corner Widget Vis hjørnehåndtag Guides Hjælpelinjer Hide Guides Skjul hjælpelinjer @@ -3482,6 +3495,9 @@ liquify-list-end {0}, {1} {0} og {1} Box Channel Kvadratets kanal Color box Farvekvadrat Color Wheel Options Indstillinger for farvehjul + Show Harmony Vis harmoni + Harmony Rule Harmoniregel + Harmony color Harmonifarve CSS Properties CSS-egenskaber Document Info Dokumentoplysninger Flattener Preview Udjævningsforhåndsvisning @@ -3713,6 +3729,25 @@ liquify-list-end {0}, {1} {0} og {1} Preserve Embedded Profiles Bevar indlejrede profiler Convert to Working Space Konverter til arbejdsfarverum Preserve Numbers Bevar tal + Profile Mismatches: Profiluoverensstemmelser: + Ask When Opening Spørg ved åbning + Ask When Pasting Spørg ved indsætning + Missing Profiles: Manglende profiler: + Embedded Profile Mismatch Uoverensstemmelse med indlejret profil + Missing Profile Manglende profil + Paste Profile Mismatch Profiluoverensstemmelse ved indsætning + “{name}” is not tagged with a {model} profile. »{name}« har ingen {model}-profil. + “{name}” is tagged with the {model} profile “{profile}”, which is not the {model} working space “{working}”. »{name}« har {model}-profilen »{profile}«, som ikke er {model}-arbejdsfarverummet »{working}«. + Use the embedded profile Brug den indlejrede profil + Convert the colors to the working space Konverter farverne til arbejdsfarverummet + Discard the embedded profile Kassér den indlejrede profil + Leave as is Lad være som den er + Assign the working space Tildel arbejdsfarverummet + Assign profile: Tildel profil: + Preserve the color numbers Bevar farveværdierne + Convert to keep the colors' appearance Konverter for at bevare farvernes udseende +@msg `{path}` goes with `{key}`: "assign" only `{path}` hører kun til `{key}`: "assign" + The pasted colors come from a document whose {model} profile is “{from}”; this document's is “{to}”. De indsatte farver kommer fra et dokument med {model}-profilen »{from}«; dette dokuments er »{to}«. CMYK CMYK Texture Tekstur Craquelure… Krakelering… @@ -3794,6 +3829,15 @@ lighting Light Lys Document Raster Effects Settings Dialog Dialogboks til indstillinger for rasteriseringseffekter i dokumentet Drop Shadow Slagskygge DXF Options Dialog Dialogboks til DXF-indstillinger + HP-GL Options HP-GL-indstillinger + HP-GL Options Dialog Dialogboks til HP-GL-indstillinger + Curve Tolerance: Kurvetolerance: + Origin: Origo: + Pens: Penne: + One Pen per Color Én pen pr. farve + Pen Table Pennetabel + Draw the Nearest Path Next Tegn den nærmeste sti som den næste + Draw Inner Paths First Tegn indre stier først Edit Toolbar Redigér værktøjslinjen Edit Views Redigér visninger Effect… Effekt… @@ -4356,6 +4400,7 @@ digits Malayalam Malayalam Roman Baseline Romersk grundlinje Select a text object to edit its character attributes. Markér et tekstobjekt for at redigere dets tegnattributter. Show Options Vis indstillinger + Show on Shape Creation Vis ved oprettelse af form Show Recent Colors Vis seneste farver Toggle RGB Percent Skift RGB i procent Small Caps Kapitæler @@ -4622,6 +4667,8 @@ digits Malayalam Malayalam Snap Curves To Lines Fastgør kurver til linjer Tracing Result with Outlines Vektoriseringsresultat med konturer Source Image Kildebillede + Split View Delt visning + Divider Skillelinje Threshold Tærskel Trace Vektorisér Trace the image with the Default preset Vektorisér billedet med standardforudindstillingen @@ -4746,6 +4793,15 @@ digits Malayalam Malayalam YakumonoZenkaku YakumonoZenkaku Kinsoku Set Kinsoku-sæt Kinsoku Shori Type Kinsoku Shori-type + Kinsoku Shori Settings… Kinsoku Shori-indstillinger… + Kinsoku Shori Settings Kinsoku Shori-indstillinger + Kinsoku Sets Kinsoku-sættene + Kinsoku Set Base Grundlag for Kinsoku-sæt + Based on: Baseret på: + Cannot Start Line Kan ikke starte linje + Cannot End Line Kan ikke afslutte linje + Hanging Punctuation Hængende tegnsætning + Inseparable Characters Uadskillelige tegn Push In First Skub ind først Push Out First Skub ud først Push Out Only Kun skub ud @@ -5145,6 +5201,12 @@ digits Malayalam Malayalam Units: Enheder: Use Typographer's Quotes Brug typografiske anførselstegn Center Artwork Centrér grafik + PSD Import Options PSD-importindstillinger + Place PSD Placér PSD + Convert Layers to Objects Konvertér lag til objekter + Import Hidden Layers Importér skjulte lag + Flatten Layers to a Single Image Fladgør lag til ét billede + Import Slices Importér udsnit DXF Import Options DXF-importindstillinger Layout: Layout: Merge Layers Flet lag @@ -5296,6 +5358,7 @@ digits Malayalam Malayalam Save As Preset… Gem som forudindstilling… Save Changes Gem ændringer Save Preset… Gem forudindstilling… + Save Summary… Gem oversigt… Vectors Vektorer A saved copy of the selected preset En gemt kopi af den valgte forudindstilling Built-in presets don't change: New makes a copy you can edit. Indbyggede forudindstillinger ændres ikke: Ny opretter en kopi, du kan redigere. @@ -5529,6 +5592,8 @@ digits Malayalam Malayalam Overprint and Transparency Flattener Options Indstillinger for overtryk og udfladning af gennemsigtighed Custom… Brugerdefineret… Custom Transparency Flattener Options Brugerdefinerede indstillinger for udfladning af gennemsigtighed + The PDF preset keeps the flattener preset but not the Custom… settings. PDF-forudindstillingen gemmer fladgøringsforudindstillingen, men ikke indstillingerne fra Brugerdefineret…. + PDF 1.3 files clip rasterized areas to their regions, and Overprint sets whether overprints are kept. PDF 1.3-filer klipper rasteriserede områder til deres regioner, og Overprint bestemmer, om overtryk bevares. EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS har ingen alfa-gennemsigtighed, og Overtryk bestemmer, om overtryk bevares. Place the pages with the placement again Placér siderne igen med placeringen Placement: Placering: @@ -5624,6 +5689,9 @@ digits Malayalam Malayalam Recolor this row Omfarv denne række Reset the rows to the artwork's colors Nulstil rækkerne til grafikkens farver Color Theme Picker Farvetemavælger + Undo Changes Fortryd ændringer + Redo Changes Gentag ændringer +@msg Recolor Artwork is not open Omfarv grafik er ikke åben Click or drag across the art to pick its colors; Shift adds more Klik eller træk hen over grafikken for at hente dens farver; Skift tilføjer flere Prominent Colors Fremtrædende farver Save All Colors Gem alle farver @@ -5911,6 +5979,17 @@ antiAlias Sharp Skarp Swatch Name: Farveprøvenavn: Diameter: Diameter: Symbolism Tools Options Indstillinger for symbolværktøjer + Tool: Værktøj: + Symbol Set Density Tæthed for symbolsæt + Symbol Sprayer Options Indstillinger for symbolsprøjter + Scrunch: Samling: + Spin: Rotering: + Screen: Gennemsigtighed: + Stain: Farvning: + Symbol Sizer Options Indstillinger for symbolstørrelse + Proportional Resizing Proportional størrelsesændring + Resizing Affects Density Størrelsesændring påvirker tætheden + Show Brush Size and Intensity Vis penselstørrelse og intensitet Symbol Set Density: Tæthed for symbolsæt: Intensity: Intensitet: Place PDF Placér PDF @@ -5971,6 +6050,7 @@ antiAlias Sharp Skarp Width Point Edit Redigér breddepunkt Art Kunst Bearing Retning + Stylus Wheel Pennehjul Bristle Borst Calligraphic Kalligrafisk Dots Prikker @@ -6105,6 +6185,9 @@ theme Appearance Udseende embedding for preview and print indlejring til visning og udskrivning embedding allowed indlejring tilladt {file}; {embedding} {file}; {embedding} + unknown type ukendt type + {type}; {uses} {type}; {uses} +@plural {n} use|{n} uses {n} anvendelse|{n} anvendelser substituted: shown in {family} {style} ({detail}) erstattet: vist med {family} {style} ({detail}) missing: shown in {family} {style} mangler: vist med {family} {style} missing mangler @@ -6677,6 +6760,7 @@ theme Appearance Udseende Show Pixel Grid (Above 600% Zoom) Vis pixelgitter (over 600 % zoom) Show Slice Numbers Vis udsnitsnumre Show The Home Screen When No Documents Are Open Vis startskærmen, når ingen dokumenter er åbne + Show Tool Cards Vis værktøjskort Show Tool Tips Vis værktøjstips Size/Leading Størrelse/linjeafstand Snapping Tolerance Snap-tolerance @@ -6802,6 +6886,8 @@ theme Appearance Udseende Spot Colors (0) Spotfarver (0) Swatch Options Indstillinger for farveprøve Ungroup Color Group Afgruppér farvegruppe + Color Group Options Indstillinger for farvegruppe + Color Group Options… Indstillinger for farvegruppe… Copy to User Defined Kopiér til brugerdefinerede Swatch Library Farveprøvebibliotek Clear All Tabs Ryd alle tabulatorer @@ -7100,6 +7186,7 @@ font-technology Variable Variable A live rectangle's properties show one Corner Radius field for all four corners; off, each corner has its own field. Egenskaberne for et live-rektangel viser ét felt Hjørneradius for alle fire hjørner; når den er slået fra, har hvert hjørne sit eget felt. What edits in the Transform panel transform: the object, its pattern tiles or both; Default follows Transform Pattern Tiles. Hvad ændringer i panelet Transformér transformerer: objektet, dets mønsterfliser eller begge; Standard følger Transformer mønsterfliser. With one symbol instance selected, the Transform panel uses the symbol's registration point as its reference point. Når én symbolforekomst er markeret, bruger panelet Transformér symbolets registreringspunkt som referencepunkt. + Drawing a rectangle, ellipse, polygon, star or line opens the Transform panel if it is closed. Når du tegner et rektangel, en ellipse, en polygon, en stjerne eller en linje, åbnes panelet Transformér, hvis det er lukket. Darkens the canvas outside the artboards while the Artboard tool is active. Gør lærredet uden for kunstpladerne mørkere, mens værktøjet Kunstplade er aktivt. With Fade Region Outside Artboard on, the area outside the artboards stays dark while you drag with the Artboard tool. Når Ton området uden for kunstpladen ned er slået til, forbliver området uden for kunstpladerne mørkt, mens du trækker med værktøjet Kunstplade. How near, in pixels, the pointer must be to an object, anchor or handle for a click to select it. Hvor tæt markøren i pixels skal være på et objekt, ankerpunkt eller håndtag, for at et klik markerer det. @@ -7194,6 +7281,9 @@ font-technology Variable Variable Channel Kanal Circle Cirkel Circle Tool Cirkelværktøj + Curvature Circle Tool Krumningscirkelværktøj + Cusp Spids + Straight segment Lige segment Circle too large Cirklen er for stor Clip to Art Beskær til grafik Colorize Farvelæg @@ -7576,6 +7666,7 @@ imageTrace Outline Kontur @msg a freeform gradient keeps at least one point en freeform-gradient bevarer mindst ét punkt @msg a gradient needs at least two stops en gradient skal have mindst to stop @msg a graphic style named `{to}` already exists der findes allerede en grafikstil med navnet `{to}` +@msg a swatch or color group named `{name}` already exists der findes allerede en farveprøve eller farvegruppe med navnet `{name}` @msg a page is missing en side mangler @msg a page out of range en side uden for området @msg a page tree kid isn't a reference et barn i sidetræet er ikke en reference @@ -7684,6 +7775,11 @@ imageTrace Outline Kontur @msg no anchor points selected ingen ankerpunkter er markeret @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 the path is straight there, so no circle matches its curvature kurven er lige der, så ingen cirkel passer til dens krumning +@msg the path has a cusp there, so it has no single curvature kurven har en spids der, så den har ingen entydig krumning +@msg the path has a corner there, so it has no single curvature kurven har et hjørne der, så den har ingen entydig krumning +@msg a guide has no curvature circle en hjælpelinje har ingen krumningscirkel +@msg the circle that matches the path there would reach past the canvas cirklen, der passer til kurven der, ville gå ud over lærredet @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 @@ -7895,6 +7991,7 @@ imageTrace Outline Kontur @msg the PDF is password-protected: give its password PDF'en er beskyttet med adgangskode: angiv dens adgangskode @msg the PDF password is wrong PDF-adgangskoden er forkert @msg the Save PDF dialog didn't open dialogen Gem PDF blev ikke åbnet +@msg the Save PDF dialog is not open dialogen Gem PDF er ikke åben @msg the WMF header is damaged WMF-headeren er beskadiget @msg the art could not be sampled der kunne ikke tages prøve af grafikken @msg the art has no bounds grafikken har ingen grænser @@ -8093,6 +8190,7 @@ imageTrace Outline Kontur @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 +@msg give only one of `index`, `indices` and `t` angiv kun én af `index`, `indices` og `t` @msg column must be true or a number from 1 column skal være true eller et tal fra 1 @msg x and y must both be numbers x og y skal begge være tal @msg "{0}" is not a colour: write it as #rrggbb "{0}" er ikke en farve: skriv den som #rrggbb @@ -8188,6 +8286,49 @@ imageTrace Outline Kontur @msg the PSD file's layer groups are nested too deeply PSD-filens laggrupper er indlejret for dybt @msg a layer of the PSD file is too large to read et lag i PSD-filen er for stort til at læse @msg the PSD file's layers take more memory to read than allowed PSD-filens lag kræver mere hukommelse at læse end tilladt +@msg the file is no longer loaded filen er ikke længere indlæst +@msg the layers can't be read ({e}): the file was placed as its merged image lagene kan ikke læses ({e}): filen blev placeret som sit samlede billede +@msg 1 type layer came in as pixels: the text isn't editable 1 tekstlag kom ind som pixels: teksten kan ikke redigeres +@msg {n} type layers came in as pixels: the text isn't editable {n} tekstlag kom ind som pixels: teksten kan ikke redigeres +@msg 1 adjustment layer was not applied 1 justeringslag blev ikke anvendt +@msg {n} adjustment layers were not applied {n} justeringslag blev ikke anvendt +@msg 1 fill layer was not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels) 1 fyldlag blev ikke tegnet (et forløbs- eller mønsterfyld, en farve, der ikke kan læses, eller en figur, der ikke gemmer pixels) +@msg {n} fill layers were not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels) {n} fyldlag blev ikke tegnet (et forløbs- eller mønsterfyld, en farve, der ikke kan læses, eller en figur, der ikke gemmer pixels) +@msg the layer effects of 1 layer weren't drawn lageffekterne for 1 lag blev ikke tegnet +@msg the layer effects of {n} layers weren't drawn lageffekterne for {n} lag blev ikke tegnet +@msg the vector masks of 1 layer weren't applied vektormaskerne for 1 lag blev ikke anvendt +@msg the vector masks of {n} layers weren't applied vektormaskerne for {n} lag blev ikke anvendt +@msg the knockout of 1 layer wasn't applied udsparingen for 1 lag blev ikke anvendt +@msg the knockout of {n} layers wasn't applied udsparingen for {n} lag blev ikke anvendt +@msg 1 layer was left out (hidden layers and the layers clipped to them) 1 lag blev udeladt (skjulte lag og de lag, der er beskåret til dem) +@msg {n} layers were left out (hidden layers and the layers clipped to them) {n} lag blev udeladt (skjulte lag og de lag, der er beskåret til dem) +@msg 1 layer clipped to a fill layer that wasn't drawn was left out 1 lag beskåret til et fyldlag, der ikke blev tegnet, blev udeladt +@msg {n} layers clipped to fill layers that weren't drawn were left out {n} lag beskåret til fyldlag, der ikke blev tegnet, blev udeladt +@msg layers in blend modes VectorCraft doesn't have ({modes}) were merged with the layers below them lag i blandingstilstande, som VectorCraft ikke har ({modes}), blev flettet med lagene under dem +@msg 1 layer in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed 1 lag i en blandingstilstand, som VectorCraft ikke har, kom ind som Normal: fletningen kræver mere hukommelse end tilladt +@msg {n} layers in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed {n} lag i blandingstilstande, som VectorCraft ikke har, kom ind som Normal: fletningen kræver mere hukommelse end tilladt +@msg 1 layer clipped to the layer below came in unclipped: the merge needs more memory than allowed 1 lag beskåret til laget nedenunder kom ind ubeskåret: fletningen kræver mere hukommelse end tilladt +@msg {n} layers clipped to the layer below came in unclipped: the merge needs more memory than allowed {n} lag beskåret til laget nedenunder kom ind ubeskåret: fletningen kræver mere hukommelse end tilladt +@msg hiddenLayers applies to a PSD file placed with layers: true hiddenLayers gælder for en PSD-fil, der placeres med layers: true +@msg importSlices: a linked PSD file is placed as its flat image; give link: false to embed it with its slices importSlices: en sammenkædet PSD-fil placeres som sit flade billede; angiv link: false for at integrere den med dens udsnit +@msg layers: a linked PSD file is placed as its flat image; leave link out or give link: false layers: en sammenkædet PSD-fil placeres som sit flade billede; udelad link eller angiv link: false +@msg the slices can't be read ({e}) and were left out udsnittene kan ikke læses ({e}) og blev udeladt +@msg 1 slice lies outside the canvas or has no size and was left out 1 udsnit ligger uden for lærredet eller har ingen størrelse og blev udeladt +@msg {n} slices lie outside the canvas or have no size and were left out {n} udsnit ligger uden for lærredet eller har ingen størrelse og blev udeladt +@msg 1 slice would lie outside the canvas and was left out 1 udsnit ville ligge uden for lærredet og blev udeladt +@msg {n} slices would lie outside the canvas and were left out {n} udsnit ville ligge uden for lærredet og blev udeladt +@msg the slices' descriptor holds too many values udsnittenes deskriptor indeholder for mange værdier +@msg the slices' descriptor has a version other than 16 udsnittenes deskriptor har en anden version end 16 +@msg the slices are stored in version {v}, which isn't read udsnittene er gemt i version {v}, som ikke læses +@msg the file has {count} slices, more than the {MAX_SLICES} read filen har {count} udsnit, flere end de {MAX_SLICES}, der læses +@msg the slices' descriptor has no list of slices udsnittenes deskriptor har ingen liste over udsnit +@msg the slices' descriptor lists something other than a slice udsnittenes deskriptor angiver noget andet end et udsnit +@msg a slice in the slices' descriptor has no bounds et udsnit i udsnittenes deskriptor har ingen grænser +@msg a slice's bounds in the slices' descriptor aren't numbers et udsnits grænser i udsnittenes deskriptor er ikke tal +@msg a text in the slices has more than the {MAX_TEXT} characters read en tekst i udsnittene har flere end de {MAX_TEXT} tegn, der læses +@msg the slices' descriptor nests too deep udsnittenes deskriptor er indlejret for dybt +@msg the slices' descriptor has a reference of an unknown kind ({_1}) udsnittenes deskriptor har en reference af en ukendt art ({_1}) +@msg the slices' descriptor has a value of an unknown type ({_1}) udsnittenes deskriptor har en værdi af en ukendt type ({_1}) @msg the layers can't be read ({e}): the file opened as its merged image lagene kan ikke læses ({e}): filen blev åbnet som sit samlede billede @msg {depth}-bit PSD files in this colour mode can't be read {depth}-bit PSD-filer i denne farvetilstand kan ikke læses @msg the PSD file is cut short PSD-filen er afkortet @@ -10182,6 +10323,8 @@ breakText Glyphs Glyffer # Path Precision Tools add-on: Tangent Circle. Tangent Circle… Tangentcirkel… Tangent Circle Tangentcirkel + Tangent Circle Tool Tangentcirkel-værktøj + No tangent circle here Ingen tangentcirkel her Circle: Cirkel: @msg `ids` names an object twice `ids` nævner et objekt to gange @msg select two or three paths or compound paths vælg to eller tre stier eller sammensatte stier @@ -10197,6 +10340,16 @@ breakText Glyphs Glyffer @msg `circle` is past the last circle found ({found}) `circle` ligger efter den sidste fundne cirkel ({found}) @msg object {value} is not a path or compound path objekt {value} er ikke en sti eller sammensat sti @msg these shapes are too small to measure disse figurer er for små til at blive målt +# Path Precision Tools add-on: Add Bounding Rectangle and Add Bounding Circle. + Add Bounding Rectangle Tilføj afgrænsende rektangel + Add Bounding Circle Tilføj afgrænsende cirkel + Add Bounding Rectangle… Tilføj afgrænsende rektangel… + Add Bounding Circle… Tilføj afgrænsende cirkel… + One per Object Én pr. objekt +@msg nothing to enclose intet at omslutte +@msg `offset` must be 0 or more `offset` skal være 0 eller mere +@msg the shape would have no size formen ville ikke have nogen størrelse +@msg the shape would reach past the edge of the canvas formen ville gå ud over lærredets kant # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Dokumentværktøjer Save a Timestamped Copy Gem en kopi med dato og klokkeslæt @@ -10531,6 +10684,50 @@ breakText Glyphs Glyffer @msg A joint does not close by {gap} pt. En samling lukker ikke med {gap} pt. @msg Two panels pass through each other. To paneler går gennem hinanden. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer skal være "singleLine", "everyLine", "standardSingleLine" eller "standardEveryLine" + Fine Stipple Fint prikmønster + Dense Stipple Tæt prikmønster + Soft Stipple Blødt prikmønster + Bold Stipple Kraftigt prikmønster + Paper Cutouts Papirudklip + Coral Layers Korallag + Mint Layers Myntelag + Midnight Layers Midnatslag + Sunflower Sheet Solsikkeark + Rose Layers Rosenlag + Monochrome Stack Monokrom stak +# Tool cards (General › Show Tool Cards): one sentence on what each tool does. + Shows a card with what a toolbar tool does and what its keys do instead of its tip; it needs Show Tool Tips. Viser et kort med, hvad et værktøj på værktøjslinjen og dets taster gør, i stedet for dets tip; kræver Vis værktøjstips. + Selects whole objects and groups to move, resize or rotate them. Markerer hele objekter og grupper for at flytte, skalere eller rotere dem. + Selects anchor points and path segments to reshape a path. Markerer ankerpunkter og kurvesegmenter for at ændre formen på en kurve. + Draws paths point by point, with straight segments and smooth curves. Tegner kurver punkt for punkt, med lige segmenter og bløde buer. + Draws smooth curves through the points you click. Tegner bløde buer gennem de punkter, du klikker på. + Adds text at a point, or in a frame you drag. Tilføjer tekst ved et punkt eller i en ramme, du trækker. + Draws rectangles and squares. Tegner rektangler og kvadrater. + Draws rectangles with rounded corners. Tegner rektangler med afrundede hjørner. + Draws ellipses and circles. Tegner ellipser og cirkler. + Draws polygons with sides of equal length. Tegner polygoner med lige lange sider. + Draws stars. Tegner stjerner. + Turns objects around a reference point. Roterer objekter om et referencepunkt. + Flips objects across an axis through a reference point. Spejler objekter over en akse gennem et referencepunkt. + Resizes objects from a reference point. Skalerer objekter fra et referencepunkt. + Slants objects from a reference point. Skråtstiller objekter fra et referencepunkt. + Moves the view of the document. Flytter visningen af dokumentet. + Magnifies or reduces the view. Forstørrer eller formindsker visningen. + Copies the color and other attributes of one object to the selection. Kopierer farven og andre egenskaber fra ét objekt til markeringen. + Sets the direction and length of a gradient. Angiver retning og længde for en gradient. + Creates, selects and resizes artboards. Opretter, markerer og skalerer tegneflader. + Changes the width of a stroke along its length. Ændrer bredden på en streg langs dens længde. + Bends art by dragging pins placed on it. Bøjer grafik ved at trække i nåle, der er placeret på den. + Pushes the outlines of paths in the direction you drag. Skubber kurvers omrids i den retning, du trækker. + Twists the outlines of paths into swirls. Snor kurvers omrids til hvirvler. + Pulls the outlines of paths in toward the brush. Trækker kurvers omrids ind mod penslen. + Pushes the outlines of paths out from the brush. Skubber kurvers omrids ud fra penslen. + Adds curved details along the outlines of paths. Tilføjer buede detaljer langs kurvers omrids. + Adds spiky details along the outlines of paths. Tilføjer spidse detaljer langs kurvers omrids. + Adds wrinkles along the outlines of paths. Tilføjer rynker langs kurvers omrids. + Moves, copies and resizes objects on the perspective grid. Flytter, kopierer og skalerer objekter på perspektivgitteret. + Makes a series of steps between two or more objects. Laver en række trin mellem to eller flere objekter. + Places dimension lines that show measured lengths. Placerer målelinjer, der viser målte længder. Tap Kort tryk Clear Hold Ryd hold Hold Shortcuts Holdegenveje @@ -10548,3 +10745,7 @@ breakText Glyphs Glyffer Pulse Stroke Pulserende strøg Round Flow Rundt strøg Chisel Flow Skråt strøg + +# #5804 native-picked raster editor (draft translations; native review welcome). + Edit Original with: Redigér original med: +file-filter Applications Programmer diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index ce3adc682f..4d5f69a2c1 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -475,6 +475,9 @@ font-technology Variable Variabel Choose… Wählen… Circle Kreis Circle Tool Kreis-Werkzeug + Curvature Circle Tool Krümmungskreis-Werkzeug + Cusp Spitze + Straight segment Gerades Segment Circle too large Kreis zu groß Classic Defaults Klassische Standardwerte Clean Up… Aufräumen… @@ -585,6 +588,9 @@ font-technology Variable Variabel Box Channel Kanal des Quadrats Color box Farbquadrat Color Wheel Options Optionen für den Farbkreis + Show Harmony Harmonie einblenden + Harmony Rule Harmonieregel + Harmony color Harmoniefarbe Color Type: Farbart: Color: Farbe: Colorize Einfärben @@ -1019,10 +1025,25 @@ font-technology Variable Variabel Duplicate Symbol Symbol duplizieren Duplicate {kind} Style {kind}format duplizieren Dutch Niederländisch + PSD Import Options PSD-Importoptionen + Place PSD PSD platzieren + Convert Layers to Objects Ebenen in Objekte umwandeln + Import Hidden Layers Ausgeblendete Ebenen importieren + Flatten Layers to a Single Image Ebenen auf ein einzelnes Bild reduzieren + Import Slices Slices importieren DXF Import Options DXF-Importoptionen DXF Info DXF-Informationen DXF Options DXF-Optionen DXF Options Dialog Dialogfeld „DXF-Optionen“ + HP-GL Options HP-GL-Optionen + HP-GL Options Dialog Dialogfeld „HP-GL-Optionen“ + Curve Tolerance: Kurventoleranz: + Origin: Ursprung: + Pens: Stifte: + One Pen per Color Ein Stift pro Farbe + Pen Table Stifttabelle + Draw the Nearest Path Next Nächstgelegenen Pfad als Nächstes zeichnen + Draw Inner Paths First Innere Pfade zuerst zeichnen e.g. 1-3, 5 z. B. 1-3, 5 Each page prints as one image, at the document's raster effects resolution. Jede Seite wird als ein Bild gedruckt, in der Rastereffektauflösung des Dokuments. Earth Tones Erdtöne @@ -1245,6 +1266,15 @@ font-technology Variable Variabel Shading Color Schattierungsfarbe Black Overprint Überdruckendes Schwarz Draw Hidden Faces Verdeckte Flächen zeichnen + Map Art… Bildmaterial zuordnen… + Map Art Bildmaterial zuordnen + First Surface Erste Oberfläche + Previous Surface Vorherige Oberfläche + Next Surface Nächste Oberfläche + Last Surface Letzte Oberfläche + Scale to Fit Auf Oberfläche skalieren + Shade Artwork Bildmaterial schattieren + Invisible Geometry Unsichtbare Geometrie Eyedropper Pipette Sample Color from Screen Farbe vom Bildschirm aufnehmen This system has no screen color sampler Dieses System hat keine Farbaufnahme vom Bildschirm @@ -1374,6 +1404,17 @@ font-technology Variable Variabel Largest: Größter: Direction: Richtung: Symbolism Tools Options Optionen für die Symbol-Werkzeuge + Tool: Werkzeug: + Symbol Set Density Dichte des Symbolsatzes + Symbol Sprayer Options Optionen für „Symbol aufsprühen“ + Scrunch: Stauchen: + Spin: Drehen: + Screen: Transparenz: + Stain: Färben: + Symbol Sizer Options Optionen für „Symbol skalieren“ + Proportional Resizing Proportional skalieren + Resizing Affects Density Skalieren beeinflusst die Dichte + Show Brush Size and Intensity Pinselgröße und Intensität anzeigen Symbol Set Density: Dichte des Symbolsatzes: Flat Image Reduziertes Bild Flat Logo Flaches Logo @@ -1655,6 +1696,8 @@ file-filter Templates Vorlagen More Options Weitere Optionen Show Properties Panel Bedienfeld „Eigenschaften“ einblenden Hide Corner Widget Ecken-Widget ausblenden + Hide Shape Widgets Form-Widgets ausblenden + Show Shape Widgets Form-Widgets einblenden Hide Corner Widget for angles greater than Ecken-Widget ausblenden bei Winkeln größer als Hide Edges Kanten ausblenden Hide Gradient Annotator Verlaufsoptimierer ausblenden @@ -2224,6 +2267,15 @@ file-filter Templates Vorlagen YakumonoZenkaku YakumonoZenkaku Kinsoku Set Kinsoku-Satz Kinsoku Shori Type Kinsoku-Shori-Typ + Kinsoku Shori Settings… Kinsoku-Shori-Einstellungen… + Kinsoku Shori Settings Kinsoku-Shori-Einstellungen + Kinsoku Sets Kinsoku-Sätze + Kinsoku Set Base Basis des Kinsoku-Satzes + Based on: Basierend auf: + Cannot Start Line Kann Zeile nicht beginnen + Cannot End Line Kann Zeile nicht beenden + Hanging Punctuation Hängende Interpunktion + Inseparable Characters Untrennbare Zeichen Push In First Zuerst einziehen Push Out First Zuerst hinausschieben Push Out Only Nur hinausschieben @@ -2297,6 +2349,7 @@ file-filter Templates Vorlagen Pressure Druck Tilt Neigung Bearing Richtung + Stylus Wheel Stiftrad Shape: Form: Bristle Length: Borstenlänge: Bristle Density: Borstendichte: @@ -2327,6 +2380,9 @@ file-filter Templates Vorlagen embedding for preview and print Einbetten für Vorschau und Druck embedding allowed Einbetten erlaubt {file}; {embedding} {file}; {embedding} + unknown type unbekannter Typ + {type}; {uses} {type}; {uses} +@plural {n} use|{n} uses {n} Verwendung|{n} Verwendungen substituted: shown in {family} {style} ({detail}) ersetzt: angezeigt in {family} {style} ({detail}) missing: shown in {family} {style} fehlt: angezeigt in {family} {style} missing fehlt @@ -2599,6 +2655,8 @@ file-filter Templates Vorlagen Overprint and Transparency Flattener Options Optionen für Überdrucken und Transparenzreduzierung Custom… Benutzerdefiniert… Custom Transparency Flattener Options Benutzerdefinierte Optionen für Transparenzreduzierung + The PDF preset keeps the flattener preset but not the Custom… settings. Die PDF-Vorgabe speichert die Reduzierungsvorgabe, aber nicht die Einstellungen unter „Benutzerdefiniert…“. + PDF 1.3 files clip rasterized areas to their regions, and Overprint sets whether overprints are kept. PDF-1.3-Dateien beschneiden gerasterte Bereiche auf ihre Regionen, und „Überdrucken“ legt fest, ob Überdrucken erhalten bleibt. EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS hat keine Alphatransparenz, und „Überdrucken“ legt fest, ob Überdrucken erhalten bleibt. Overprint Black… Schwarz überdrucken… Overprint Fill Fläche überdrucken @@ -3119,6 +3177,9 @@ digits Malayalam Malayalam Rotate View to Selection Ansicht nach Auswahl drehen Reset the rows to the artwork's colors Zeilen auf die Farben der Grafik zurücksetzen Color Theme Picker Farbthema-Auswahl + Undo Changes Änderungen rückgängig machen + Redo Changes Änderungen wiederholen +@msg Recolor Artwork is not open „Grafik neu färben“ ist nicht geöffnet Click or drag across the art to pick its colors; Shift adds more Klicken oder ziehen Sie über die Grafik, um ihre Farben aufzunehmen; Umschalt fügt weitere hinzu Prominent Colors Hervorstechende Farben Save All Colors Alle Farben speichern @@ -3173,6 +3234,7 @@ digits Malayalam Malayalam A live rectangle's properties show one Corner Radius field for all four corners; off, each corner has its own field. Die Eigenschaften eines Live-Rechtecks zeigen ein Feld „Eckenradius“ für alle vier Ecken; ist die Option aus, hat jede Ecke ihr eigenes Feld. What edits in the Transform panel transform: the object, its pattern tiles or both; Default follows Transform Pattern Tiles. Was Änderungen im Bedienfeld „Transformieren“ transformieren: das Objekt, seine Musterkacheln oder beides; „Standard“ folgt „Musterkacheln transformieren“. With one symbol instance selected, the Transform panel uses the symbol's registration point as its reference point. Ist eine Symbolinstanz ausgewählt, verwendet das Bedienfeld „Transformieren“ den Registrierungspunkt des Symbols als Referenzpunkt. + Drawing a rectangle, ellipse, polygon, star or line opens the Transform panel if it is closed. Wenn Sie ein Rechteck, eine Ellipse, ein Polygon, einen Stern oder eine Linie zeichnen, wird das Bedienfeld „Transformieren“ geöffnet, falls es geschlossen ist. Darkens the canvas outside the artboards while the Artboard tool is active. Dunkelt die Arbeitsfläche außerhalb der Zeichenflächen ab, solange das Zeichenflächen-Werkzeug aktiv ist. With Fade Region Outside Artboard on, the area outside the artboards stays dark while you drag with the Artboard tool. Ist „Bereich außerhalb der Zeichenfläche abblenden“ an, bleibt der Bereich außerhalb der Zeichenflächen dunkel, während Sie mit dem Zeichenflächen-Werkzeug ziehen. How near, in pixels, the pointer must be to an object, anchor or handle for a click to select it. Wie nah der Zeiger in Pixeln an einem Objekt, Ankerpunkt oder Griff sein muss, damit ein Klick es auswählt. @@ -3353,6 +3415,7 @@ digits Malayalam Malayalam Save Document Preset Dokumentvorgabe speichern Preset {number} Vorgabe {number} Save Preset… Vorgabe speichern… + Save Summary… Übersicht speichern… Save Print Preset Druckvorgabe speichern Save Recovery Data Wiederherstellungsdaten speichern Save Save for Web Preset Vorgabe für „Für Web speichern“ speichern @@ -3661,6 +3724,7 @@ digits Malayalam Malayalam Show Modified Geänderte einblenden Show Note Notiz einblenden Show Options Optionen einblenden + Show on Shape Creation Beim Erstellen von Formen einblenden Show Recent Colors Zuletzt verwendete Farben einblenden Toggle RGB Percent RGB in Prozent umschalten Show Original Path Originalpfad einblenden @@ -3688,6 +3752,7 @@ digits Malayalam Malayalam Show Thumbnails Miniaturen einblenden Show Tile Edge Kachelkante einblenden Show Tints/Shades Aufhellungen/Abdunklungen einblenden + Show Tool Cards Werkzeugkarten anzeigen Show Tool Tips Tooltips anzeigen Show Transparency Grid Transparenzraster einblenden Show Video Rulers Videolineale einblenden @@ -3774,6 +3839,8 @@ effect Points Punkte Outlines Pfade Outlines with Source Image Pfade mit Quellbild Source Image Quellbild + Split View Geteilte Ansicht + Divider Trennlinie Press and hold to view the source image Gedrückt halten, um das Quellbild anzuzeigen Image Trace View Bildnachzeichner-Ansicht Snap Options Einrastoptionen @@ -4208,6 +4275,8 @@ effect Points Punkte Unembed… Einbettung aufheben… Ungroup Gruppierung aufheben Ungroup Color Group Farbgruppe auflösen + Color Group Options Farbgruppenoptionen + Color Group Options… Farbgruppenoptionen… Unicode Unicode Unicode (UTF-16) Unicode (UTF-16) Unicode (UTF-8) Unicode (UTF-8) @@ -4964,6 +5033,7 @@ liquify-list-end {0}, {1} {0} und {1} @msg a freeform gradient keeps at least one point ein Freiformverlauf behält mindestens einen Punkt @msg a gradient needs at least two stops ein Verlauf braucht mindestens zwei Farbstopps @msg a graphic style named `{to}` already exists ein Grafikstil namens `{to}` ist bereits vorhanden +@msg a swatch or color group named `{name}` already exists ein Farbfeld oder eine Farbgruppe namens `{name}` ist bereits vorhanden @msg a key object sits on that point auf diesem Punkt liegt ein Basisobjekt @msg a page is missing eine Seite fehlt @msg a page out of range eine Seite außerhalb des Bereichs @@ -5105,6 +5175,11 @@ liquify-list-end {0}, {1} {0} und {1} @msg no anchor points selected keine Ankerpunkte ausgewählt @msg `points` must be two or three [x, y] pairs of numbers `points` muss aus zwei oder drei Zahlenpaaren [x, y] bestehen @msg direct-select two or three anchor points, or give `points` wählen Sie zwei oder drei Ankerpunkte direkt aus oder geben Sie `points` an +@msg the path is straight there, so no circle matches its curvature der Pfad ist dort gerade, daher passt kein Kreis zu seiner Krümmung +@msg the path has a cusp there, so it has no single curvature der Pfad hat dort eine Spitze und daher keine eindeutige Krümmung +@msg the path has a corner there, so it has no single curvature der Pfad hat dort eine Ecke und daher keine eindeutige Krümmung +@msg a guide has no curvature circle eine Hilfslinie hat keinen Krümmungskreis +@msg the circle that matches the path there would reach past the canvas der Kreis, der dort zum Pfad passt, würde über die Arbeitsfläche hinausreichen @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 @@ -5362,6 +5437,7 @@ liquify-list-end {0}, {1} {0} und {1} @msg the PDF is password-protected: give its password die PDF-Datei ist kennwortgeschützt: Geben Sie ihr Kennwort an @msg the PDF password is wrong das PDF-Kennwort ist falsch @msg the Save PDF dialog didn't open das Dialogfeld „PDF speichern“ wurde nicht geöffnet +@msg the Save PDF dialog is not open das Dialogfeld „PDF speichern“ ist nicht geöffnet @msg the WMF header is damaged der WMF-Header ist beschädigt @msg the art could not be sampled die Grafik konnte nicht abgetastet werden @msg the art has no bounds die Grafik hat keine Begrenzung @@ -5585,6 +5661,7 @@ variable-list-end {0}, {1} {0} und {1} @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 +@msg give only one of `index`, `indices` and `t` nur eines von `index`, `indices` und `t` angeben @msg column must be true or a number from 1 column muss true oder eine Zahl ab 1 sein @msg x and y must both be numbers x und y müssen beide Zahlen sein @msg "{0}" is not a colour: write it as #rrggbb "{0}" ist keine Farbe: Schreiben Sie sie als #rrggbb @@ -5821,6 +5898,25 @@ variable-list-end {0}, {1} {0} und {1} Preserve Embedded Profiles Eingebettete Profile beibehalten Convert to Working Space In Arbeitsfarbraum konvertieren Preserve Numbers Werte beibehalten + Profile Mismatches: Profilabweichungen: + Ask When Opening Beim Öffnen fragen + Ask When Pasting Beim Einfügen fragen + Missing Profiles: Fehlende Profile: + Embedded Profile Mismatch Abweichung vom eingebetteten Profil + Missing Profile Fehlendes Profil + Paste Profile Mismatch Profilabweichung beim Einfügen + “{name}” is not tagged with a {model} profile. „{name}“ ist mit keinem {model}-Profil versehen. + “{name}” is tagged with the {model} profile “{profile}”, which is not the {model} working space “{working}”. „{name}“ ist mit dem {model}-Profil „{profile}“ versehen, das nicht der {model}-Arbeitsfarbraum „{working}“ ist. + Use the embedded profile Eingebettetes Profil verwenden + Convert the colors to the working space Farben in den Arbeitsfarbraum konvertieren + Discard the embedded profile Eingebettetes Profil verwerfen + Leave as is Unverändert lassen + Assign the working space Arbeitsfarbraum zuweisen + Assign profile: Profil zuweisen: + Preserve the color numbers Farbwerte beibehalten + Convert to keep the colors' appearance Konvertieren, um das Aussehen der Farben zu erhalten +@msg `{path}` goes with `{key}`: "assign" only `{path}` gehört nur zu `{key}`: "assign" + The pasted colors come from a document whose {model} profile is “{from}”; this document's is “{to}”. Die eingefügten Farben stammen aus einem Dokument mit dem {model}-Profil „{from}“; dieses Dokument hat „{to}“. # PSD files. @msg not a PSD file keine PSD-Datei @msg Multichannel PSD files can't be read: save it in RGB, CMYK or Grayscale mode PSD-Dateien im Mehrkanalmodus können nicht gelesen werden: Speichern Sie die Datei im RGB-, CMYK- oder Graustufenmodus @@ -5847,6 +5943,49 @@ variable-list-end {0}, {1} {0} und {1} @msg the PSD file's layer groups are nested too deeply die Ebenengruppen der PSD-Datei sind zu tief verschachtelt @msg a layer of the PSD file is too large to read eine Ebene der PSD-Datei ist zu groß zum Lesen @msg the PSD file's layers take more memory to read than allowed die Ebenen der PSD-Datei brauchen zum Lesen mehr Speicher als erlaubt +@msg the file is no longer loaded die Datei ist nicht mehr geladen +@msg the layers can't be read ({e}): the file was placed as its merged image die Ebenen können nicht gelesen werden ({e}): die Datei wurde als ihr zusammengefügtes Bild platziert +@msg 1 type layer came in as pixels: the text isn't editable 1 Textebene wurde als Pixel übernommen: der Text ist nicht bearbeitbar +@msg {n} type layers came in as pixels: the text isn't editable {n} Textebenen wurden als Pixel übernommen: der Text ist nicht bearbeitbar +@msg 1 adjustment layer was not applied 1 Einstellungsebene wurde nicht angewendet +@msg {n} adjustment layers were not applied {n} Einstellungsebenen wurden nicht angewendet +@msg 1 fill layer was not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels) 1 Füllebene wurde nicht gezeichnet (eine Verlaufs- oder Musterfüllung, eine Farbe, die nicht gelesen werden kann, oder eine Form ohne gespeicherte Pixel) +@msg {n} fill layers were not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels) {n} Füllebenen wurden nicht gezeichnet (eine Verlaufs- oder Musterfüllung, eine Farbe, die nicht gelesen werden kann, oder eine Form ohne gespeicherte Pixel) +@msg the layer effects of 1 layer weren't drawn die Ebeneneffekte von 1 Ebene wurden nicht gezeichnet +@msg the layer effects of {n} layers weren't drawn die Ebeneneffekte von {n} Ebenen wurden nicht gezeichnet +@msg the vector masks of 1 layer weren't applied die Vektormasken von 1 Ebene wurden nicht angewendet +@msg the vector masks of {n} layers weren't applied die Vektormasken von {n} Ebenen wurden nicht angewendet +@msg the knockout of 1 layer wasn't applied die Aussparung von 1 Ebene wurde nicht angewendet +@msg the knockout of {n} layers wasn't applied die Aussparung von {n} Ebenen wurde nicht angewendet +@msg 1 layer was left out (hidden layers and the layers clipped to them) 1 Ebene wurde weggelassen (ausgeblendete Ebenen und die auf sie beschnittenen Ebenen) +@msg {n} layers were left out (hidden layers and the layers clipped to them) {n} Ebenen wurden weggelassen (ausgeblendete Ebenen und die auf sie beschnittenen Ebenen) +@msg 1 layer clipped to a fill layer that wasn't drawn was left out 1 Ebene, die auf eine nicht gezeichnete Füllebene beschnitten ist, wurde weggelassen +@msg {n} layers clipped to fill layers that weren't drawn were left out {n} Ebenen, die auf nicht gezeichnete Füllebenen beschnitten sind, wurden weggelassen +@msg layers in blend modes VectorCraft doesn't have ({modes}) were merged with the layers below them Ebenen in Füllmethoden, die VectorCraft nicht hat ({modes}), wurden mit den Ebenen darunter zusammengefügt +@msg 1 layer in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed 1 Ebene in einer Füllmethode, die VectorCraft nicht hat, wurde als Normal übernommen: das Zusammenfügen braucht mehr Speicher als erlaubt +@msg {n} layers in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed {n} Ebenen in Füllmethoden, die VectorCraft nicht hat, wurden als Normal übernommen: das Zusammenfügen braucht mehr Speicher als erlaubt +@msg 1 layer clipped to the layer below came in unclipped: the merge needs more memory than allowed 1 Ebene, die auf die Ebene darunter beschnitten ist, wurde unbeschnitten übernommen: das Zusammenfügen braucht mehr Speicher als erlaubt +@msg {n} layers clipped to the layer below came in unclipped: the merge needs more memory than allowed {n} Ebenen, die auf die Ebene darunter beschnitten sind, wurden unbeschnitten übernommen: das Zusammenfügen braucht mehr Speicher als erlaubt +@msg hiddenLayers applies to a PSD file placed with layers: true hiddenLayers gilt für eine PSD-Datei, die mit layers: true platziert wird +@msg importSlices: a linked PSD file is placed as its flat image; give link: false to embed it with its slices importSlices: eine verknüpfte PSD-Datei wird als ihr flaches Bild platziert; geben Sie link: false an, um sie mit ihren Slices einzubetten +@msg layers: a linked PSD file is placed as its flat image; leave link out or give link: false layers: eine verknüpfte PSD-Datei wird als ihr flaches Bild platziert; lassen Sie link weg oder geben Sie link: false an +@msg the slices can't be read ({e}) and were left out die Slices können nicht gelesen werden ({e}) und wurden weggelassen +@msg 1 slice lies outside the canvas or has no size and was left out 1 Slice liegt außerhalb der Arbeitsfläche oder hat keine Größe und wurde weggelassen +@msg {n} slices lie outside the canvas or have no size and were left out {n} Slices liegen außerhalb der Arbeitsfläche oder haben keine Größe und wurden weggelassen +@msg 1 slice would lie outside the canvas and was left out 1 Slice würde außerhalb der Arbeitsfläche liegen und wurde weggelassen +@msg {n} slices would lie outside the canvas and were left out {n} Slices würden außerhalb der Arbeitsfläche liegen und wurden weggelassen +@msg the slices' descriptor holds too many values der Deskriptor der Slices enthält zu viele Werte +@msg the slices' descriptor has a version other than 16 der Deskriptor der Slices hat eine andere Version als 16 +@msg the slices are stored in version {v}, which isn't read die Slices sind in Version {v} gespeichert, die nicht gelesen wird +@msg the file has {count} slices, more than the {MAX_SLICES} read die Datei hat {count} Slices, mehr als die {MAX_SLICES}, die gelesen werden +@msg the slices' descriptor has no list of slices der Deskriptor der Slices hat keine Liste der Slices +@msg the slices' descriptor lists something other than a slice der Deskriptor der Slices führt etwas anderes als ein Slice auf +@msg a slice in the slices' descriptor has no bounds ein Slice im Deskriptor der Slices hat keine Begrenzung +@msg a slice's bounds in the slices' descriptor aren't numbers die Begrenzung eines Slices im Deskriptor der Slices besteht nicht aus Zahlen +@msg a text in the slices has more than the {MAX_TEXT} characters read ein Text in den Slices hat mehr als die {MAX_TEXT} Zeichen, die gelesen werden +@msg the slices' descriptor nests too deep der Deskriptor der Slices ist zu tief verschachtelt +@msg the slices' descriptor has a reference of an unknown kind ({_1}) der Deskriptor der Slices hat einen Verweis unbekannter Art ({_1}) +@msg the slices' descriptor has a value of an unknown type ({_1}) der Deskriptor der Slices hat einen Wert unbekannten Typs ({_1}) @msg the layers can't be read ({e}): the file opened as its merged image die Ebenen können nicht gelesen werden ({e}): die Datei wurde als ihr zusammengefügtes Bild geöffnet @msg {depth}-bit PSD files in this colour mode can't be read {depth}-Bit-PSD-Dateien in diesem Farbmodus können nicht gelesen werden @msg the JPEG XL file is cut short die JPEG-XL-Datei ist unvollständig @@ -7724,6 +7863,8 @@ breakText Glyphs Glyphen # Path Precision Tools add-on: Tangent Circle. Tangent Circle… Tangentialkreis… Tangent Circle Tangentialkreis + Tangent Circle Tool Tangentialkreis-Werkzeug + No tangent circle here Hier kein Tangentialkreis Circle: Kreis: @msg `ids` names an object twice `ids` nennt ein Objekt zweimal @msg select two or three paths or compound paths wählen Sie zwei oder drei Pfade oder zusammengesetzte Pfade aus @@ -7739,6 +7880,16 @@ breakText Glyphs Glyphen @msg `circle` is past the last circle found ({found}) `circle` liegt hinter dem letzten gefundenen Kreis ({found}) @msg object {value} is not a path or compound path Objekt {value} ist kein Pfad oder zusammengesetzter Pfad @msg these shapes are too small to measure diese Formen sind zu klein zum Messen +# Path Precision Tools add-on: Add Bounding Rectangle and Add Bounding Circle. + Add Bounding Rectangle Begrenzungsrechteck hinzufügen + Add Bounding Circle Begrenzungskreis hinzufügen + Add Bounding Rectangle… Begrenzungsrechteck hinzufügen… + Add Bounding Circle… Begrenzungskreis hinzufügen… + One per Object Eine pro Objekt +@msg nothing to enclose nichts zu umschließen +@msg `offset` must be 0 or more `offset` muss 0 oder größer sein +@msg the shape would have no size die Form hätte keine Größe +@msg the shape would reach past the edge of the canvas die Form würde über den Rand der Arbeitsfläche hinausreichen # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Dokumentwerkzeuge Save a Timestamped Copy Kopie mit Zeitstempel speichern @@ -10021,6 +10172,39 @@ breakText Glyphs Glyphen No objects are selected. Es sind keine Objekte ausgewählt. Open a document to mark its fold lines. Öffnen Sie ein Dokument, um seine Faltlinien festzulegen. Remove Fold Line Role Linienart entfernen +# Tool cards (General › Show Tool Cards): one sentence on what each tool does. + Shows a card with what a toolbar tool does and what its keys do instead of its tip; it needs Show Tool Tips. Zeigt statt des Tooltips eine Karte, was ein Werkzeug der Werkzeugleiste und seine Tasten tun; erfordert Tooltips anzeigen. + Selects whole objects and groups to move, resize or rotate them. Wählt ganze Objekte und Gruppen aus, um sie zu verschieben, zu skalieren oder zu drehen. + Selects anchor points and path segments to reshape a path. Wählt Ankerpunkte und Pfadsegmente aus, um einen Pfad umzuformen. + Draws paths point by point, with straight segments and smooth curves. Zeichnet Pfade Punkt für Punkt, mit geraden Segmenten und glatten Kurven. + Draws smooth curves through the points you click. Zeichnet glatte Kurven durch die Punkte, die Sie klicken. + Adds text at a point, or in a frame you drag. Fügt Text an einem Punkt oder in einem aufgezogenen Rahmen ein. + Draws rectangles and squares. Zeichnet Rechtecke und Quadrate. + Draws rectangles with rounded corners. Zeichnet Rechtecke mit abgerundeten Ecken. + Draws ellipses and circles. Zeichnet Ellipsen und Kreise. + Draws polygons with sides of equal length. Zeichnet Polygone mit gleich langen Seiten. + Draws stars. Zeichnet Sterne. + Turns objects around a reference point. Dreht Objekte um einen Referenzpunkt. + Flips objects across an axis through a reference point. Spiegelt Objekte an einer Achse durch einen Referenzpunkt. + Resizes objects from a reference point. Skaliert Objekte von einem Referenzpunkt aus. + Slants objects from a reference point. Neigt Objekte von einem Referenzpunkt aus. + Moves the view of the document. Verschiebt die Ansicht des Dokuments. + Magnifies or reduces the view. Vergrößert oder verkleinert die Ansicht. + Copies the color and other attributes of one object to the selection. Überträgt die Farbe und andere Attribute eines Objekts auf die Auswahl. + Sets the direction and length of a gradient. Legt Richtung und Länge eines Verlaufs fest. + Creates, selects and resizes artboards. Erstellt, wählt und skaliert Zeichenflächen. + Changes the width of a stroke along its length. Ändert die Breite einer Kontur entlang ihrer Länge. + Bends art by dragging pins placed on it. Verbiegt Bildmaterial durch Ziehen von Pins, die darauf gesetzt sind. + Pushes the outlines of paths in the direction you drag. Schiebt die Umrisse von Pfaden in die Richtung, in die Sie ziehen. + Twists the outlines of paths into swirls. Verdreht die Umrisse von Pfaden zu Wirbeln. + Pulls the outlines of paths in toward the brush. Zieht die Umrisse von Pfaden zum Pinsel hin zusammen. + Pushes the outlines of paths out from the brush. Drückt die Umrisse von Pfaden vom Pinsel weg nach außen. + Adds curved details along the outlines of paths. Fügt den Umrissen von Pfaden gebogene Details hinzu. + Adds spiky details along the outlines of paths. Fügt den Umrissen von Pfaden spitze Details hinzu. + Adds wrinkles along the outlines of paths. Fügt den Umrissen von Pfaden Falten hinzu. + Moves, copies and resizes objects on the perspective grid. Verschiebt, kopiert und skaliert Objekte im Perspektivenraster. + Makes a series of steps between two or more objects. Erzeugt eine Reihe von Stufen zwischen zwei oder mehr Objekten. + Places dimension lines that show measured lengths. Platziert Bemaßungslinien, die gemessene Längen anzeigen. Tap Kurz drücken Clear Hold Halten löschen Hold Shortcuts Halte-Tastaturbefehle @@ -10051,7 +10235,18 @@ breakText Glyphs Glyphen @msg A panel is not joined to the rest by a crease. Ein Feld ist durch keine Rilllinie mit den übrigen verbunden. @msg A fold line is on a non-printing layer. Eine Faltlinie liegt auf einer nicht druckbaren Ebene. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Felder: {panels}, Scharniere: {hinges}, Fehler: {errors}, Warnungen: {warnings} + Paper Cutouts Papierschnitte + Coral Layers Korallschichten + Mint Layers Minzschichten + Midnight Layers Mitternachtsschichten + Sunflower Sheet Sonnenblumenblatt + Rose Layers Rosenschichten + Monochrome Stack Monochromer Stapel Dashed Arrow Gestrichelter Pfeil + Fine Stipple Feine Punktierung + Dense Stipple Dichte Punktierung + Soft Stipple Weiche Punktierung + Bold Stipple Kräftige Punktierung Pressure Sensitive Druckempfindlich Flex Ribbon Flexibles Band Pulse Stroke Pulsierender Strich @@ -10067,3 +10262,7 @@ breakText Glyphs Glyphen @msg Other blanks not shown: {count} Weitere Zuschnitte nicht angezeigt: {count} @msg A joint does not close by {gap} pt. Eine Verbindung schließt um {gap} pt nicht. @msg Two panels pass through each other. Zwei Felder durchdringen einander. + +# #5804 native-picked raster editor (draft translations; native review welcome). + Edit Original with: Original bearbeiten mit: +file-filter Applications Anwendungen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index b627ceb826..6a36ef6515 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -468,6 +468,9 @@ font-technology Variable Μεταβλητές Choose… Επιλογή… Circle Κύκλος Circle Tool Εργαλείο κύκλου + Curvature Circle Tool Εργαλείο Κύκλος καμπυλότητας + Cusp Ακίδα + Straight segment Ευθύ τμήμα Circle too large Ο κύκλος είναι πολύ μεγάλος Classic Defaults Κλασικές προεπιλογές Clean Up… Εκκαθάριση… @@ -560,6 +563,9 @@ font-technology Variable Μεταβλητές Box Channel Κανάλι τετραγώνου Color box Τετράγωνο χρώματος Color Wheel Options Επιλογές χρωματικού τροχού + Show Harmony Εμφάνιση αρμονίας + Harmony Rule Κανόνας χρωματικής αρμονίας + Harmony color Χρώμα αρμονίας Color Type: Τύπος χρώματος: Color: Χρώμα: Colorize Χρωματισμός @@ -981,10 +987,25 @@ font-technology Variable Μεταβλητές Duplicate Swatch Δημιουργία αντιγράφου δείγματος χρώματος Duplicate Symbol Δημιουργία αντιγράφου συμβόλου Duplicate {kind} Style Δημιουργία αντιγράφου στυλ {kind} + PSD Import Options Επιλογές εισαγωγής PSD + Place PSD Τοποθέτηση PSD + Convert Layers to Objects Μετατροπή επιπέδων σε αντικείμενα + Import Hidden Layers Εισαγωγή κρυφών επιπέδων + Flatten Layers to a Single Image Ισοπέδωση επιπέδων σε μία εικόνα + Import Slices Εισαγωγή τομών DXF Import Options Επιλογές εισαγωγής DXF DXF Info Πληροφορίες DXF DXF Options Επιλογές DXF DXF Options Dialog Παράθυρο επιλογών DXF + HP-GL Options Επιλογές HP-GL + HP-GL Options Dialog Παράθυρο επιλογών HP-GL + Curve Tolerance: Ανοχή καμπυλών: + Origin: Αρχή αξόνων: + Pens: Πένες: + One Pen per Color Μία πένα ανά χρώμα + Pen Table Πίνακας πενών + Draw the Nearest Path Next Σχεδίαση της πλησιέστερης διαδρομής ως επόμενης + Draw Inner Paths First Σχεδίαση πρώτα των εσωτερικών διαδρομών e.g. 1-3, 5 π.χ. 1-3, 5 Earth Tones Γήινοι τόνοι East Asian Type Κείμενο Ανατολικής Ασίας @@ -1205,6 +1226,15 @@ font-technology Variable Μεταβλητές Shading Color Χρώμα σκίασης Black Overprint Μαύρο με υπερεκτύπωση Draw Hidden Faces Σχεδίαση κρυφών εδρών + Map Art… Αντιστοίχιση γραφικών… + Map Art Αντιστοίχιση γραφικών + First Surface Πρώτη επιφάνεια + Previous Surface Προηγούμενη επιφάνεια + Next Surface Επόμενη επιφάνεια + Last Surface Τελευταία επιφάνεια + Scale to Fit Κλιμάκωση για προσαρμογή + Shade Artwork Σκίαση γραφικών + Invisible Geometry Αόρατη γεωμετρία Eyedropper Σταγονόμετρο (Eyedropper Tool) Eyedropper Applies: Το σταγονόμετρο εφαρμόζει: Eyedropper Options Επιλογές σταγονόμετρου @@ -1312,6 +1342,17 @@ font-technology Variable Μεταβλητές Largest: Μεγαλύτερο: Direction: Κατεύθυνση: Symbolism Tools Options Επιλογές εργαλείων συμβόλων + Tool: Εργαλείο: + Symbol Set Density Πυκνότητα συνόλου συμβόλων + Symbol Sprayer Options Επιλογές ψεκαστήρα συμβόλων + Scrunch: Σύμπτυξη: + Spin: Περιστροφή: + Screen: Αραίωση: + Stain: Χρωματισμός: + Symbol Sizer Options Επιλογές αλλαγής μεγέθους συμβόλων + Proportional Resizing Αναλογική αλλαγή μεγέθους + Resizing Affects Density Η αλλαγή μεγέθους επηρεάζει την πυκνότητα + Show Brush Size and Intensity Εμφάνιση μεγέθους και έντασης πινέλου Symbol Set Density: Πυκνότητα συνόλου συμβόλων: Flat Image Επίπεδη εικόνα Flat Logo Επίπεδο λογότυπο @@ -1578,6 +1619,8 @@ font-technology Variable Μεταβλητές More Options Περισσότερες επιλογές Show Properties Panel Εμφάνιση πίνακα ιδιοτήτων Hide Corner Widget Απόκρυψη χειριστηρίου γωνιών + Hide Shape Widgets Απόκρυψη χειριστηρίων σχημάτων + Show Shape Widgets Εμφάνιση χειριστηρίων σχημάτων Hide Corner Widget for angles greater than Απόκρυψη χειριστηρίου γωνιών για γωνίες μεγαλύτερες από Hide Edges Απόκρυψη ακμών Hide Gradient Annotator Απόκρυψη χειριστηρίου ντεγκραντέ @@ -1976,6 +2019,7 @@ font-technology Variable Μεταβλητές Pressure Πίεση Tilt Κλίση Bearing Αζιμούθιο + Stylus Wheel Τροχός γραφίδας Shape: Σχήμα: New Brush… Νέο πινέλο… New Brush Νέο πινέλο @@ -1991,6 +2035,9 @@ font-technology Variable Μεταβλητές embedding for preview and print ενσωμάτωση για προεπισκόπηση και εκτύπωση embedding allowed η ενσωμάτωση επιτρέπεται {file}; {embedding} {file}· {embedding} + unknown type άγνωστος τύπος + {type}; {uses} {type}· {uses} +@plural {n} use|{n} uses {n} χρήση|{n} χρήσεις substituted: shown in {family} {style} ({detail}) αντικαταστάθηκε: εμφανίζεται με {family} {style} ({detail}) missing: shown in {family} {style} λείπει: εμφανίζεται με {family} {style} missing λείπει @@ -2201,6 +2248,7 @@ font-technology Variable Μεταβλητές Save As… Αποθήκευση ως… Save for Web (Legacy)… Αποθήκευση για ιστό (παλαιού τύπου)… Save Preset… Αποθήκευση προεπιλογής… + Save Summary… Αποθήκευση σύνοψης… Save Selection… Αποθήκευση επιλογής… Update Selection Ενημέρωση επιλογής Saved Αποθηκεύτηκε @@ -3316,6 +3364,15 @@ theme Appearance Εμφάνιση YakumonoZenkaku YakumonoZenkaku Kinsoku Set Σύνολο Kinsoku Kinsoku Shori Type Τύπος Kinsoku Shori + Kinsoku Shori Settings… Ρυθμίσεις Kinsoku Shori… + Kinsoku Shori Settings Ρυθμίσεις Kinsoku Shori + Kinsoku Sets Σύνολα Kinsoku + Kinsoku Set Base Βάση συνόλου Kinsoku + Based on: Με βάση: + Cannot Start Line Δεν ξεκινά γραμμή + Cannot End Line Δεν τελειώνει γραμμή + Hanging Punctuation Κρεμαστή στίξη + Inseparable Characters Αδιαχώριστοι χαρακτήρες Push In First Πρώτα προς τα μέσα Push Out First Πρώτα προς τα έξω Push Out Only Μόνο προς τα έξω @@ -3579,6 +3636,8 @@ theme Appearance Εμφάνιση Overprint and Transparency Flattener Options Επιλογές υπερεκτύπωσης και ισοπέδωσης διαφάνειας Custom… Προσαρμοσμένο… Custom Transparency Flattener Options Προσαρμοσμένες επιλογές ισοπέδωσης διαφάνειας + The PDF preset keeps the flattener preset but not the Custom… settings. Η προεπιλογή PDF διατηρεί την προεπιλογή ισοπέδωσης, αλλά όχι τις ρυθμίσεις του Προσαρμοσμένο…. + PDF 1.3 files clip rasterized areas to their regions, and Overprint sets whether overprints are kept. Τα αρχεία PDF 1.3 αποκόπτουν τις ραστεροποιημένες περιοχές στα όριά τους και η Υπερεκτύπωση ορίζει αν διατηρούνται οι υπερεκτυπώσεις. EPS has no alpha transparency, and Overprints sets whether overprints are kept. Το EPS δεν έχει διαφάνεια άλφα και οι Υπερεκτυπώσεις ορίζουν αν διατηρούνται οι υπερεκτυπώσεις. Overprint Black… Υπερεκτύπωση μαύρου… Overprint Fill Υπερεκτύπωση γεμίσματος @@ -3974,6 +4033,9 @@ digits Malayalam Μαλαγιάλαμ Rotate View to Selection Περιστροφή προβολής ως προς την επιλογή Reset the rows to the artwork's colors Επαναφορά γραμμών στα χρώματα του σχεδίου Color Theme Picker Επιλογέας χρωματικού θέματος + Undo Changes Αναίρεση αλλαγών + Redo Changes Επανάληψη αλλαγών +@msg Recolor Artwork is not open ο Επαναχρωματισμός σχεδίου δεν είναι ανοιχτός Click or drag across the art to pick its colors; Shift adds more Κάντε κλικ ή σύρετε πάνω στο σχέδιο για να πάρετε τα χρώματά του· το Shift προσθέτει κι άλλα Prominent Colors Κυρίαρχα χρώματα Save All Colors Αποθήκευση όλων των χρωμάτων @@ -4024,6 +4086,7 @@ digits Malayalam Μαλαγιάλαμ A live rectangle's properties show one Corner Radius field for all four corners; off, each corner has its own field. Οι ιδιότητες ενός δυναμικού ορθογωνίου εμφανίζουν ένα πεδίο Ακτίνα γωνίας και για τις τέσσερις γωνίες· όταν είναι ανενεργό, κάθε γωνία έχει δικό της πεδίο. What edits in the Transform panel transform: the object, its pattern tiles or both; Default follows Transform Pattern Tiles. Τι μετασχηματίζουν οι αλλαγές στο πλαίσιο Μετασχηματισμός: το αντικείμενο, τα πλακίδια του μοτίβου του ή και τα δύο· η Προεπιλογή ακολουθεί τον Μετασχηματισμό πλακιδίων μοτίβου. With one symbol instance selected, the Transform panel uses the symbol's registration point as its reference point. Όταν είναι επιλεγμένη μία παρουσία συμβόλου, το πλαίσιο Μετασχηματισμός χρησιμοποιεί το σημείο καταχώρισης του συμβόλου ως σημείο αναφοράς. + Drawing a rectangle, ellipse, polygon, star or line opens the Transform panel if it is closed. Η σχεδίαση ορθογωνίου, έλλειψης, πολυγώνου, αστεριού ή γραμμής ανοίγει το πλαίσιο Μετασχηματισμός, αν είναι κλειστό. Darkens the canvas outside the artboards while the Artboard tool is active. Σκουραίνει τον καμβά έξω από τους πίνακες σχεδίασης όσο είναι ενεργό το εργαλείο Πίνακας σχεδίασης. With Fade Region Outside Artboard on, the area outside the artboards stays dark while you drag with the Artboard tool. Όταν είναι ενεργή η Σκίαση περιοχής εκτός πίνακα σχεδίασης, η περιοχή έξω από τους πίνακες σχεδίασης μένει σκοτεινή όσο σύρετε με το εργαλείο Πίνακας σχεδίασης. How near, in pixels, the pointer must be to an object, anchor or handle for a click to select it. Πόσο κοντά, σε εικονοστοιχεία, πρέπει να είναι ο δείκτης σε αντικείμενο, σημείο αγκύρωσης ή λαβή για να το επιλέξει ένα κλικ. @@ -4366,6 +4429,7 @@ digits Malayalam Μαλαγιάλαμ Show Modified Εμφάνιση τροποποιημένων Show Note Εμφάνιση σημείωσης Show Options Εμφάνιση επιλογών + Show on Shape Creation Εμφάνιση κατά τη δημιουργία σχήματος Show Recent Colors Εμφάνιση πρόσφατων χρωμάτων Toggle RGB Percent Εναλλαγή RGB σε ποσοστό Show Original Path Εμφάνιση αρχικής διαδρομής @@ -4390,6 +4454,7 @@ digits Malayalam Μαλαγιάλαμ Show Thumbnails Εμφάνιση μικρογραφιών Show Tile Edge Εμφάνιση ακμής πλακιδίου Show Tints/Shades Εμφάνιση αποχρώσεων/σκιάσεων + Show Tool Cards Εμφάνιση καρτών εργαλείων Show Tool Tips Εμφάνιση συμβουλών εργαλείων Show Transparency Grid Εμφάνιση πλέγματος διαφάνειας Show Video Rulers Εμφάνιση χαράκων βίντεο @@ -4449,6 +4514,8 @@ digits Malayalam Μαλαγιάλαμ Tracing Result with Outlines Αποτέλεσμα διανυσματοποίησης με περιγράμματα Outlines with Source Image Περιγράμματα με εικόνα πηγής Source Image Εικόνα πηγής + Split View Διαιρεμένη προβολή + Divider Διαχωριστικό Image Trace View Προβολή διανυσματοποίησης εικόνας Snap Options Επιλογές προσκόλλησης Snap to Glyph Προσκόλληση σε γλυφή @@ -4801,6 +4868,8 @@ digits Malayalam Μαλαγιάλαμ Unembedded to {} Καταργήθηκε η ενσωμάτωση στο {} Unembed… Κατάργηση ενσωμάτωσης… Ungroup Color Group Κατάργηση ομαδοποίησης χρωμάτων + Color Group Options Επιλογές ομάδας χρωμάτων + Color Group Options… Επιλογές ομάδας χρωμάτων… Unique Μοναδικό Unite Ένωση Unite and Simplify Ένωση και απλοποίηση @@ -5028,6 +5097,9 @@ digits Malayalam Μαλαγιάλαμ @msg a freeform gradient keeps at least one point το ντεγκραντέ ελεύθερης μορφής χρειάζεται τουλάχιστον ένα σημείο @msg a gradient needs at least two stops το ντεγκραντέ χρειάζεται τουλάχιστον δύο σημεία χρώματος @msg a graphic style named `{to}` already exists υπάρχει ήδη στυλ γραφικών με όνομα `{to}` +@msg a swatch or color group named `{name}` already exists υπάρχει ήδη δείγμα χρώματος ή ομάδα χρωμάτων με όνομα `{name}` +@msg missing `group` λείπει το `group` +@msg no colour group `{group}` δεν υπάρχει ομάδα χρωμάτων `{group}` @msg a key object sits on that point σε αυτό το σημείο βρίσκεται βασικό αντικείμενο @msg a page is missing λείπει μια σελίδα @msg a page out of range η σελίδα βρίσκεται εκτός εύρους @@ -5140,6 +5212,7 @@ digits Malayalam Μαλαγιάλαμ @msg missing `folder` λείπει το `folder` @msg missing `id` (see plugin.list) λείπει το `id` (δείτε plugin.list) @msg missing `name` λείπει το `name` +@msg missing `path` λείπει το `path` @msg missing `tool` λείπει το `tool` @msg missing id λείπει το id @msg missing index λείπει ο δείκτης @@ -5162,6 +5235,11 @@ digits Malayalam Μαλαγιάλαμ @msg no anchor points selected δεν έχουν επιλεγεί σημεία αγκύρωσης @msg `points` must be two or three [x, y] pairs of numbers το `points` πρέπει να είναι δύο ή τρία ζεύγη αριθμών [x, y] @msg direct-select two or three anchor points, or give `points` επιλέξτε άμεσα δύο ή τρία σημεία αγκύρωσης ή δώστε `points` +@msg the path is straight there, so no circle matches its curvature η διαδρομή είναι ευθεία εκεί, οπότε κανένας κύκλος δεν ταιριάζει με την καμπυλότητά της +@msg the path has a cusp there, so it has no single curvature η διαδρομή έχει ακίδα εκεί, οπότε δεν έχει μία μόνο καμπυλότητα +@msg the path has a corner there, so it has no single curvature η διαδρομή έχει γωνία εκεί, οπότε δεν έχει μία μόνο καμπυλότητα +@msg a guide has no curvature circle ένας οδηγός δεν έχει κύκλο καμπυλότητας +@msg the circle that matches the path there would reach past the canvas ο κύκλος που ταιριάζει με τη διαδρομή εκεί θα υπερέβαινε τον καμβά @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 δεν υπάρχει πίνακας σχεδίασης @@ -5415,6 +5493,7 @@ digits Malayalam Μαλαγιάλαμ @msg the PDF is password-protected: give its password το PDF προστατεύεται με κωδικό: πληκτρολογήστε τον κωδικό του @msg the PDF password is wrong ο κωδικός PDF είναι λανθασμένος @msg the Save PDF dialog didn't open δεν άνοιξε το παράθυρο Αποθήκευση PDF +@msg the Save PDF dialog is not open το παράθυρο Αποθήκευση PDF δεν είναι ανοιχτό @msg the WMF header is damaged η κεφαλίδα WMF είναι κατεστραμμένη @msg the art could not be sampled δεν ήταν δυνατή η δειγματοληψία του σχεδίου @msg the art has no bounds το σχέδιο δεν έχει όρια @@ -5638,6 +5717,7 @@ variable-list-end {0}, {1} {0} και {1} @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 +@msg give only one of `index`, `indices` and `t` δώστε μόνο ένα από τα `index`, `indices` και `t` @msg column must be true or a number from 1 το column πρέπει να είναι true ή αριθμός από 1 και πάνω @msg x and y must both be numbers τα x και y πρέπει να είναι αριθμοί @msg "{0}" is not a colour: write it as #rrggbb το "{0}" δεν είναι χρώμα: γράψτε το ως #rrggbb @@ -5799,6 +5879,49 @@ variable-list-end {0}, {1} {0} και {1} @msg the PSD file's layer groups are nested too deeply οι ομάδες επιπέδων του αρχείου PSD είναι ένθετες σε υπερβολικό βάθος @msg a layer of the PSD file is too large to read ένα επίπεδο του αρχείου PSD είναι πολύ μεγάλο για ανάγνωση @msg the PSD file's layers take more memory to read than allowed τα επίπεδα του αρχείου PSD χρειάζονται περισσότερη μνήμη για ανάγνωση από όση επιτρέπεται +@msg the file is no longer loaded το αρχείο δεν είναι πλέον φορτωμένο +@msg the layers can't be read ({e}): the file was placed as its merged image τα επίπεδα δεν μπορούν να διαβαστούν ({e}): το αρχείο τοποθετήθηκε ως η συγχωνευμένη εικόνα του +@msg 1 type layer came in as pixels: the text isn't editable 1 επίπεδο κειμένου εισήχθη ως pixel: το κείμενο δεν είναι επεξεργάσιμο +@msg {n} type layers came in as pixels: the text isn't editable {n} επίπεδα κειμένου εισήχθησαν ως pixel: το κείμενο δεν είναι επεξεργάσιμο +@msg 1 adjustment layer was not applied 1 επίπεδο προσαρμογής δεν εφαρμόστηκε +@msg {n} adjustment layers were not applied {n} επίπεδα προσαρμογής δεν εφαρμόστηκαν +@msg 1 fill layer was not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels) 1 επίπεδο γεμίσματος δεν σχεδιάστηκε (γέμισμα διαβάθμισης ή μοτίβου, χρώμα που δεν μπορεί να διαβαστεί ή σχήμα που δεν αποθηκεύει pixel) +@msg {n} fill layers were not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels) {n} επίπεδα γεμίσματος δεν σχεδιάστηκαν (γέμισμα διαβάθμισης ή μοτίβου, χρώμα που δεν μπορεί να διαβαστεί ή σχήμα που δεν αποθηκεύει pixel) +@msg the layer effects of 1 layer weren't drawn τα εφέ επιπέδου 1 επιπέδου δεν σχεδιάστηκαν +@msg the layer effects of {n} layers weren't drawn τα εφέ επιπέδου {n} επιπέδων δεν σχεδιάστηκαν +@msg the vector masks of 1 layer weren't applied οι διανυσματικές μάσκες 1 επιπέδου δεν εφαρμόστηκαν +@msg the vector masks of {n} layers weren't applied οι διανυσματικές μάσκες {n} επιπέδων δεν εφαρμόστηκαν +@msg the knockout of 1 layer wasn't applied η διάτρηση 1 επιπέδου δεν εφαρμόστηκε +@msg the knockout of {n} layers wasn't applied η διάτρηση {n} επιπέδων δεν εφαρμόστηκε +@msg 1 layer was left out (hidden layers and the layers clipped to them) 1 επίπεδο παραλείφθηκε (κρυφά επίπεδα και τα επίπεδα που αποκόπτονται σε αυτά) +@msg {n} layers were left out (hidden layers and the layers clipped to them) {n} επίπεδα παραλείφθηκαν (κρυφά επίπεδα και τα επίπεδα που αποκόπτονται σε αυτά) +@msg 1 layer clipped to a fill layer that wasn't drawn was left out 1 επίπεδο που αποκόπτεται σε επίπεδο γεμίσματος που δεν σχεδιάστηκε παραλείφθηκε +@msg {n} layers clipped to fill layers that weren't drawn were left out {n} επίπεδα που αποκόπτονται σε επίπεδα γεμίσματος που δεν σχεδιάστηκαν παραλείφθηκαν +@msg layers in blend modes VectorCraft doesn't have ({modes}) were merged with the layers below them τα επίπεδα σε λειτουργίες ανάμειξης που δεν έχει το VectorCraft ({modes}) συγχωνεύτηκαν με τα επίπεδα από κάτω τους +@msg 1 layer in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed 1 επίπεδο σε λειτουργία ανάμειξης που δεν έχει το VectorCraft εισήχθη ως Κανονική: η συγχώνευση χρειάζεται περισσότερη μνήμη από όση επιτρέπεται +@msg {n} layers in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed {n} επίπεδα σε λειτουργίες ανάμειξης που δεν έχει το VectorCraft εισήχθησαν ως Κανονική: η συγχώνευση χρειάζεται περισσότερη μνήμη από όση επιτρέπεται +@msg 1 layer clipped to the layer below came in unclipped: the merge needs more memory than allowed 1 επίπεδο που αποκόπτεται στο επίπεδο από κάτω εισήχθη χωρίς αποκοπή: η συγχώνευση χρειάζεται περισσότερη μνήμη από όση επιτρέπεται +@msg {n} layers clipped to the layer below came in unclipped: the merge needs more memory than allowed {n} επίπεδα που αποκόπτονται στο επίπεδο από κάτω εισήχθησαν χωρίς αποκοπή: η συγχώνευση χρειάζεται περισσότερη μνήμη από όση επιτρέπεται +@msg hiddenLayers applies to a PSD file placed with layers: true το hiddenLayers ισχύει για αρχείο PSD που τοποθετείται με layers: true +@msg importSlices: a linked PSD file is placed as its flat image; give link: false to embed it with its slices importSlices: ένα συνδεδεμένο αρχείο PSD τοποθετείται ως η επίπεδη εικόνα του· δώστε link: false για να ενσωματωθεί με τις τομές του +@msg layers: a linked PSD file is placed as its flat image; leave link out or give link: false layers: ένα συνδεδεμένο αρχείο PSD τοποθετείται ως η επίπεδη εικόνα του· παραλείψτε το link ή δώστε link: false +@msg the slices can't be read ({e}) and were left out οι τομές δεν μπορούν να διαβαστούν ({e}) και παραλείφθηκαν +@msg 1 slice lies outside the canvas or has no size and was left out 1 τομή βρίσκεται έξω από τον καμβά ή δεν έχει μέγεθος και παραλείφθηκε +@msg {n} slices lie outside the canvas or have no size and were left out {n} τομές βρίσκονται έξω από τον καμβά ή δεν έχουν μέγεθος και παραλείφθηκαν +@msg 1 slice would lie outside the canvas and was left out 1 τομή θα βρισκόταν έξω από τον καμβά και παραλείφθηκε +@msg {n} slices would lie outside the canvas and were left out {n} τομές θα βρίσκονταν έξω από τον καμβά και παραλείφθηκαν +@msg the slices' descriptor holds too many values ο περιγραφέας των τομών περιέχει πάρα πολλές τιμές +@msg the slices' descriptor has a version other than 16 ο περιγραφέας των τομών έχει έκδοση διαφορετική από 16 +@msg the slices are stored in version {v}, which isn't read οι τομές είναι αποθηκευμένες στην έκδοση {v}, η οποία δεν διαβάζεται +@msg the file has {count} slices, more than the {MAX_SLICES} read το αρχείο έχει {count} τομές, περισσότερες από τις {MAX_SLICES} που διαβάζονται +@msg the slices' descriptor has no list of slices ο περιγραφέας των τομών δεν έχει λίστα τομών +@msg the slices' descriptor lists something other than a slice ο περιγραφέας των τομών απαριθμεί κάτι άλλο από τομή +@msg a slice in the slices' descriptor has no bounds μια τομή στον περιγραφέα των τομών δεν έχει όρια +@msg a slice's bounds in the slices' descriptor aren't numbers τα όρια μιας τομής στον περιγραφέα των τομών δεν είναι αριθμοί +@msg a text in the slices has more than the {MAX_TEXT} characters read ένα κείμενο στις τομές έχει περισσότερους από τους {MAX_TEXT} χαρακτήρες που διαβάζονται +@msg the slices' descriptor nests too deep ο περιγραφέας των τομών είναι εμφωλευμένος πολύ βαθιά +@msg the slices' descriptor has a reference of an unknown kind ({_1}) ο περιγραφέας των τομών έχει αναφορά άγνωστου είδους ({_1}) +@msg the slices' descriptor has a value of an unknown type ({_1}) ο περιγραφέας των τομών έχει τιμή άγνωστου τύπου ({_1}) @msg the layers can't be read ({e}): the file opened as its merged image τα επίπεδα δεν μπορούν να διαβαστούν ({e}): το αρχείο άνοιξε ως η συγχωνευμένη εικόνα του @msg {depth}-bit PSD files in this colour mode can't be read τα αρχεία PSD {depth} bit δεν διαβάζονται σε αυτήν τη λειτουργία χρώματος @msg the PSD file is cut short το αρχείο PSD είναι περικομμένο @@ -5817,6 +5940,25 @@ variable-list-end {0}, {1} {0} και {1} Preserve Embedded Profiles Διατήρηση ενσωματωμένων προφίλ Convert to Working Space Μετατροπή στον χώρο εργασίας Preserve Numbers Διατήρηση αριθμών + Profile Mismatches: Αναντιστοιχίες προφίλ: + Ask When Opening Ερώτηση κατά το άνοιγμα + Ask When Pasting Ερώτηση κατά την επικόλληση + Missing Profiles: Προφίλ που λείπουν: + Embedded Profile Mismatch Αναντιστοιχία ενσωματωμένου προφίλ + Missing Profile Λείπει προφίλ + Paste Profile Mismatch Αναντιστοιχία προφίλ κατά την επικόλληση + “{name}” is not tagged with a {model} profile. Το «{name}» δεν έχει προφίλ {model}. + “{name}” is tagged with the {model} profile “{profile}”, which is not the {model} working space “{working}”. Το «{name}» έχει το προφίλ {model} «{profile}», που δεν είναι ο χώρος εργασίας {model} «{working}». + Use the embedded profile Χρήση του ενσωματωμένου προφίλ + Convert the colors to the working space Μετατροπή των χρωμάτων στον χώρο εργασίας + Discard the embedded profile Απόρριψη του ενσωματωμένου προφίλ + Leave as is Διατήρηση ως έχει + Assign the working space Αντιστοίχιση του χώρου εργασίας + Assign profile: Αντιστοίχιση προφίλ: + Preserve the color numbers Διατήρηση των αριθμών των χρωμάτων + Convert to keep the colors' appearance Μετατροπή με διατήρηση της εμφάνισης των χρωμάτων +@msg `{path}` goes with `{key}`: "assign" only το `{path}` συνδυάζεται μόνο με `{key}`: "assign" + The pasted colors come from a document whose {model} profile is “{from}”; this document's is “{to}”. Τα χρώματα που επικολλήθηκαν προέρχονται από έγγραφο με προφίλ {model} «{from}»· το προφίλ αυτού του εγγράφου είναι «{to}». System Title Bar Γραμμή τίτλου συστήματος VectorCraft Title Bar on Every Desktop Γραμμή τίτλου του VectorCraft σε κάθε επιφάνεια εργασίας The VECTORCRAFT_TITLEBAR environment variable chooses the title bar while it is set. Όσο είναι ορισμένη, η μεταβλητή περιβάλλοντος VECTORCRAFT_TITLEBAR επιλέγει τη γραμμή τίτλου. @@ -8116,6 +8258,8 @@ breakText Glyphs Γλύφοι # Path Precision Tools add-on: Tangent Circle. Tangent Circle… Εφαπτόμενος κύκλος… Tangent Circle Εφαπτόμενος κύκλος + Tangent Circle Tool Εφαπτόμενος κύκλος (Tangent Circle Tool) + No tangent circle here Δεν υπάρχει εφαπτόμενος κύκλος εδώ Circle: Κύκλος: @msg `ids` names an object twice το `ids` αναφέρει ένα αντικείμενο δύο φορές @msg select two or three paths or compound paths επιλέξτε δύο ή τρεις διαδρομές ή σύνθετες διαδρομές @@ -8131,6 +8275,16 @@ breakText Glyphs Γλύφοι @msg `circle` is past the last circle found ({found}) το `circle` είναι μετά τον τελευταίο κύκλο που βρέθηκε ({found}) @msg object {value} is not a path or compound path το αντικείμενο {value} δεν είναι διαδρομή ή σύνθετη διαδρομή @msg these shapes are too small to measure αυτά τα σχήματα είναι πολύ μικρά για να μετρηθούν +# Path Precision Tools add-on: Add Bounding Rectangle and Add Bounding Circle. + Add Bounding Rectangle Προσθήκη ορθογωνίου οριοθέτησης + Add Bounding Circle Προσθήκη κύκλου οριοθέτησης + Add Bounding Rectangle… Προσθήκη ορθογωνίου οριοθέτησης… + Add Bounding Circle… Προσθήκη κύκλου οριοθέτησης… + One per Object Ένα ανά αντικείμενο +@msg nothing to enclose δεν υπάρχει τίποτα για περίκλειση +@msg `offset` must be 0 or more το `offset` πρέπει να είναι 0 ή μεγαλύτερο +@msg the shape would have no size το σχήμα δεν θα είχε μέγεθος +@msg the shape would reach past the edge of the canvas το σχήμα θα ξεπερνούσε την άκρη του καμβά # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Εργαλεία εγγράφου Save a Timestamped Copy Αποθήκευση αντιγράφου με ημερομηνία και ώρα @@ -8617,6 +8771,50 @@ breakText Glyphs Γλύφοι @msg A joint does not close by {gap} pt. Μια ένωση δεν κλείνει κατά {gap} pt. @msg Two panels pass through each other. Δύο πάνελ διαπερνούν το ένα το άλλο. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" το composer πρέπει να είναι "singleLine", "everyLine", "standardSingleLine" ή "standardEveryLine" + Fine Stipple Λεπτή στιγμογραφία + Dense Stipple Πυκνή στιγμογραφία + Soft Stipple Απαλή στιγμογραφία + Bold Stipple Έντονη στιγμογραφία + Paper Cutouts Χάρτινα αποκόμματα + Coral Layers Στρώσεις κοραλλί + Mint Layers Στρώσεις μέντας + Midnight Layers Στρώσεις μεσονυκτίου + Sunflower Sheet Φύλλο ηλιοτρόπιου + Rose Layers Στρώσεις ροζ + Monochrome Stack Μονόχρωμη στοίβα +# Tool cards (General › Show Tool Cards): one sentence on what each tool does. + Shows a card with what a toolbar tool does and what its keys do instead of its tip; it needs Show Tool Tips. Εμφανίζει μια κάρτα με το τι κάνει ένα εργαλείο της γραμμής και τα πλήκτρα του, αντί για τη συμβουλή του· απαιτεί την Εμφάνιση συμβουλών εργαλείων. + Selects whole objects and groups to move, resize or rotate them. Επιλέγει ολόκληρα αντικείμενα και ομάδες για μετακίνηση, αλλαγή μεγέθους ή περιστροφή. + Selects anchor points and path segments to reshape a path. Επιλέγει σημεία αγκύρωσης και τμήματα διαδρομής για αλλαγή του σχήματος μιας διαδρομής. + Draws paths point by point, with straight segments and smooth curves. Σχεδιάζει διαδρομές σημείο προς σημείο, με ευθύγραμμα τμήματα και ομαλές καμπύλες. + Draws smooth curves through the points you click. Σχεδιάζει ομαλές καμπύλες που περνούν από τα σημεία που κάνετε κλικ. + Adds text at a point, or in a frame you drag. Προσθέτει κείμενο σε ένα σημείο ή σε ένα πλαίσιο που σύρετε. + Draws rectangles and squares. Σχεδιάζει ορθογώνια και τετράγωνα. + Draws rectangles with rounded corners. Σχεδιάζει ορθογώνια με στρογγυλεμένες γωνίες. + Draws ellipses and circles. Σχεδιάζει ελλείψεις και κύκλους. + Draws polygons with sides of equal length. Σχεδιάζει πολύγωνα με πλευρές ίσου μήκους. + Draws stars. Σχεδιάζει αστέρια. + Turns objects around a reference point. Περιστρέφει αντικείμενα γύρω από ένα σημείο αναφοράς. + Flips objects across an axis through a reference point. Αντικατοπτρίζει αντικείμενα ως προς έναν άξονα που περνά από ένα σημείο αναφοράς. + Resizes objects from a reference point. Αλλάζει το μέγεθος αντικειμένων από ένα σημείο αναφοράς. + Slants objects from a reference point. Πλαγιάζει αντικείμενα από ένα σημείο αναφοράς. + Moves the view of the document. Μετακινεί την προβολή του εγγράφου. + Magnifies or reduces the view. Μεγεθύνει ή σμικρύνει την προβολή. + Copies the color and other attributes of one object to the selection. Αντιγράφει το χρώμα και άλλα χαρακτηριστικά ενός αντικειμένου στην επιλογή. + Sets the direction and length of a gradient. Ορίζει την κατεύθυνση και το μήκος ενός ντεγκραντέ. + Creates, selects and resizes artboards. Δημιουργεί, επιλέγει και αλλάζει το μέγεθος πινάκων σχεδίασης. + Changes the width of a stroke along its length. Αλλάζει το πλάτος ενός περιγράμματος κατά μήκος του. + Bends art by dragging pins placed on it. Λυγίζει το σχέδιο σύροντας καρφίτσες τοποθετημένες πάνω του. + Pushes the outlines of paths in the direction you drag. Σπρώχνει τα σχήματα των διαδρομών προς την κατεύθυνση που σύρετε. + Twists the outlines of paths into swirls. Συστρέφει τα σχήματα των διαδρομών σε δίνες. + Pulls the outlines of paths in toward the brush. Τραβά τα σχήματα των διαδρομών προς το πινέλο. + Pushes the outlines of paths out from the brush. Σπρώχνει τα σχήματα των διαδρομών προς τα έξω από το πινέλο. + Adds curved details along the outlines of paths. Προσθέτει καμπύλες λεπτομέρειες κατά μήκος των σχημάτων των διαδρομών. + Adds spiky details along the outlines of paths. Προσθέτει αιχμηρές λεπτομέρειες κατά μήκος των σχημάτων των διαδρομών. + Adds wrinkles along the outlines of paths. Προσθέτει ζάρες κατά μήκος των σχημάτων των διαδρομών. + Moves, copies and resizes objects on the perspective grid. Μετακινεί, αντιγράφει και αλλάζει το μέγεθος αντικειμένων στο πλέγμα προοπτικής. + Makes a series of steps between two or more objects. Δημιουργεί μια σειρά βημάτων ανάμεσα σε δύο ή περισσότερα αντικείμενα. + Places dimension lines that show measured lengths. Τοποθετεί γραμμές διαστάσεων που δείχνουν μετρημένα μήκη. Tap Σύντομο πάτημα Clear Hold Εκκαθάριση παρατεταμένου πατήματος Hold Shortcuts Συντομεύσεις παρατεταμένου πατήματος @@ -8635,3 +8833,7 @@ breakText Glyphs Γλύφοι Round Flow Στρογγυλή ροή Chisel Flow Λοξή ροή @msg text.{key} `{v}`: use "{_1}" or "{_2}" text.{key} `{v}`: χρησιμοποιήστε "{_1}" ή "{_2}" + +# #5804 native-picked raster editor (draft translations; native review welcome). + Edit Original with: Επεξεργασία πρωτοτύπου με: +file-filter Applications Εφαρμογές diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 1817148cff..549d75e4d4 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -498,6 +498,9 @@ font-technology Variable Variables Choose… Elegir… Circle Círculo Circle Tool Herramienta Círculo + Curvature Circle Tool Herramienta Círculo de curvatura + Cusp Cúspide + Straight segment Segmento recto Circle too large Círculo demasiado grande Classic Defaults Valores predeterminados clásicos Clean Up… Limpiar… @@ -605,6 +608,9 @@ font-technology Variable Variables Box Channel Canal del cuadro Color box Cuadro de color Color Wheel Options Opciones de la rueda de color + Show Harmony Mostrar armonía + Harmony Rule Regla de armonía + Harmony color Color de la armonía Color Type: Tipo de color: Color: Color: Colorize Colorear @@ -1030,10 +1036,25 @@ font-technology Variable Variables Duplicate Symbol Duplicar símbolo Duplicate {kind} Style Duplicar estilo de {kind} Dutch Neerlandés + PSD Import Options Opciones de importación PSD + Place PSD Colocar PSD + Convert Layers to Objects Convertir capas en objetos + Import Hidden Layers Importar capas ocultas + Flatten Layers to a Single Image Acoplar capas en una sola imagen + Import Slices Importar sectores DXF Import Options Opciones de importación DXF DXF Info Información DXF DXF Options Opciones DXF DXF Options Dialog Cuadro de diálogo Opciones DXF + HP-GL Options Opciones HP-GL + HP-GL Options Dialog Cuadro de diálogo Opciones HP-GL + Curve Tolerance: Tolerancia de las curvas: + Origin: Origen: + Pens: Plumas: + One Pen per Color Una pluma por color + Pen Table Tabla de plumas + Draw the Nearest Path Next Dibujar a continuación el trazado más cercano + Draw Inner Paths First Dibujar primero los trazados interiores e.g. 1-3, 5 p. ej. 1-3, 5 Each page prints as one image, at the document's raster effects resolution. Cada página se imprime como una imagen, con la resolución de efectos de rasterización del documento. Earth Tones Tonos tierra @@ -1270,6 +1291,15 @@ font-technology Variable Variables Shading Color Color de sombreado Black Overprint Negro sobreimpreso Draw Hidden Faces Dibujar caras ocultas + Map Art… Asignar ilustración… + Map Art Asignar ilustración + First Surface Primera superficie + Previous Surface Superficie anterior + Next Surface Superficie siguiente + Last Surface Última superficie + Scale to Fit Escalar para encajar + Shade Artwork Sombrear ilustración + Invisible Geometry Geometría invisible Eyedropper Cuentagotas Sample Color from Screen Tomar color de la pantalla This system has no screen color sampler Este sistema no tiene muestreador de color de la pantalla @@ -1399,6 +1429,17 @@ font-technology Variable Variables Largest: Más grande: Direction: Dirección: Symbolism Tools Options Opciones de las herramientas de símbolos + Tool: Herramienta: + Symbol Set Density Densidad del conjunto de símbolos + Symbol Sprayer Options Opciones del rociador de símbolos + Scrunch: Concentración: + Spin: Giro: + Screen: Transparencia: + Stain: Tinte: + Symbol Sizer Options Opciones de tamaño de símbolos + Proportional Resizing Cambio de tamaño proporcional + Resizing Affects Density El cambio de tamaño afecta a la densidad + Show Brush Size and Intensity Mostrar tamaño e intensidad del pincel Symbol Set Density: Densidad del conjunto de símbolos: Flat Image Imagen acoplada Flat Logo Logotipo plano @@ -1668,6 +1709,8 @@ font-technology Variable Variables More Options Más opciones Show Properties Panel Mostrar panel Propiedades Hide Corner Widget Ocultar widget de esquina + Hide Shape Widgets Ocultar widgets de forma + Show Shape Widgets Mostrar widgets de forma Hide Corner Widget for angles greater than Ocultar widget de esquina para ángulos mayores que Hide Edges Ocultar bordes Hide Gradient Annotator Ocultar anotador de degradado @@ -2223,6 +2266,15 @@ font-technology Variable Variables YakumonoZenkaku YakumonoZenkaku Kinsoku Set Conjunto de kinsoku Kinsoku Shori Type Tipo de kinsoku shori + Kinsoku Shori Settings… Configuración de kinsoku shori… + Kinsoku Shori Settings Configuración de kinsoku shori + Kinsoku Sets Conjuntos de kinsoku + Kinsoku Set Base Base del conjunto de kinsoku + Based on: Basado en: + Cannot Start Line No puede iniciar línea + Cannot End Line No puede terminar línea + Hanging Punctuation Puntuación colgante + Inseparable Characters Caracteres inseparables Push In First Primero hacia dentro Push Out First Primero hacia fuera Push Out Only Solo hacia fuera @@ -2341,6 +2393,7 @@ font-technology Variable Variables Pressure Presión Tilt Inclinación Bearing Orientación + Stylus Wheel Rueda del lápiz Shape: Forma: Bristle Length: Longitud de cerdas: Bristle Density: Densidad de cerdas: @@ -2371,6 +2424,9 @@ font-technology Variable Variables embedding for preview and print incrustación para vista previa e impresión embedding allowed incrustación permitida {file}; {embedding} {file}; {embedding} + unknown type tipo desconocido + {type}; {uses} {type}; {uses} +@plural {n} use|{n} uses {n} uso|{n} usos substituted: shown in {family} {style} ({detail}) sustituida: se muestra con {family} {style} ({detail}) missing: shown in {family} {style} falta: se muestra con {family} {style} missing falta @@ -2643,6 +2699,8 @@ font-technology Variable Variables Overprint and Transparency Flattener Options Opciones de sobreimpresión y acoplador de transparencia Custom… Personalizado… Custom Transparency Flattener Options Opciones personalizadas de acoplador de transparencia + The PDF preset keeps the flattener preset but not the Custom… settings. El preajuste PDF conserva el preajuste de acoplamiento, pero no los ajustes de Personalizado…. + PDF 1.3 files clip rasterized areas to their regions, and Overprint sets whether overprints are kept. Los archivos PDF 1.3 recortan las áreas rasterizadas a sus regiones, y Sobreimprimir determina si se conservan las sobreimpresiones. EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS no tiene transparencia alfa, y Sobreimpresiones determina si se conservan las sobreimpresiones. Overprint Black… Sobreimprimir negro… Overprint Fill Sobreimprimir relleno @@ -3156,6 +3214,9 @@ digits Malayalam Malayálam Rotate View to Selection Rotar vista según la selección Reset the rows to the artwork's colors Restablecer las filas a los colores de la ilustración Color Theme Picker Selector de tema de color + Undo Changes Deshacer cambios + Redo Changes Rehacer cambios +@msg Recolor Artwork is not open Volver a colorear ilustración no está abierto Click or drag across the art to pick its colors; Shift adds more Haga clic o arrastre sobre la ilustración para tomar sus colores; Mayús añade más Prominent Colors Colores destacados Save All Colors Guardar todos los colores @@ -3210,6 +3271,7 @@ digits Malayalam Malayálam A live rectangle's properties show one Corner Radius field for all four corners; off, each corner has its own field. Las propiedades de un rectángulo dinámico muestran un solo campo Radio de esquina para las cuatro esquinas; desactivada, cada esquina tiene su propio campo. What edits in the Transform panel transform: the object, its pattern tiles or both; Default follows Transform Pattern Tiles. Lo que transforman los cambios del panel Transformar: el objeto, sus mosaicos de motivo o ambos; Predeterminado sigue a Transformar mosaicos de motivo. With one symbol instance selected, the Transform panel uses the symbol's registration point as its reference point. Con una instancia de símbolo seleccionada, el panel Transformar usa el punto de registro del símbolo como punto de referencia. + Drawing a rectangle, ellipse, polygon, star or line opens the Transform panel if it is closed. Al dibujar un rectángulo, una elipse, un polígono, una estrella o una línea, se abre el panel Transformar si está cerrado. Darkens the canvas outside the artboards while the Artboard tool is active. Oscurece el lienzo fuera de las mesas de trabajo mientras la herramienta Mesa de trabajo está activa. With Fade Region Outside Artboard on, the area outside the artboards stays dark while you drag with the Artboard tool. Con Atenuar región fuera de la mesa de trabajo activado, el área fuera de las mesas de trabajo sigue oscura mientras arrastra con la herramienta Mesa de trabajo. How near, in pixels, the pointer must be to an object, anchor or handle for a click to select it. Qué tan cerca, en píxeles, debe estar el puntero de un objeto, ancla o manejador para que un clic lo seleccione. @@ -3389,6 +3451,7 @@ digits Malayalam Malayálam Save Preset Guardar preajuste Save Document Preset Guardar preajuste de documento Save Preset… Guardar preajuste… + Save Summary… Guardar resumen… Save Print Preset Guardar preajuste de impresión Save Recovery Data Guardar datos de recuperación Save Save for Web Preset Guardar preajuste de Guardar para web @@ -3694,6 +3757,7 @@ digits Malayalam Malayálam Show Modified Mostrar modificados Show Note Mostrar nota Show Options Mostrar opciones + Show on Shape Creation Mostrar al crear formas Show Recent Colors Mostrar colores recientes Toggle RGB Percent Alternar RGB en porcentaje Show Original Path Mostrar trazado original @@ -3721,6 +3785,7 @@ digits Malayalam Malayálam Show Thumbnails Mostrar miniaturas Show Tile Edge Mostrar borde de mosaico Show Tints/Shades Mostrar matices/sombras + Show Tool Cards Mostrar fichas de herramientas Show Tool Tips Mostrar información sobre herramientas Show Transparency Grid Mostrar cuadrícula de transparencia Show Video Rulers Mostrar reglas de video @@ -3804,6 +3869,8 @@ digits Malayalam Malayálam Outlines Contornos Outlines with Source Image Contornos con imagen de origen Source Image Imagen de origen + Split View Vista dividida + Divider Divisor Press and hold to view the source image Mantén pulsado para ver la imagen de origen Image Trace View Vista del calco de imagen Snap Options Opciones de ajuste @@ -4258,6 +4325,8 @@ digits Malayalam Malayálam Unembed… Desincrustar… Ungroup Desagrupar Ungroup Color Group Desagrupar grupo de colores + Color Group Options Opciones de grupo de colores + Color Group Options… Opciones de grupo de colores… Unicode Unicode Unicode (UTF-16) Unicode (UTF-16) Unicode (UTF-8) Unicode (UTF-8) @@ -5076,6 +5145,7 @@ liquify-list-end {0}, {1} {0}, {1} @msg a freeform gradient keeps at least one point un degradado de forma libre conserva al menos un punto @msg a gradient needs at least two stops un degradado necesita al menos dos paradas @msg a graphic style named `{to}` already exists ya existe un estilo gráfico llamado `{to}` +@msg a swatch or color group named `{name}` already exists ya existe una muestra o un grupo de colores llamado `{name}` @msg a key object sits on that point hay un objeto clave en ese punto @msg a page is missing falta una página @msg a page out of range una página fuera de rango @@ -5217,6 +5287,11 @@ liquify-list-end {0}, {1} {0}, {1} @msg no anchor points selected no hay puntos de ancla seleccionados @msg `points` must be two or three [x, y] pairs of numbers `points` debe ser dos o tres pares de números [x, y] @msg direct-select two or three anchor points, or give `points` seleccione directamente dos o tres puntos de ancla o indique `points` +@msg the path is straight there, so no circle matches its curvature el trazado es recto en ese punto, así que ningún círculo coincide con su curvatura +@msg the path has a cusp there, so it has no single curvature el trazado tiene una cúspide en ese punto, así que no tiene una curvatura única +@msg the path has a corner there, so it has no single curvature el trazado tiene un vértice en ese punto, así que no tiene una curvatura única +@msg a guide has no curvature circle una guía no tiene círculo de curvatura +@msg the circle that matches the path there would reach past the canvas el círculo que coincide con el trazado en ese punto excedería el lienzo @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 @@ -5477,6 +5552,7 @@ liquify-list-end {0}, {1} {0}, {1} @msg the PDF is password-protected: give its password el PDF está protegido con contraseña: indica su contraseña @msg the PDF password is wrong la contraseña del PDF es incorrecta @msg the Save PDF dialog didn't open el cuadro de diálogo Guardar PDF no se abrió +@msg the Save PDF dialog is not open el cuadro de diálogo Guardar PDF no está abierto @msg the WMF header is damaged el encabezado WMF está dañado @msg the art could not be sampled no se pudo muestrear la ilustración @msg the art has no bounds la ilustración no tiene límites @@ -5700,6 +5776,7 @@ variable-list-end {0}, {1} {0} y {1} @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 +@msg give only one of `index`, `indices` and `t` indica solo uno de `index`, `indices` y `t` @msg column must be true or a number from 1 column debe ser true o un número desde 1 @msg x and y must both be numbers x e y deben ser números @msg "{0}" is not a colour: write it as #rrggbb "{0}" no es un color: escríbelo como #rrggbb @@ -5843,6 +5920,49 @@ variable-list-end {0}, {1} {0} y {1} @msg the PSD file's layer groups are nested too deeply los grupos de capas del archivo PSD están anidados a demasiada profundidad @msg a layer of the PSD file is too large to read una capa del archivo PSD es demasiado grande para leerla @msg the PSD file's layers take more memory to read than allowed las capas del archivo PSD necesitan más memoria de la permitida para leerlas +@msg the file is no longer loaded el archivo ya no está cargado +@msg the layers can't be read ({e}): the file was placed as its merged image no se pueden leer las capas ({e}): el archivo se colocó como su imagen combinada +@msg 1 type layer came in as pixels: the text isn't editable 1 capa de texto se importó como píxeles: el texto no es editable +@msg {n} type layers came in as pixels: the text isn't editable {n} capas de texto se importaron como píxeles: el texto no es editable +@msg 1 adjustment layer was not applied 1 capa de ajuste no se aplicó +@msg {n} adjustment layers were not applied {n} capas de ajuste no se aplicaron +@msg 1 fill layer was not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels) 1 capa de relleno no se dibujó (un relleno de degradado o de motivo, un color que no se puede leer o una forma que no guarda píxeles) +@msg {n} fill layers were not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels) {n} capas de relleno no se dibujaron (un relleno de degradado o de motivo, un color que no se puede leer o una forma que no guarda píxeles) +@msg the layer effects of 1 layer weren't drawn los efectos de capa de 1 capa no se dibujaron +@msg the layer effects of {n} layers weren't drawn los efectos de capa de {n} capas no se dibujaron +@msg the vector masks of 1 layer weren't applied las máscaras vectoriales de 1 capa no se aplicaron +@msg the vector masks of {n} layers weren't applied las máscaras vectoriales de {n} capas no se aplicaron +@msg the knockout of 1 layer wasn't applied el vaciado de 1 capa no se aplicó +@msg the knockout of {n} layers wasn't applied el vaciado de {n} capas no se aplicó +@msg 1 layer was left out (hidden layers and the layers clipped to them) 1 capa se omitió (capas ocultas y las capas recortadas a ellas) +@msg {n} layers were left out (hidden layers and the layers clipped to them) {n} capas se omitieron (capas ocultas y las capas recortadas a ellas) +@msg 1 layer clipped to a fill layer that wasn't drawn was left out 1 capa recortada a una capa de relleno que no se dibujó se omitió +@msg {n} layers clipped to fill layers that weren't drawn were left out {n} capas recortadas a capas de relleno que no se dibujaron se omitieron +@msg layers in blend modes VectorCraft doesn't have ({modes}) were merged with the layers below them las capas en modos de fusión que VectorCraft no tiene ({modes}) se combinaron con las capas de debajo +@msg 1 layer in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed 1 capa en un modo de fusión que VectorCraft no tiene se importó como Normal: la combinación necesita más memoria de la permitida +@msg {n} layers in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed {n} capas en modos de fusión que VectorCraft no tiene se importaron como Normal: la combinación necesita más memoria de la permitida +@msg 1 layer clipped to the layer below came in unclipped: the merge needs more memory than allowed 1 capa recortada a la capa de debajo se importó sin recortar: la combinación necesita más memoria de la permitida +@msg {n} layers clipped to the layer below came in unclipped: the merge needs more memory than allowed {n} capas recortadas a la capa de debajo se importaron sin recortar: la combinación necesita más memoria de la permitida +@msg hiddenLayers applies to a PSD file placed with layers: true hiddenLayers se aplica a un archivo PSD colocado con layers: true +@msg importSlices: a linked PSD file is placed as its flat image; give link: false to embed it with its slices importSlices: un archivo PSD vinculado se coloca como su imagen acoplada; indique link: false para incrustarlo con sus sectores +@msg layers: a linked PSD file is placed as its flat image; leave link out or give link: false layers: un archivo PSD vinculado se coloca como su imagen acoplada; omita link o indique link: false +@msg the slices can't be read ({e}) and were left out no se pueden leer los sectores ({e}) y se omitieron +@msg 1 slice lies outside the canvas or has no size and was left out 1 sector está fuera del lienzo o no tiene tamaño y se omitió +@msg {n} slices lie outside the canvas or have no size and were left out {n} sectores están fuera del lienzo o no tienen tamaño y se omitieron +@msg 1 slice would lie outside the canvas and was left out 1 sector quedaría fuera del lienzo y se omitió +@msg {n} slices would lie outside the canvas and were left out {n} sectores quedarían fuera del lienzo y se omitieron +@msg the slices' descriptor holds too many values el descriptor de los sectores contiene demasiados valores +@msg the slices' descriptor has a version other than 16 el descriptor de los sectores tiene una versión distinta de 16 +@msg the slices are stored in version {v}, which isn't read los sectores están guardados en la versión {v}, que no se lee +@msg the file has {count} slices, more than the {MAX_SLICES} read el archivo tiene {count} sectores, más que los {MAX_SLICES} que se leen +@msg the slices' descriptor has no list of slices el descriptor de los sectores no tiene una lista de sectores +@msg the slices' descriptor lists something other than a slice el descriptor de los sectores enumera algo que no es un sector +@msg a slice in the slices' descriptor has no bounds un sector del descriptor de los sectores no tiene límites +@msg a slice's bounds in the slices' descriptor aren't numbers los límites de un sector del descriptor de los sectores no son números +@msg a text in the slices has more than the {MAX_TEXT} characters read un texto de los sectores tiene más de los {MAX_TEXT} caracteres que se leen +@msg the slices' descriptor nests too deep el descriptor de los sectores está anidado a demasiada profundidad +@msg the slices' descriptor has a reference of an unknown kind ({_1}) el descriptor de los sectores tiene una referencia de un tipo desconocido ({_1}) +@msg the slices' descriptor has a value of an unknown type ({_1}) el descriptor de los sectores tiene un valor de un tipo desconocido ({_1}) @msg the layers can't be read ({e}): the file opened as its merged image no se pueden leer las capas ({e}): el archivo se abrió como su imagen combinada @msg {depth}-bit PSD files in this colour mode can't be read los archivos PSD de {depth} bits en este modo de color no se pueden leer @msg the PSD file is cut short el archivo PSD está incompleto @@ -5870,6 +5990,25 @@ variable-list-end {0}, {1} {0} y {1} Preserve Embedded Profiles Conservar perfiles incrustados Convert to Working Space Convertir en espacio de trabajo Preserve Numbers Conservar números + Profile Mismatches: Discrepancias de perfil: + Ask When Opening Preguntar al abrir + Ask When Pasting Preguntar al pegar + Missing Profiles: Perfiles que faltan: + Embedded Profile Mismatch Discrepancia del perfil incrustado + Missing Profile Falta el perfil + Paste Profile Mismatch Discrepancia de perfil al pegar + “{name}” is not tagged with a {model} profile. “{name}” no tiene un perfil {model}. + “{name}” is tagged with the {model} profile “{profile}”, which is not the {model} working space “{working}”. “{name}” tiene el perfil {model} “{profile}”, que no es el espacio de trabajo {model} “{working}”. + Use the embedded profile Usar el perfil incrustado + Convert the colors to the working space Convertir los colores al espacio de trabajo + Discard the embedded profile Descartar el perfil incrustado + Leave as is Dejar como está + Assign the working space Asignar el espacio de trabajo + Assign profile: Asignar perfil: + Preserve the color numbers Conservar los valores de color + Convert to keep the colors' appearance Convertir para conservar el aspecto de los colores +@msg `{path}` goes with `{key}`: "assign" only `{path}` solo va con `{key}`: "assign" + The pasted colors come from a document whose {model} profile is “{from}”; this document's is “{to}”. Los colores pegados provienen de un documento con el perfil {model} “{from}”; el de este documento es “{to}”. Texture Textura Craquelure… Craquelado… Grain… Granulado… @@ -8104,6 +8243,8 @@ breakText Glyphs Glifos # Path Precision Tools add-on: Tangent Circle. Tangent Circle… Círculo tangente… Tangent Circle Círculo tangente + Tangent Circle Tool Herramienta Círculo tangente + No tangent circle here No hay círculo tangente aquí Circle: Círculo: @msg `ids` names an object twice `ids` indica un objeto dos veces @msg select two or three paths or compound paths seleccione dos o tres trazados o trazados compuestos @@ -8119,6 +8260,16 @@ breakText Glyphs Glifos @msg `circle` is past the last circle found ({found}) `circle` pasa del último círculo encontrado ({found}) @msg object {value} is not a path or compound path el objeto {value} no es un trazado ni un trazado compuesto @msg these shapes are too small to measure estas formas son demasiado pequeñas para medirlas +# Path Precision Tools add-on: Add Bounding Rectangle and Add Bounding Circle. + Add Bounding Rectangle Agregar rectángulo delimitador + Add Bounding Circle Agregar círculo delimitador + Add Bounding Rectangle… Agregar rectángulo delimitador… + Add Bounding Circle… Agregar círculo delimitador… + One per Object Uno por objeto +@msg nothing to enclose no hay nada que rodear +@msg `offset` must be 0 or more `offset` debe ser 0 o más +@msg the shape would have no size la forma no tendría tamaño +@msg the shape would reach past the edge of the canvas la forma sobrepasaría el borde del lienzo # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Herramientas de documento Save a Timestamped Copy Guardar una copia con fecha y hora @@ -10363,6 +10514,50 @@ breakText Glyphs Glifos @msg A joint does not close by {gap} pt. Una unión no cierra por {gap} pt. @msg Two panels pass through each other. Dos paneles se atraviesan entre sí. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer debe ser "singleLine", "everyLine", "standardSingleLine" o "standardEveryLine" + Fine Stipple Punteado fino + Dense Stipple Punteado denso + Soft Stipple Punteado suave + Bold Stipple Punteado grueso + Paper Cutouts Recortes de papel + Coral Layers Capas coral + Mint Layers Capas menta + Midnight Layers Capas de medianoche + Sunflower Sheet Hoja de girasol + Rose Layers Capas rosa + Monochrome Stack Pila monocroma +# Tool cards (General › Show Tool Cards): one sentence on what each tool does. + Shows a card with what a toolbar tool does and what its keys do instead of its tip; it needs Show Tool Tips. Muestra una ficha con lo que hacen una herramienta de la barra y sus teclas en lugar de su información; requiere Mostrar información sobre herramientas. + Selects whole objects and groups to move, resize or rotate them. Selecciona objetos y grupos completos para moverlos, cambiar su tamaño o girarlos. + Selects anchor points and path segments to reshape a path. Selecciona puntos de ancla y segmentos de trazado para cambiar la forma de un trazado. + Draws paths point by point, with straight segments and smooth curves. Dibuja trazados punto a punto, con segmentos rectos y curvas suaves. + Draws smooth curves through the points you click. Dibuja curvas suaves que pasan por los puntos en los que hace clic. + Adds text at a point, or in a frame you drag. Añade texto en un punto o en un marco que arrastra. + Draws rectangles and squares. Dibuja rectángulos y cuadrados. + Draws rectangles with rounded corners. Dibuja rectángulos con esquinas redondeadas. + Draws ellipses and circles. Dibuja elipses y círculos. + Draws polygons with sides of equal length. Dibuja polígonos con lados de igual longitud. + Draws stars. Dibuja estrellas. + Turns objects around a reference point. Gira objetos alrededor de un punto de referencia. + Flips objects across an axis through a reference point. Refleja objetos sobre un eje que pasa por un punto de referencia. + Resizes objects from a reference point. Cambia el tamaño de los objetos desde un punto de referencia. + Slants objects from a reference point. Inclina objetos desde un punto de referencia. + Moves the view of the document. Desplaza la vista del documento. + Magnifies or reduces the view. Amplía o reduce la vista. + Copies the color and other attributes of one object to the selection. Copia el color y otros atributos de un objeto en la selección. + Sets the direction and length of a gradient. Define la dirección y la longitud de un degradado. + Creates, selects and resizes artboards. Crea, selecciona y cambia el tamaño de mesas de trabajo. + Changes the width of a stroke along its length. Cambia el ancho de un trazo a lo largo de su longitud. + Bends art by dragging pins placed on it. Deforma la ilustración arrastrando chinchetas colocadas sobre ella. + Pushes the outlines of paths in the direction you drag. Empuja los contornos de los trazados en la dirección en la que arrastra. + Twists the outlines of paths into swirls. Retuerce los contornos de los trazados en remolinos. + Pulls the outlines of paths in toward the brush. Atrae los contornos de los trazados hacia el pincel. + Pushes the outlines of paths out from the brush. Empuja los contornos de los trazados hacia fuera del pincel. + Adds curved details along the outlines of paths. Añade detalles curvos a lo largo de los contornos de los trazados. + Adds spiky details along the outlines of paths. Añade detalles puntiagudos a lo largo de los contornos de los trazados. + Adds wrinkles along the outlines of paths. Añade arrugas a lo largo de los contornos de los trazados. + Moves, copies and resizes objects on the perspective grid. Mueve, copia y cambia el tamaño de objetos en la cuadrícula de perspectiva. + Makes a series of steps between two or more objects. Crea una serie de pasos entre dos o más objetos. + Places dimension lines that show measured lengths. Coloca líneas de cota que muestran longitudes medidas. Tap Pulsación breve Clear Hold Borrar pulsación larga Hold Shortcuts Métodos abreviados de pulsación larga @@ -10381,3 +10576,7 @@ breakText Glyphs Glifos Round Flow Flujo redondo Chisel Flow Flujo biselado @msg text.{key} `{v}`: use "{_1}" or "{_2}" text.{key} `{v}`: use "{_1}" o "{_2}" + +# #5804 native-picked raster editor (draft translations; native review welcome). + Edit Original with: Editar original con: +file-filter Applications Aplicaciones diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index e83dd7bc8b..d4084e7b2c 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -560,6 +560,15 @@ Shading Color Varjostusväri Black Overprint Päällepainettu musta Draw Hidden Faces Piirrä piilotetut pinnat + Map Art… Kartoita kuvitus… + Map Art Kartoita kuvitus + First Surface Ensimmäinen pinta + Previous Surface Edellinen pinta + Next Surface Seuraava pinta + Last Surface Viimeinen pinta + Scale to Fit Skaalaa sopivaksi + Shade Artwork Varjosta kuvitus + Invisible Geometry Näkymätön geometria Revolve… Pyöräytä… Inflate… Täytä ilmalla… Materials… Materiaalit… @@ -673,6 +682,8 @@ Hide Gradient Annotator Piilota liukuvärin säädin Show Gradient Annotator Näytä liukuvärin säädin Hide Corner Widget Piilota kulmasäädin + Hide Shape Widgets Piilota muotosäätimet + Show Shape Widgets Näytä muotosäätimet Show Corner Widget Näytä kulmasäädin Guides Apuviivat Hide Guides Piilota apuviivat @@ -793,6 +804,9 @@ Box Channel Ruudun kanava Color box Väriruutu Color Wheel Options Väriympyrän asetukset + Show Harmony Näytä harmonia + Harmony Rule Harmoniasääntö + Harmony color Harmonian väri CSS Properties CSS-ominaisuudet Document Info Asiakirjan tiedot Flattener Preview Litistyksen esikatselu @@ -1039,6 +1053,25 @@ Preserve Embedded Profiles Säilytä upotetut profiilit Convert to Working Space Muunna työväriavaruuteen Preserve Numbers Säilytä lukuarvot + Profile Mismatches: Profiilien ristiriidat: + Ask When Opening Kysy avattaessa + Ask When Pasting Kysy liitettäessä + Missing Profiles: Puuttuvat profiilit: + Embedded Profile Mismatch Upotetun profiilin ristiriita + Missing Profile Profiili puuttuu + Paste Profile Mismatch Profiiliristiriita liitettäessä + “{name}” is not tagged with a {model} profile. Kohteella ”{name}” ei ole {model}-profiilia. + “{name}” is tagged with the {model} profile “{profile}”, which is not the {model} working space “{working}”. Kohteella ”{name}” on {model}-profiili ”{profile}”, joka ei ole {model}-työväriavaruus ”{working}”. + Use the embedded profile Käytä upotettua profiilia + Convert the colors to the working space Muunna värit työväriavaruuteen + Discard the embedded profile Hylkää upotettu profiili + Leave as is Jätä ennalleen + Assign the working space Määritä työväriavaruus + Assign profile: Määritä profiili: + Preserve the color numbers Säilytä värien lukuarvot + Convert to keep the colors' appearance Muunna ja säilytä värien ulkoasu +@msg `{path}` goes with `{key}`: "assign" only `{path}` annetaan vain, kun `{key}` on "assign" + The pasted colors come from a document whose {model} profile is “{from}”; this document's is “{to}”. Liitetyt värit ovat asiakirjasta, jonka {model}-profiili on ”{from}”; tämän asiakirjan profiili on ”{to}”. CMYK CMYK Texture Tekstuuri Craquelure… Krakelyyri… @@ -1121,6 +1154,15 @@ lighting Light Valo Document Raster Effects Settings Dialog Asiakirjan rasteritehosteiden asetusten valintaikkuna Drop Shadow Pudotusvarjo DXF Options Dialog DXF-asetusten valintaikkuna + HP-GL Options HP-GL-asetukset + HP-GL Options Dialog HP-GL-asetusten valintaikkuna + Curve Tolerance: Käyrien toleranssi: + Origin: Origo: + Pens: Kynät: + One Pen per Color Yksi kynä kullekin värille + Pen Table Kynätaulukko + Draw the Nearest Path Next Piirrä seuraavaksi lähin polku + Draw Inner Paths First Piirrä sisemmät polut ensin Edit Toolbar Muokkaa työkaluriviä Edit Views Muokkaa näkymiä Effect… Tehoste… @@ -1696,6 +1738,7 @@ digits Malayalam Malajalam Roman Baseline Latinalainen perusviiva Select a text object to edit its character attributes. Valitse tekstiobjekti, jonka merkkimääritteitä haluat muokata. Show Options Näytä asetukset + Show on Shape Creation Näytä muotoa luotaessa Show Recent Colors Näytä viimeisimmät värit Toggle RGB Percent Vaihda RGB prosentteina Small Caps Kapiteelit @@ -2048,6 +2091,8 @@ digits Malayalam Malajalam Snap Curves To Lines Tartu käyrät viivoihin Tracing Result with Outlines Jäljitystulos ääriviivoineen Source Image Lähdekuva + Split View Jaettu näkymä + Divider Jakoviiva Threshold Kynnys Trace Jäljitä Trace the image with the Default preset Jäljitä kuva oletusesiasetuksella @@ -2185,6 +2230,15 @@ digits Malayalam Malajalam YakumonoZenkaku YakumonoZenkaku Kinsoku Set Kinsoku-joukko Kinsoku Shori Type Kinsoku Shori -tyyppi + Kinsoku Shori Settings… Kinsoku Shori -asetukset… + Kinsoku Shori Settings Kinsoku Shori -asetukset + Kinsoku Sets Kinsoku-joukot + Kinsoku Set Base Kinsoku-joukon pohja + Based on: Pohjana: + Cannot Start Line Ei voi aloittaa riviä + Cannot End Line Ei voi päättää riviä + Hanging Punctuation Riippuvat välimerkit + Inseparable Characters Erottamattomat merkit Push In First Ensin sisään Push Out First Ensin ulos Push Out Only Vain ulos @@ -2585,6 +2639,12 @@ digits Malayalam Malajalam Units: Yksiköt: Use Typographer's Quotes Käytä typografisia lainausmerkkejä Center Artwork Keskitä kuvitus + PSD Import Options PSD-tuonnin asetukset + Place PSD Sijoita PSD + Convert Layers to Objects Muunna tasot objekteiksi + Import Hidden Layers Tuo piilotetut tasot + Flatten Layers to a Single Image Litistä tasot yhdeksi kuvaksi + Import Slices Tuo siivut DXF Import Options DXF-tuonnin asetukset Layout: Asettelu: Merge Layers Yhdistä tasot @@ -2736,6 +2796,7 @@ digits Malayalam Malajalam Save As Preset… Tallenna esiasetuksena… Save Changes Tallenna muutokset Save Preset… Tallenna esiasetus… + Save Summary… Tallenna yhteenveto… Vectors Vektorit A saved copy of the selected preset Tallennettu kopio valitusta esiasetuksesta Built-in presets don't change: New makes a copy you can edit. Sisäiset esiasetukset eivät muutu: Uusi luo muokattavan kopion. @@ -2969,6 +3030,8 @@ digits Malayalam Malajalam Overprint and Transparency Flattener Options Päällepainatuksen ja läpinäkyvyyden litistyksen asetukset Custom… Mukautettu… Custom Transparency Flattener Options Läpinäkyvyyden litistyksen mukautetut asetukset + The PDF preset keeps the flattener preset but not the Custom… settings. PDF-esiasetus säilyttää litistyksen esiasetuksen mutta ei Mukautettu…-asetuksia. + PDF 1.3 files clip rasterized areas to their regions, and Overprint sets whether overprints are kept. PDF 1.3 -tiedostot rajaavat rasteroidut alueet niiden muotoon, ja Päällepainatus määrää, säilytetäänkö päällepainatukset. EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS:ssä ei ole alfa-läpinäkyvyyttä, ja Päällepainatukset määrää, säilytetäänkö päällepainatukset. Place the pages with the placement again Sijoita sivut uudelleen sijoittelun mukaan Placement: Sijoittelu: @@ -3064,6 +3127,9 @@ digits Malayalam Malajalam Recolor this row Väritä tämä rivi uudelleen Reset the rows to the artwork's colors Palauta rivit kuvituksen väreihin Color Theme Picker Väriteeman valitsin + Undo Changes Kumoa muutokset + Redo Changes Tee muutokset uudelleen +@msg Recolor Artwork is not open Väritä kuvitus uudelleen ei ole auki Click or drag across the art to pick its colors; Shift adds more Napsauta tai vedä kuvituksen yli poimiaksesi sen värit; Vaihto lisää useampia Prominent Colors Hallitsevat värit Save All Colors Tallenna kaikki värit @@ -3351,6 +3417,17 @@ antiAlias Sharp Terävä Swatch Name: Värimallin nimi: Diameter: Halkaisija: Symbolism Tools Options Symbolityökalujen asetukset + Tool: Työkalu: + Symbol Set Density Symbolijoukon tiheys + Symbol Sprayer Options Symbolisuihkuttimen asetukset + Scrunch: Tiivistys: + Spin: Kierto: + Screen: Läpinäkyvyys: + Stain: Värjäys: + Symbol Sizer Options Symbolien koonmuutoksen asetukset + Proportional Resizing Suhteellinen koonmuutos + Resizing Affects Density Koonmuutos vaikuttaa tiheyteen + Show Brush Size and Intensity Näytä siveltimen koko ja voimakkuus Symbol Set Density: Symbolijoukon tiheys: Intensity: Voimakkuus: Place PDF Sijoita PDF @@ -3447,6 +3524,7 @@ antiAlias Sharp Terävä Width Point Edit Leveyspisteen muokkaus Art Kuvitus Bearing Suunta + Stylus Wheel Kynän rulla Bristle Harjas Calligraphic Kalligrafinen Dots Pisteet @@ -3589,6 +3667,9 @@ theme Appearance Ulkoasu embedding for preview and print upottaminen esikatselua ja tulostusta varten embedding allowed upottaminen sallittu {file}; {embedding} {file}; {embedding} + unknown type tuntematon tyyppi + {type}; {uses} {type}; {uses} +@plural {n} use|{n} uses {n} käyttö|{n} käyttöä substituted: shown in {family} {style} ({detail}) korvattu: näytetään fontilla {family} {style} ({detail}) missing: shown in {family} {style} puuttuu: näytetään fontilla {family} {style} missing puuttuu @@ -4162,6 +4243,7 @@ theme Appearance Ulkoasu Show Pixel Grid (Above 600% Zoom) Näytä pikseliruudukko (yli 600 %:n zoomaus) Show Slice Numbers Näytä viipaleiden numerot Show The Home Screen When No Documents Are Open Näytä aloitusnäyttö, kun asiakirjoja ei ole avoinna + Show Tool Cards Näytä työkalukortit Show Tool Tips Näytä työkaluvihjeet Size/Leading Koko/riviväli Snapping Tolerance Tartuntatoleranssi @@ -4287,6 +4369,8 @@ theme Appearance Ulkoasu Spot Colors (0) Spottivärit (0) Swatch Options Värimallin asetukset Ungroup Color Group Pura väriryhmä + Color Group Options Väriryhmän asetukset + Color Group Options… Väriryhmän asetukset… Copy to User Defined Kopioi käyttäjän määrittämiin Swatch Library Värimallikirjasto Clear All Tabs Tyhjennä kaikki sarkaimet @@ -4589,6 +4673,7 @@ font-technology Variable Muuttuvat A live rectangle's properties show one Corner Radius field for all four corners; off, each corner has its own field. Dynaamisen suorakulmion ominaisuuksissa on yksi Kulman säde -kenttä kaikille neljälle kulmalle; kun asetus ei ole käytössä, jokaisella kulmalla on oma kenttänsä. What edits in the Transform panel transform: the object, its pattern tiles or both; Default follows Transform Pattern Tiles. Mitä Muunna-paneelin muokkaukset muuntavat: objektin, sen kuvioruudut tai molemmat; Oletus noudattaa asetusta Muunna kuvioruudut. With one symbol instance selected, the Transform panel uses the symbol's registration point as its reference point. Kun yksi symbolin esiintymä on valittuna, Muunna-paneeli käyttää symbolin kohdistuspistettä viitepisteenä. + Drawing a rectangle, ellipse, polygon, star or line opens the Transform panel if it is closed. Suorakulmion, ellipsin, monikulmion, tähden tai viivan piirtäminen avaa Muunna-paneelin, jos se on suljettu. Darkens the canvas outside the artboards while the Artboard tool is active. Tummentaa piirtopinnan piirtoalustojen ulkopuolelta, kun Piirtoalusta-työkalu on käytössä. With Fade Region Outside Artboard on, the area outside the artboards stays dark while you drag with the Artboard tool. Kun Himmennä piirtoalustan ulkopuolinen alue on käytössä, piirtoalustojen ulkopuolinen alue pysyy tummana, kun vedät Piirtoalusta-työkalulla. How near, in pixels, the pointer must be to an object, anchor or handle for a click to select it. Kuinka lähellä, pikseleinä, osoittimen on oltava objektia, ankkuripistettä tai kahvaa, jotta napsautus valitsee sen. @@ -4683,6 +4768,9 @@ font-technology Variable Muuttuvat Channel Kanava Circle Ympyrä Circle Tool Ympyrätyökalu + Curvature Circle Tool Kaarevuusympyrätyökalu + Cusp Kärki + Straight segment Suora segmentti Circle too large Ympyrä on liian suuri Clip to Art Rajaa kuvitukseen Colorize Väritä @@ -5294,6 +5382,9 @@ liquify-list-end {0}, {1} {0} ja {1} @msg a freeform gradient keeps at least one point vapaamuotoisessa liukuvärissä on oltava vähintään yksi piste @msg a gradient needs at least two stops liukuvärissä on oltava vähintään kaksi väripistettä @msg a graphic style named `{to}` already exists grafiikkatyyli nimeltä `{to}` on jo olemassa +@msg a swatch or color group named `{name}` already exists värimalli tai väriryhmä nimeltä `{name}` on jo olemassa +@msg missing `group` `group` puuttuu +@msg no colour group `{group}` ei väriryhmää `{group}` @msg a key object sits on that point pisteessä on avainobjekti @msg a page is missing sivu puuttuu @msg a page out of range sivu alueen ulkopuolella @@ -5406,6 +5497,7 @@ liquify-list-end {0}, {1} {0} ja {1} @msg missing `folder` `folder` puuttuu @msg missing `id` (see plugin.list) `id` puuttuu (ks. plugin.list) @msg missing `name` `name` puuttuu +@msg missing `path` `path` puuttuu @msg missing `tool` `tool` puuttuu @msg missing id id puuttuu @msg missing index indeksi puuttuu @@ -5428,6 +5520,11 @@ liquify-list-end {0}, {1} {0} ja {1} @msg no anchor points selected ankkuripisteitä ei ole valittu @msg `points` must be two or three [x, y] pairs of numbers `points` on annettava kahtena tai kolmena lukuparina [x, y] @msg direct-select two or three anchor points, or give `points` valitse suoraan kaksi tai kolme ankkuripistettä tai anna `points` +@msg the path is straight there, so no circle matches its curvature polku on siinä kohdassa suora, joten mikään ympyrä ei vastaa sen kaarevuutta +@msg the path has a cusp there, so it has no single curvature polulla on siinä kohdassa kärki, joten sillä ei ole yksiselitteistä kaarevuutta +@msg the path has a corner there, so it has no single curvature polulla on siinä kohdassa kulma, joten sillä ei ole yksiselitteistä kaarevuutta +@msg a guide has no curvature circle apuviivalla ei ole kaarevuusympyrää +@msg the circle that matches the path there would reach past the canvas ympyrä, joka vastaa polkua siinä kohdassa, ylittäisi kankaan @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 @@ -5680,6 +5777,7 @@ liquify-list-end {0}, {1} {0} ja {1} @msg the PDF is password-protected: give its password tämä PDF-tiedosto on suojattu salasanalla: anna sen salasana @msg the PDF password is wrong annettu PDF-salasana on väärä @msg the Save PDF dialog didn't open valintaikkuna Tallenna PDF ei avautunut +@msg the Save PDF dialog is not open valintaikkuna Tallenna PDF ei ole auki @msg the WMF header is damaged tiedoston WMF-otsake on vaurioitunut @msg the art could not be sampled kuvitusta ei voitu näytteistää @msg the art has no bounds kuvituksella ei ole rajoja @@ -5903,6 +6001,7 @@ variable-list-end {0}, {1} {0} ja {1} @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 +@msg give only one of `index`, `indices` and `t` anna vain yksi arvoista `index`, `indices` ja `t` @msg column must be true or a number from 1 column-arvon on oltava true tai luku 1:stä alkaen @msg x and y must both be numbers x:n ja y:n on molempien oltava lukuja @msg "{0}" is not a colour: write it as #rrggbb "{0}" ei ole väri: kirjoita se muodossa #rrggbb @@ -6022,6 +6121,49 @@ variable-list-end {0}, {1} {0} ja {1} @msg the PSD file's layer groups are nested too deeply tämän PSD-tiedoston tasoryhmät ovat sisäkkäin liian syvällä @msg a layer of the PSD file is too large to read tämän PSD-tiedoston taso on liian suuri luettavaksi @msg the PSD file's layers take more memory to read than allowed tämän PSD-tiedoston tasojen lukeminen vaatii enemmän muistia kuin sallitaan +@msg the file is no longer loaded tiedosto ei ole enää ladattuna +@msg the layers can't be read ({e}): the file was placed as its merged image tasoja ei voi lukea ({e}): tiedosto sijoitettiin yhdistettynä kuvanaan +@msg 1 type layer came in as pixels: the text isn't editable 1 tekstitaso tuotiin pikseleinä: tekstiä ei voi muokata +@msg {n} type layers came in as pixels: the text isn't editable {n} tekstitasoa tuotiin pikseleinä: tekstiä ei voi muokata +@msg 1 adjustment layer was not applied 1 säätötasoa ei käytetty +@msg {n} adjustment layers were not applied {n} säätötasoa ei käytetty +@msg 1 fill layer was not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels) 1 täyttötasoa ei piirretty (liukuväri- tai kuviotäyttö, väri, jota ei voi lukea, tai muoto, joka ei tallenna pikseleitä) +@msg {n} fill layers were not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels) {n} täyttötasoa ei piirretty (liukuväri- tai kuviotäyttö, väri, jota ei voi lukea, tai muoto, joka ei tallenna pikseleitä) +@msg the layer effects of 1 layer weren't drawn 1 tason tasotehosteita ei piirretty +@msg the layer effects of {n} layers weren't drawn {n} tason tasotehosteita ei piirretty +@msg the vector masks of 1 layer weren't applied 1 tason vektorimaskeja ei käytetty +@msg the vector masks of {n} layers weren't applied {n} tason vektorimaskeja ei käytetty +@msg the knockout of 1 layer wasn't applied 1 tason poistoa ei käytetty +@msg the knockout of {n} layers wasn't applied {n} tason poistoa ei käytetty +@msg 1 layer was left out (hidden layers and the layers clipped to them) 1 taso jätettiin pois (piilotetut tasot ja niihin leikatut tasot) +@msg {n} layers were left out (hidden layers and the layers clipped to them) {n} tasoa jätettiin pois (piilotetut tasot ja niihin leikatut tasot) +@msg 1 layer clipped to a fill layer that wasn't drawn was left out 1 taso, joka on leikattu piirtämättä jääneeseen täyttötasoon, jätettiin pois +@msg {n} layers clipped to fill layers that weren't drawn were left out {n} tasoa, jotka on leikattu piirtämättä jääneisiin täyttötasoihin, jätettiin pois +@msg layers in blend modes VectorCraft doesn't have ({modes}) were merged with the layers below them tasot sekoitustiloissa, joita VectorCraftissa ei ole ({modes}), yhdistettiin alla oleviin tasoihin +@msg 1 layer in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed 1 taso sekoitustilassa, jota VectorCraftissa ei ole, tuotiin Normaali-tilassa: yhdistäminen vaatii sallittua enemmän muistia +@msg {n} layers in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed {n} tasoa sekoitustiloissa, joita VectorCraftissa ei ole, tuotiin Normaali-tilassa: yhdistäminen vaatii sallittua enemmän muistia +@msg 1 layer clipped to the layer below came in unclipped: the merge needs more memory than allowed 1 alla olevaan tasoon leikattu taso tuotiin leikkaamattomana: yhdistäminen vaatii sallittua enemmän muistia +@msg {n} layers clipped to the layer below came in unclipped: the merge needs more memory than allowed {n} alla olevaan tasoon leikattua tasoa tuotiin leikkaamattomina: yhdistäminen vaatii sallittua enemmän muistia +@msg hiddenLayers applies to a PSD file placed with layers: true hiddenLayers koskee PSD-tiedostoa, joka sijoitetaan asetuksella layers: true +@msg importSlices: a linked PSD file is placed as its flat image; give link: false to embed it with its slices importSlices: linkitetty PSD-tiedosto sijoitetaan litteänä kuvanaan; anna link: false, jotta se upotetaan siivuineen +@msg layers: a linked PSD file is placed as its flat image; leave link out or give link: false layers: linkitetty PSD-tiedosto sijoitetaan litteänä kuvanaan; jätä link pois tai anna link: false +@msg the slices can't be read ({e}) and were left out siivuja ei voi lukea ({e}), ja ne jätettiin pois +@msg 1 slice lies outside the canvas or has no size and was left out 1 siivu on kankaan ulkopuolella tai sillä ei ole kokoa, ja se jätettiin pois +@msg {n} slices lie outside the canvas or have no size and were left out {n} siivua on kankaan ulkopuolella tai niillä ei ole kokoa, ja ne jätettiin pois +@msg 1 slice would lie outside the canvas and was left out 1 siivu olisi kankaan ulkopuolella, ja se jätettiin pois +@msg {n} slices would lie outside the canvas and were left out {n} siivua olisi kankaan ulkopuolella, ja ne jätettiin pois +@msg the slices' descriptor holds too many values siivujen kuvaajassa on liian monta arvoa +@msg the slices' descriptor has a version other than 16 siivujen kuvaajan versio on muu kuin 16 +@msg the slices are stored in version {v}, which isn't read siivut on tallennettu versiossa {v}, jota ei lueta +@msg the file has {count} slices, more than the {MAX_SLICES} read tiedostossa on {count} siivua, enemmän kuin luettavat {MAX_SLICES} +@msg the slices' descriptor has no list of slices siivujen kuvaajassa ei ole siivuluetteloa +@msg the slices' descriptor lists something other than a slice siivujen kuvaaja luettelee jotain muuta kuin siivun +@msg a slice in the slices' descriptor has no bounds siivujen kuvaajan siivulla ei ole rajoja +@msg a slice's bounds in the slices' descriptor aren't numbers siivujen kuvaajan siivun rajat eivät ole lukuja +@msg a text in the slices has more than the {MAX_TEXT} characters read siivujen tekstissä on enemmän kuin luettavat {MAX_TEXT} merkkiä +@msg the slices' descriptor nests too deep siivujen kuvaaja on sisäkkäin liian syvälle +@msg the slices' descriptor has a reference of an unknown kind ({_1}) siivujen kuvaajassa on tuntematonta lajia oleva viittaus ({_1}) +@msg the slices' descriptor has a value of an unknown type ({_1}) siivujen kuvaajassa on tuntematonta tyyppiä oleva arvo ({_1}) @msg the layers can't be read ({e}): the file opened as its merged image tasoja ei voi lukea ({e}): tiedosto avattiin yhdistettynä kuvanaan @msg {depth}-bit PSD files in this colour mode can't be read tässä väritilassa olevia {depth}-bittisiä PSD-tiedostoja ei voi lukea @msg the PSD file is cut short tämä PSD-tiedosto on katkennut @@ -8192,6 +8334,8 @@ breakText Glyphs Merkit # Path Precision Tools add-on: Tangent Circle. Tangent Circle… Sivuava ympyrä… Tangent Circle Sivuava ympyrä + Tangent Circle Tool Sivuava ympyrä -työkalu + No tangent circle here Tässä ei ole sivuavaa ympyrää Circle: Ympyrä: @msg `ids` names an object twice `ids` mainitsee saman objektin kahdesti @msg select two or three paths or compound paths valitse kaksi tai kolme polkua tai yhdistelmäpolkua @@ -8207,6 +8351,16 @@ breakText Glyphs Merkit @msg `circle` is past the last circle found ({found}) `circle` on viimeisen löydetyn ympyrän jälkeen ({found}) @msg object {value} is not a path or compound path objekti {value} ei ole polku eikä yhdistelmäpolku @msg these shapes are too small to measure nämä muodot ovat liian pieniä mitattaviksi +# Path Precision Tools add-on: Add Bounding Rectangle and Add Bounding Circle. + Add Bounding Rectangle Lisää rajaava suorakulmio + Add Bounding Circle Lisää rajaava ympyrä + Add Bounding Rectangle… Lisää rajaava suorakulmio… + Add Bounding Circle… Lisää rajaava ympyrä… + One per Object Yksi kutakin objektia kohden +@msg nothing to enclose ei ympäröitävää +@msg `offset` must be 0 or more `offset` on oltava 0 tai enemmän +@msg the shape would have no size muodolla ei olisi kokoa +@msg the shape would reach past the edge of the canvas muoto ulottuisi kankaan reunan yli # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Asiakirjatyökalut Save a Timestamped Copy Tallenna kopio aikaleimalla @@ -8700,6 +8854,50 @@ breakText Glyphs Merkit @msg A joint does not close by {gap} pt. Liitos ei sulkeudu, rako {gap} pt. @msg Two panels pass through each other. Kaksi paneelia kulkee toistensa läpi. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer on oltava "singleLine", "everyLine", "standardSingleLine" tai "standardEveryLine" + Fine Stipple Hieno pistetys + Dense Stipple Tiheä pistetys + Soft Stipple Pehmeä pistetys + Bold Stipple Vahva pistetys + Paper Cutouts Paperileikkeet + Coral Layers Korallikerrokset + Mint Layers Minttukerrokset + Midnight Layers Keskiyön kerrokset + Sunflower Sheet Auringonkukka-arkki + Rose Layers Ruusukerrokset + Monochrome Stack Yksivärinen pino +# Tool cards (General › Show Tool Cards): one sentence on what each tool does. + Shows a card with what a toolbar tool does and what its keys do instead of its tip; it needs Show Tool Tips. Näyttää vihjeen sijaan kortin siitä, mitä työkalurivin työkalu ja sen näppäimet tekevät; vaatii asetuksen Näytä työkaluvihjeet. + Selects whole objects and groups to move, resize or rotate them. Valitsee kokonaisia objekteja ja ryhmiä niiden siirtämistä, koon muuttamista tai kiertämistä varten. + Selects anchor points and path segments to reshape a path. Valitsee ankkuripisteitä ja polun osia polun muodon muuttamista varten. + Draws paths point by point, with straight segments and smooth curves. Piirtää polkuja piste kerrallaan suorin osin ja pehmein kaarin. + Draws smooth curves through the points you click. Piirtää pehmeitä kaaria napsauttamiesi pisteiden kautta. + Adds text at a point, or in a frame you drag. Lisää tekstiä pisteeseen tai vetämääsi kehykseen. + Draws rectangles and squares. Piirtää suorakulmioita ja neliöitä. + Draws rectangles with rounded corners. Piirtää pyöristettykulmaisia suorakulmioita. + Draws ellipses and circles. Piirtää ellipsejä ja ympyröitä. + Draws polygons with sides of equal length. Piirtää monikulmioita, joiden sivut ovat yhtä pitkiä. + Draws stars. Piirtää tähtiä. + Turns objects around a reference point. Kiertää objekteja viitepisteen ympäri. + Flips objects across an axis through a reference point. Peilaa objekteja viitepisteen kautta kulkevan akselin yli. + Resizes objects from a reference point. Muuttaa objektien kokoa viitepisteestä. + Slants objects from a reference point. Vinouttaa objekteja viitepisteestä. + Moves the view of the document. Siirtää asiakirjan näkymää. + Magnifies or reduces the view. Suurentaa tai pienentää näkymää. + Copies the color and other attributes of one object to the selection. Kopioi yhden objektin värin ja muut määritteet valintaan. + Sets the direction and length of a gradient. Asettaa liukuvärin suunnan ja pituuden. + Creates, selects and resizes artboards. Luo ja valitsee piirtoalustoja ja muuttaa niiden kokoa. + Changes the width of a stroke along its length. Muuttaa viivan leveyttä sen pituudella. + Bends art by dragging pins placed on it. Taivuttaa kuvitusta vetämällä siihen asetettuja nastoja. + Pushes the outlines of paths in the direction you drag. Työntää polkujen ääriviivoja vetosuuntaan. + Twists the outlines of paths into swirls. Kiertää polkujen ääriviivat pyörteiksi. + Pulls the outlines of paths in toward the brush. Vetää polkujen ääriviivoja siveltimeen päin. + Pushes the outlines of paths out from the brush. Työntää polkujen ääriviivoja ulospäin siveltimestä. + Adds curved details along the outlines of paths. Lisää kaarevia yksityiskohtia polkujen ääriviivoihin. + Adds spiky details along the outlines of paths. Lisää piikikkäitä yksityiskohtia polkujen ääriviivoihin. + Adds wrinkles along the outlines of paths. Lisää ryppyjä polkujen ääriviivoihin. + Moves, copies and resizes objects on the perspective grid. Siirtää, kopioi ja muuttaa objektien kokoa perspektiiviruudukossa. + Makes a series of steps between two or more objects. Luo sarjan välivaiheita kahden tai useamman objektin välille. + Places dimension lines that show measured lengths. Lisää mittaviivoja, jotka näyttävät mitatut pituudet. Tap Lyhyt painallus Clear Hold Tyhjennä pitkä painallus Hold Shortcuts Pitkän painalluksen pikanäppäimet @@ -8718,3 +8916,7 @@ breakText Glyphs Merkit Round Flow Pyöreä veto Chisel Flow Viisto veto @msg text.{key} `{v}`: use "{_1}" or "{_2}" text.{key} `{v}`: käytä arvoa "{_1}" tai "{_2}" + +# #5804 native-picked raster editor (draft translations; native review welcome). + Edit Original with: Muokkaa alkuperäistä sovelluksella: +file-filter Applications Sovellukset diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 41f57382ff..f055af1686 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -499,6 +499,9 @@ font-technology Variable Variables Choose… Choisir… Circle Cercle Circle Tool Outil Cercle + Curvature Circle Tool Outil Cercle de courbure + Cusp Point de rebroussement + Straight segment Segment droit Circle too large Cercle trop grand Classic Defaults Valeurs par défaut classiques Clean Up… Nettoyer… @@ -606,6 +609,9 @@ font-technology Variable Variables Box Channel Couche du carré Color box Carré de couleur Color Wheel Options Options de la roue chromatique + Show Harmony Afficher l’harmonie + Harmony Rule Règle d’harmonie + Harmony color Couleur de l’harmonie Color Type: Type de couleur : Color: Couleur : Colorize Coloriser @@ -1033,10 +1039,25 @@ font-technology Variable Variables Duplicate Symbol Dupliquer le symbole Duplicate {kind} Style Dupliquer le style de {kind} Dutch Néerlandais + PSD Import Options Options d’importation PSD + Place PSD Importer un fichier PSD + Convert Layers to Objects Convertir les calques en objets + Import Hidden Layers Importer les calques masqués + Flatten Layers to a Single Image Aplatir les calques en une seule image + Import Slices Importer les tranches DXF Import Options Options d’importation DXF DXF Info Informations DXF DXF Options Options DXF DXF Options Dialog Boîte de dialogue Options DXF + HP-GL Options Options HP-GL + HP-GL Options Dialog Boîte de dialogue Options HP-GL + Curve Tolerance: Tolérance des courbes : + Origin: Origine : + Pens: Plumes : + One Pen per Color Une plume par couleur + Pen Table Table des plumes + Draw the Nearest Path Next Tracer ensuite le tracé le plus proche + Draw Inner Paths First Tracer d’abord les tracés intérieurs e.g. 1-3, 5 p. ex. 1-3, 5 Each page prints as one image, at the document's raster effects resolution. Chaque page s’imprime comme une seule image, à la résolution des effets de pixellisation du document. Earth Tones Tons terre @@ -1261,6 +1282,15 @@ font-technology Variable Variables Shading Color Couleur d’ombrage Black Overprint Noir en surimpression Draw Hidden Faces Dessiner les faces cachées + Map Art… Placage d’illustration… + Map Art Placage d’illustration + First Surface Première surface + Previous Surface Surface précédente + Next Surface Surface suivante + Last Surface Dernière surface + Scale to Fit Mettre à l’échelle pour ajuster + Shade Artwork Ombrer l’illustration + Invisible Geometry Géométrie invisible Eyedropper Pipette Sample Color from Screen Prélever une couleur à l’écran This system has no screen color sampler Ce système n’a pas d’outil de prélèvement de couleur à l’écran @@ -1389,6 +1419,17 @@ font-technology Variable Variables Largest: Le plus grand : Direction: Direction : Symbolism Tools Options Options des outils de symbolisme + Tool: Outil : + Symbol Set Density Densité du jeu de symboles + Symbol Sprayer Options Options de pulvérisation de symboles + Scrunch: Espacement : + Spin: Rotation : + Screen: Transparence : + Stain: Coloration : + Symbol Sizer Options Options de redimensionnement de symboles + Proportional Resizing Redimensionnement proportionnel + Resizing Affects Density Le redimensionnement modifie la densité + Show Brush Size and Intensity Afficher la taille et l’intensité du pinceau Symbol Set Density: Densité du jeu de symboles : Flat Image Image aplatie Flat Logo Logo en aplats @@ -1658,6 +1699,8 @@ font-technology Variable Variables More Options Plus d’options Show Properties Panel Afficher le panneau Propriétés Hide Corner Widget Masquer le widget d’angle + Hide Shape Widgets Masquer les widgets de forme + Show Shape Widgets Afficher les widgets de forme Hide Corner Widget for angles greater than Masquer le widget d’angle pour les angles supérieurs à Hide Edges Masquer les contours Hide Gradient Annotator Masquer l’annotateur de dégradé @@ -2213,6 +2256,15 @@ font-technology Variable Variables YakumonoZenkaku YakumonoZenkaku Kinsoku Set Jeu de kinsoku Kinsoku Shori Type Type de kinsoku shori + Kinsoku Shori Settings… Paramètres de kinsoku shori… + Kinsoku Shori Settings Paramètres de kinsoku shori + Kinsoku Sets Jeux de kinsoku + Kinsoku Set Base Base du jeu de kinsoku + Based on: Basé sur : + Cannot Start Line Ne peut pas commencer une ligne + Cannot End Line Ne peut pas terminer une ligne + Hanging Punctuation Ponctuation suspendue + Inseparable Characters Caractères insécables Push In First D’abord vers l’intérieur Push Out First D’abord vers l’extérieur Push Out Only Vers l’extérieur uniquement @@ -2329,6 +2381,7 @@ font-technology Variable Variables Pressure Pression Tilt Inclinaison Bearing Orientation + Stylus Wheel Molette du stylet Shape: Forme : Bristle Length: Longueur des soies : Bristle Density: Densité des soies : @@ -2359,6 +2412,9 @@ font-technology Variable Variables embedding for preview and print incorporation pour l’aperçu et l’impression embedding allowed incorporation autorisée {file}; {embedding} {file}, {embedding} + unknown type type inconnu + {type}; {uses} {type}, {uses} +@plural {n} use|{n} uses {n} utilisation|{n} utilisations substituted: shown in {family} {style} ({detail}) remplacée, affichée en {family} {style} ({detail}) missing: shown in {family} {style} absente, affichée en {family} {style} missing absente @@ -2631,6 +2687,8 @@ font-technology Variable Variables Overprint and Transparency Flattener Options Options de surimpression et d’aplatissement des transparences Custom… Personnalisé… Custom Transparency Flattener Options Options personnalisées d’aplatissement des transparences + The PDF preset keeps the flattener preset but not the Custom… settings. Le paramètre prédéfini PDF conserve le paramètre prédéfini d’aplatissement, mais pas les réglages de Personnalisé…. + PDF 1.3 files clip rasterized areas to their regions, and Overprint sets whether overprints are kept. Les fichiers PDF 1.3 écrêtent les zones pixellisées à leurs régions, et Surimpression détermine si les surimpressions sont conservées. EPS has no alpha transparency, and Overprints sets whether overprints are kept. Le format EPS n’a pas de transparence alpha, et Surimpressions détermine si les surimpressions sont conservées. Overprint Black… Surimpression du noir… Overprint Fill Surimpression du fond @@ -3144,6 +3202,9 @@ digits Malayalam Malayalam Rotate View to Selection Faire pivoter l’affichage selon la sélection Reset the rows to the artwork's colors Réinitialiser les lignes avec les couleurs de l’illustration Color Theme Picker Sélecteur de thème de couleurs + Undo Changes Annuler les modifications + Redo Changes Rétablir les modifications +@msg Recolor Artwork is not open Redéfinir les couleurs de l’illustration n’est pas ouvert Click or drag across the art to pick its colors; Shift adds more Cliquez ou faites glisser sur l’illustration pour prélever ses couleurs ; Maj en ajoute d’autres Prominent Colors Couleurs dominantes Save All Colors Enregistrer toutes les couleurs @@ -3198,6 +3259,7 @@ digits Malayalam Malayalam A live rectangle's properties show one Corner Radius field for all four corners; off, each corner has its own field. Les propriétés d’un rectangle dynamique affichent un seul champ Rayon de l’angle pour les quatre angles. Désactivée, chaque angle a son propre champ. What edits in the Transform panel transform: the object, its pattern tiles or both; Default follows Transform Pattern Tiles. Les modifications du panneau Transformation transforment l’objet, ses carreaux de motif ou les deux, et Par défaut suit Transformer les carreaux de motif. With one symbol instance selected, the Transform panel uses the symbol's registration point as its reference point. Quand une occurrence de symbole est sélectionnée, le panneau Transformation utilise le point d’alignement du symbole comme point de référence. + Drawing a rectangle, ellipse, polygon, star or line opens the Transform panel if it is closed. Dessiner un rectangle, une ellipse, un polygone, une étoile ou une ligne ouvre le panneau Transformation s’il est fermé. Darkens the canvas outside the artboards while the Artboard tool is active. Assombrit la zone de travail hors des plans de travail tant que l’outil Plan de travail est actif. With Fade Region Outside Artboard on, the area outside the artboards stays dark while you drag with the Artboard tool. Avec Assombrir la zone hors du plan de travail activé, la zone hors des plans de travail reste sombre pendant que vous faites glisser avec l’outil Plan de travail. How near, in pixels, the pointer must be to an object, anchor or handle for a click to select it. Distance en pixels à laquelle le pointeur doit se trouver d’un objet, d’un point d’ancrage ou d’une poignée pour qu’un clic le sélectionne. @@ -3377,6 +3439,7 @@ digits Malayalam Malayalam Save Preset Enregistrer le paramètre prédéfini Save Document Preset Enregistrer le paramètre prédéfini du document Save Preset… Enregistrer le paramètre prédéfini… + Save Summary… Enregistrer le résumé… Save Print Preset Enregistrer le paramètre prédéfini d’impression Save Recovery Data Enregistrer les données de récupération Save Save for Web Preset Enregistrer le paramètre prédéfini d’Enregistrer pour le web @@ -3682,6 +3745,7 @@ digits Malayalam Malayalam Show Modified Afficher les éléments modifiés Show Note Afficher la note Show Options Afficher les options + Show on Shape Creation Afficher à la création de formes Show Recent Colors Afficher les couleurs récentes Toggle RGB Percent Basculer RVB en pourcentage Show Original Path Afficher le tracé d’origine @@ -3709,6 +3773,7 @@ digits Malayalam Malayalam Show Thumbnails Afficher les vignettes Show Tile Edge Afficher le bord du carreau Show Tints/Shades Afficher les teintes claires/foncées + Show Tool Cards Afficher les fiches d’outils Show Tool Tips Afficher les info-bulles Show Transparency Grid Afficher la grille de transparence Show Video Rulers Afficher les règles vidéo @@ -3792,6 +3857,8 @@ digits Malayalam Malayalam Outlines Contours Outlines with Source Image Tracés avec l’image source Source Image Image source + Split View Vue partagée + Divider Séparateur Press and hold to view the source image Maintenez le bouton enfoncé pour afficher l’image source Image Trace View Affichage de la vectorisation de l’image Snap Options Options de magnétisme @@ -4242,6 +4309,8 @@ digits Malayalam Malayalam Unembed… Annuler l’incorporation… Ungroup Dissocier Ungroup Color Group Dissocier le groupe de couleurs + Color Group Options Options du groupe de couleurs + Color Group Options… Options du groupe de couleurs… Unicode Unicode Unicode (UTF-16) Unicode (UTF-16) Unicode (UTF-8) Unicode (UTF-8) @@ -5035,6 +5104,7 @@ liquify-list-end {0}, {1} {0} et {1} @msg a freeform gradient keeps at least one point un dégradé de forme libre garde au moins un point @msg a gradient needs at least two stops un dégradé doit avoir au moins deux étapes de dégradé @msg a graphic style named `{to}` already exists un style graphique nommé `{to}` existe déjà +@msg a swatch or color group named `{name}` already exists une nuance ou un groupe de couleurs nommé `{name}` existe déjà @msg a key object sits on that point un objet clé se trouve sur ce point @msg a page is missing une page est manquante @msg a page out of range une page hors limites @@ -5176,6 +5246,11 @@ liquify-list-end {0}, {1} {0} et {1} @msg no anchor points selected aucun point d’ancrage sélectionné @msg `points` must be two or three [x, y] pairs of numbers `points` doit contenir deux ou trois paires de nombres [x, y] @msg direct-select two or three anchor points, or give `points` sélectionnez deux ou trois points d’ancrage avec l’outil Sélection directe, ou indiquez `points` +@msg the path is straight there, so no circle matches its curvature le tracé est droit à cet endroit, donc aucun cercle ne correspond à sa courbure +@msg the path has a cusp there, so it has no single curvature le tracé a un point de rebroussement à cet endroit, donc il n’a pas de courbure unique +@msg the path has a corner there, so it has no single curvature le tracé forme un angle à cet endroit, donc il n’a pas de courbure unique +@msg a guide has no curvature circle un repère n’a pas de cercle de courbure +@msg the circle that matches the path there would reach past the canvas le cercle qui correspond au tracé à cet endroit dépasserait la zone de travail @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 @@ -5432,6 +5507,7 @@ liquify-list-end {0}, {1} {0} et {1} @msg the PDF is password-protected: give its password le PDF est protégé par un mot de passe : indiquez-le @msg the PDF password is wrong le mot de passe du PDF est incorrect @msg the Save PDF dialog didn't open la boîte de dialogue Enregistrer au format PDF ne s’est pas ouverte +@msg the Save PDF dialog is not open la boîte de dialogue Enregistrer au format PDF n’est pas ouverte @msg the WMF header is damaged l’en-tête WMF est endommagé @msg the art could not be sampled impossible d’échantillonner l’illustration @msg the art has no bounds l’illustration n’a pas de limites @@ -5653,6 +5729,7 @@ variable-list-end {0}, {1} {0} et {1} @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 +@msg give only one of `index`, `indices` and `t` indiquez un seul de `index`, `indices` et `t` @msg column must be true or a number from 1 column doit être true ou un nombre à partir de 1 @msg x and y must both be numbers x et y doivent tous deux être des nombres @msg "{0}" is not a colour: write it as #rrggbb « {0} » n’est pas une couleur : écrivez-la sous la forme #rrggbb @@ -5820,6 +5897,49 @@ variable-list-end {0}, {1} {0} et {1} @msg the PSD file's layer groups are nested too deeply les groupes de calques du fichier PSD sont imbriqués trop profondément @msg a layer of the PSD file is too large to read un calque du fichier PSD est trop grand pour être lu @msg the PSD file's layers take more memory to read than allowed les calques du fichier PSD demandent plus de mémoire que permis pour être lus +@msg the file is no longer loaded le fichier n’est plus chargé +@msg the layers can't be read ({e}): the file was placed as its merged image les calques ne peuvent pas être lus ({e}) : le fichier a été importé comme son image fusionnée +@msg 1 type layer came in as pixels: the text isn't editable 1 calque de texte a été importé en pixels : le texte n’est pas modifiable +@msg {n} type layers came in as pixels: the text isn't editable {n} calques de texte ont été importés en pixels : le texte n’est pas modifiable +@msg 1 adjustment layer was not applied 1 calque de réglage n’a pas été appliqué +@msg {n} adjustment layers were not applied {n} calques de réglage n’ont pas été appliqués +@msg 1 fill layer was not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels) 1 calque de remplissage n’a pas été dessiné (un remplissage de dégradé ou de motif, une couleur illisible ou une forme qui ne stocke aucun pixel) +@msg {n} fill layers were not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels) {n} calques de remplissage n’ont pas été dessinés (un remplissage de dégradé ou de motif, une couleur illisible ou une forme qui ne stocke aucun pixel) +@msg the layer effects of 1 layer weren't drawn les effets de calque de 1 calque n’ont pas été dessinés +@msg the layer effects of {n} layers weren't drawn les effets de calque de {n} calques n’ont pas été dessinés +@msg the vector masks of 1 layer weren't applied les masques vectoriels de 1 calque n’ont pas été appliqués +@msg the vector masks of {n} layers weren't applied les masques vectoriels de {n} calques n’ont pas été appliqués +@msg the knockout of 1 layer wasn't applied la défonce de 1 calque n’a pas été appliquée +@msg the knockout of {n} layers wasn't applied la défonce de {n} calques n’a pas été appliquée +@msg 1 layer was left out (hidden layers and the layers clipped to them) 1 calque a été omis (calques masqués et calques écrêtés sur eux) +@msg {n} layers were left out (hidden layers and the layers clipped to them) {n} calques ont été omis (calques masqués et calques écrêtés sur eux) +@msg 1 layer clipped to a fill layer that wasn't drawn was left out 1 calque écrêté sur un calque de remplissage non dessiné a été omis +@msg {n} layers clipped to fill layers that weren't drawn were left out {n} calques écrêtés sur des calques de remplissage non dessinés ont été omis +@msg layers in blend modes VectorCraft doesn't have ({modes}) were merged with the layers below them les calques dans des modes de fusion que VectorCraft n’a pas ({modes}) ont été fusionnés avec les calques situés en dessous +@msg 1 layer in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed 1 calque dans un mode de fusion que VectorCraft n’a pas a été importé en Normal : la fusion demande plus de mémoire que permis +@msg {n} layers in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed {n} calques dans des modes de fusion que VectorCraft n’a pas ont été importés en Normal : la fusion demande plus de mémoire que permis +@msg 1 layer clipped to the layer below came in unclipped: the merge needs more memory than allowed 1 calque écrêté sur le calque inférieur a été importé sans écrêtage : la fusion demande plus de mémoire que permis +@msg {n} layers clipped to the layer below came in unclipped: the merge needs more memory than allowed {n} calques écrêtés sur le calque inférieur ont été importés sans écrêtage : la fusion demande plus de mémoire que permis +@msg hiddenLayers applies to a PSD file placed with layers: true hiddenLayers s’applique à un fichier PSD importé avec layers: true +@msg importSlices: a linked PSD file is placed as its flat image; give link: false to embed it with its slices importSlices : un fichier PSD lié est importé comme son image aplatie ; indiquez link: false pour l’incorporer avec ses tranches +@msg layers: a linked PSD file is placed as its flat image; leave link out or give link: false layers : un fichier PSD lié est importé comme son image aplatie ; omettez link ou indiquez link: false +@msg the slices can't be read ({e}) and were left out les tranches ne peuvent pas être lues ({e}) et ont été omises +@msg 1 slice lies outside the canvas or has no size and was left out 1 tranche se trouve hors de la zone de travail ou n’a pas de taille et a été omise +@msg {n} slices lie outside the canvas or have no size and were left out {n} tranches se trouvent hors de la zone de travail ou n’ont pas de taille et ont été omises +@msg 1 slice would lie outside the canvas and was left out 1 tranche se trouverait hors de la zone de travail et a été omise +@msg {n} slices would lie outside the canvas and were left out {n} tranches se trouveraient hors de la zone de travail et ont été omises +@msg the slices' descriptor holds too many values le descripteur des tranches contient trop de valeurs +@msg the slices' descriptor has a version other than 16 le descripteur des tranches a une version autre que 16 +@msg the slices are stored in version {v}, which isn't read les tranches sont enregistrées en version {v}, qui n’est pas lue +@msg the file has {count} slices, more than the {MAX_SLICES} read le fichier a {count} tranches, plus que les {MAX_SLICES} lues +@msg the slices' descriptor has no list of slices le descripteur des tranches n’a pas de liste de tranches +@msg the slices' descriptor lists something other than a slice le descripteur des tranches liste autre chose qu’une tranche +@msg a slice in the slices' descriptor has no bounds une tranche du descripteur des tranches n’a pas de limites +@msg a slice's bounds in the slices' descriptor aren't numbers les limites d’une tranche du descripteur des tranches ne sont pas des nombres +@msg a text in the slices has more than the {MAX_TEXT} characters read un texte des tranches a plus que les {MAX_TEXT} caractères lus +@msg the slices' descriptor nests too deep le descripteur des tranches est imbriqué trop profondément +@msg the slices' descriptor has a reference of an unknown kind ({_1}) le descripteur des tranches a une référence d’un genre inconnu ({_1}) +@msg the slices' descriptor has a value of an unknown type ({_1}) le descripteur des tranches a une valeur d’un type inconnu ({_1}) @msg the layers can't be read ({e}): the file opened as its merged image les calques ne peuvent pas être lus ({e}) : le fichier a été ouvert comme son image fusionnée @msg {depth}-bit PSD files in this colour mode can't be read les fichiers PSD {depth} bits dans ce mode colorimétrique ne peuvent pas être lus @msg the PSD file is cut short le fichier PSD est tronqué @@ -5847,6 +5967,25 @@ variable-list-end {0}, {1} {0} et {1} Preserve Embedded Profiles Conserver les profils incorporés Convert to Working Space Convertir en espace de travail Preserve Numbers Conserver les valeurs numériques + Profile Mismatches: Non-concordance des profils : + Ask When Opening Demander à l’ouverture + Ask When Pasting Demander au collage + Missing Profiles: Profils manquants : + Embedded Profile Mismatch Non-concordance du profil incorporé + Missing Profile Profil manquant + Paste Profile Mismatch Non-concordance de profil au collage + “{name}” is not tagged with a {model} profile. « {name} » n’a pas de profil {model}. + “{name}” is tagged with the {model} profile “{profile}”, which is not the {model} working space “{working}”. « {name} » a le profil {model} « {profile} », qui n’est pas l’espace de travail {model} « {working} ». + Use the embedded profile Utiliser le profil incorporé + Convert the colors to the working space Convertir les couleurs dans l’espace de travail + Discard the embedded profile Supprimer le profil incorporé + Leave as is Laisser tel quel + Assign the working space Attribuer l’espace de travail + Assign profile: Attribuer le profil : + Preserve the color numbers Conserver les valeurs des couleurs + Convert to keep the colors' appearance Convertir pour conserver l’aspect des couleurs +@msg `{path}` goes with `{key}`: "assign" only `{path}` ne s’utilise qu’avec `{key}` égal à "assign" + The pasted colors come from a document whose {model} profile is “{from}”; this document's is “{to}”. Les couleurs collées proviennent d’un document dont le profil {model} est « {from} » ; celui de ce document est « {to} ». Texture Texture Craquelure… Craquelure… Grain… Grain… @@ -8124,6 +8263,8 @@ breakText Glyphs Glyphes # Path Precision Tools add-on: Tangent Circle. Tangent Circle… Cercle tangent… Tangent Circle Cercle tangent + Tangent Circle Tool Outil Cercle tangent + No tangent circle here Aucun cercle tangent ici Circle: Cercle : @msg `ids` names an object twice `ids` désigne deux fois le même objet @msg select two or three paths or compound paths sélectionnez deux ou trois tracés ou tracés transparents @@ -8139,6 +8280,16 @@ breakText Glyphs Glyphes @msg `circle` is past the last circle found ({found}) `circle` dépasse le dernier cercle trouvé ({found}) @msg object {value} is not a path or compound path l’objet {value} n’est ni un tracé ni un tracé transparent @msg these shapes are too small to measure ces formes sont trop petites pour être mesurées +# Path Precision Tools add-on: Add Bounding Rectangle and Add Bounding Circle. + Add Bounding Rectangle Ajouter un rectangle englobant + Add Bounding Circle Ajouter un cercle englobant + Add Bounding Rectangle… Ajouter un rectangle englobant… + Add Bounding Circle… Ajouter un cercle englobant… + One per Object Une par objet +@msg nothing to enclose rien à entourer +@msg `offset` must be 0 or more `offset` doit être supérieur ou égal à 0 +@msg the shape would have no size la forme n’aurait aucune taille +@msg the shape would reach past the edge of the canvas la forme dépasserait le bord de la zone de travail # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Outils de document Save a Timestamped Copy Enregistrer une copie horodatée @@ -10434,9 +10585,57 @@ breakText Glyphs Glyphes @msg A joint does not close by {gap} pt. Un joint ne se ferme pas, avec un écart de {gap} pt. @msg Two panels pass through each other. Deux panneaux se traversent. @msg {_1} × {_2} pixels is too large for GIF (at most 65535 pixels a side): lower the resolution {_1} × {_2} pixels, c’est trop grand pour le GIF (65535 pixels par côté au plus) : réduisez la résolution + Paper Cutouts Découpes de papier + Coral Layers Couches corail + Mint Layers Couches menthe + Midnight Layers Couches de minuit + Sunflower Sheet Feuille tournesol + Rose Layers Couches rose + Monochrome Stack Pile monochrome +# Tool cards (General › Show Tool Cards): one sentence on what each tool does. + Shows a card with what a toolbar tool does and what its keys do instead of its tip; it needs Show Tool Tips. Affiche une fiche indiquant ce que font un outil de la barre et ses touches, à la place de son info-bulle. Nécessite Afficher les info-bulles. + Selects whole objects and groups to move, resize or rotate them. Sélectionne des objets et des groupes entiers pour les déplacer, les redimensionner ou les faire pivoter. + Selects anchor points and path segments to reshape a path. Sélectionne des points d’ancrage et des segments de tracé pour modifier la forme d’un tracé. + Draws paths point by point, with straight segments and smooth curves. Dessine des tracés point par point, avec des segments droits et des courbes lisses. + Draws smooth curves through the points you click. Dessine des courbes lisses passant par les points sur lesquels vous cliquez. + Adds text at a point, or in a frame you drag. Ajoute du texte en un point ou dans un cadre que vous faites glisser. + Draws rectangles and squares. Dessine des rectangles et des carrés. + Draws rectangles with rounded corners. Dessine des rectangles aux angles arrondis. + Draws ellipses and circles. Dessine des ellipses et des cercles. + Draws polygons with sides of equal length. Dessine des polygones dont les côtés sont de même longueur. + Draws stars. Dessine des étoiles. + Turns objects around a reference point. Fait pivoter des objets autour d’un point de référence. + Flips objects across an axis through a reference point. Retourne des objets par rapport à un axe passant par un point de référence. + Resizes objects from a reference point. Redimensionne des objets à partir d’un point de référence. + Slants objects from a reference point. Incline des objets à partir d’un point de référence. + Moves the view of the document. Déplace la vue du document. + Magnifies or reduces the view. Agrandit ou réduit la vue. + Copies the color and other attributes of one object to the selection. Copie la couleur et les autres attributs d’un objet vers la sélection. + Sets the direction and length of a gradient. Définit la direction et la longueur d’un dégradé. + Creates, selects and resizes artboards. Crée, sélectionne et redimensionne des plans de travail. + Changes the width of a stroke along its length. Modifie l’épaisseur d’un contour sur sa longueur. + Bends art by dragging pins placed on it. Déforme l’illustration en faisant glisser des épingles placées dessus. + Pushes the outlines of paths in the direction you drag. Pousse les contours des tracés dans la direction du glissement. + Twists the outlines of paths into swirls. Tord les contours des tracés en tourbillons. + Pulls the outlines of paths in toward the brush. Resserre les contours des tracés vers le pinceau. + Pushes the outlines of paths out from the brush. Gonfle les contours des tracés à partir du pinceau. + Adds curved details along the outlines of paths. Ajoute des détails arrondis le long des contours des tracés. + Adds spiky details along the outlines of paths. Ajoute des détails pointus le long des contours des tracés. + Adds wrinkles along the outlines of paths. Ajoute des plis le long des contours des tracés. + Moves, copies and resizes objects on the perspective grid. Déplace, copie et redimensionne des objets sur la grille de perspective. + Makes a series of steps between two or more objects. Crée une série d’étapes entre deux objets ou plus. + Places dimension lines that show measured lengths. Place des lignes de cote qui indiquent des longueurs mesurées. Dashed Arrow Flèche en pointillés + Fine Stipple Pointillé fin + Dense Stipple Pointillé dense + Soft Stipple Pointillé doux + Bold Stipple Pointillé marqué Pressure Sensitive Sensible à la pression Flex Ribbon Ruban souple Pulse Stroke Trait pulsé Round Flow Flux rond Chisel Flow Flux biseauté + +# #5804 native-picked raster editor (draft translations; native review welcome). + Edit Original with: Modifier l’original avec : +file-filter Applications Applications diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 85499ca847..578bfbe963 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -492,6 +492,25 @@ Preserve Embedded Profiles એમ્બેડ કરેલી પ્રોફાઇલ જાળવો Convert to Working Space કાર્યકારી સ્પેસમાં રૂપાંતરિત કરો Preserve Numbers સંખ્યાઓ જાળવો + Profile Mismatches: પ્રોફાઇલ મેળ ન ખાવા: + Ask When Opening ખોલતી વખતે પૂછો + Ask When Pasting પેસ્ટ કરતી વખતે પૂછો + Missing Profiles: ખૂટતી પ્રોફાઇલ: + Embedded Profile Mismatch એમ્બેડ કરેલી પ્રોફાઇલ મેળ ખાતી નથી + Missing Profile પ્રોફાઇલ ખૂટે છે + Paste Profile Mismatch પેસ્ટ કરતી વખતે પ્રોફાઇલ મેળ ખાતી નથી + “{name}” is not tagged with a {model} profile. “{name}” પાસે કોઈ {model} પ્રોફાઇલ નથી. + “{name}” is tagged with the {model} profile “{profile}”, which is not the {model} working space “{working}”. “{name}” પાસે {model} પ્રોફાઇલ “{profile}” છે, જે {model} કાર્યકારી સ્પેસ “{working}” નથી. + Use the embedded profile એમ્બેડ કરેલી પ્રોફાઇલ વાપરો + Convert the colors to the working space રંગોને કાર્યકારી સ્પેસમાં રૂપાંતરિત કરો + Discard the embedded profile એમ્બેડ કરેલી પ્રોફાઇલ કાઢી નાખો + Leave as is જેમ છે તેમ રહેવા દો + Assign the working space કાર્યકારી સ્પેસ સોંપો + Assign profile: પ્રોફાઇલ સોંપો: + Preserve the color numbers રંગોની સંખ્યાઓ જાળવો + Convert to keep the colors' appearance રંગોનો દેખાવ જાળવવા રૂપાંતરિત કરો +@msg `{path}` goes with `{key}`: "assign" only `{path}` ફક્ત `{key}`: "assign" સાથે જ વપરાય છે + The pasted colors come from a document whose {model} profile is “{from}”; this document's is “{to}”. પેસ્ટ કરેલા રંગો એવા દસ્તાવેજમાંથી આવે છે જેની {model} પ્રોફાઇલ “{from}” છે; આ દસ્તાવેજની “{to}” છે. CSS Properties CSS ગુણધર્મો Calligraphic Brush કેલિગ્રાફિક બ્રશ Calligraphic Brush Options કેલિગ્રાફિક બ્રશ વિકલ્પો @@ -576,6 +595,9 @@ Chop Design ચૉપ ડિઝાઇન Chosen: {n} of {total} પસંદ કરેલ: {total} માંથી {n} Chrome… ક્રોમ… + Curvature Circle Tool વક્રતા વર્તુળ ટૂલ + Cusp અણી + Straight segment સીધો સેગમેન્ટ Circle વર્તુળ Circle Tool વર્તુળ ટૂલ Circle too large વર્તુળ ખૂબ મોટું છે @@ -890,6 +912,12 @@ Cut Path at Selected Anchor Points પસંદ કરેલા એન્કર પોઇન્ટ પર પાથ કાપો Cutout… કટઆઉટ… Czech ચેક + PSD Import Options PSD આયાત વિકલ્પો + Place PSD PSD મૂકો + Convert Layers to Objects લેયર્સને ઑબ્જેક્ટમાં ફેરવો + Import Hidden Layers છુપાયેલા લેયર્સ આયાત કરો + Flatten Layers to a Single Image લેયર્સને એક જ ઇમેજમાં ફ્લેટન કરો + Import Slices સ્લાઇસ આયાત કરો DXF Import Options DXF આયાત વિકલ્પો DXF Info DXF માહિતી DXF Options DXF વિકલ્પો @@ -1140,6 +1168,15 @@ Draw દોરો Draw Dashed Lines as Solid Lines ડેશ્ડ રેખાઓ સોલિડ રેખાઓ તરીકે દોરો Draw Hidden Faces છુપાયેલી સપાટીઓ દોરો + Map Art… આર્ટવર્ક મેપ કરો… + Map Art આર્ટવર્ક મેપ કરો + First Surface પ્રથમ સપાટી + Previous Surface પાછલી સપાટી + Next Surface આગલી સપાટી + Last Surface છેલ્લી સપાટી + Scale to Fit ફિટ થાય તેમ સ્કેલ કરો + Shade Artwork આર્ટવર્કને છાયા આપો + Invisible Geometry અદૃશ્ય ભૂમિતિ Draw in Perspective પર્સ્પેક્ટિવમાં દોરો Draw: દોરો: Drawer menu ડ્રોઅર મેનુ @@ -1726,6 +1763,8 @@ Hide Bounding Box બાઉન્ડિંગ બૉક્સ છુપાવો Hide Code કોડ છુપાવો Hide Corner Widget કૉર્નર વિજેટ છુપાવો + Hide Shape Widgets શેપ વિજેટ્સ છુપાવો + Show Shape Widgets શેપ વિજેટ્સ બતાવો Hide Corner Widget for angles greater than આથી વધુ એંગલ માટે કૉર્નર વિજેટ છુપાવો Hide Edges કિનારીઓ છુપાવો Hide Font Height Options ફોન્ટ ઊંચાઈ વિકલ્પો છુપાવો @@ -2669,6 +2708,8 @@ Overprint and Transparency Flattener Options ઓવરપ્રિન્ટ અને પારદર્શિતા ફ્લેટનર વિકલ્પો Custom… કસ્ટમ… Custom Transparency Flattener Options કસ્ટમ પારદર્શિતા ફ્લેટનર વિકલ્પો + The PDF preset keeps the flattener preset but not the Custom… settings. PDF પ્રીસેટ ફ્લેટનર પ્રીસેટ રાખે છે, પરંતુ કસ્ટમ… સેટિંગ્સ નહીં. + PDF 1.3 files clip rasterized areas to their regions, and Overprint sets whether overprints are kept. PDF 1.3 ફાઇલો રાસ્ટરાઇઝ્ડ વિસ્તારોને તેમના પ્રદેશો સુધી ક્લિપ કરે છે, અને ઓવરપ્રિન્ટ નક્કી કરે છે કે ઓવરપ્રિન્ટ્સ જાળવવામાં આવે કે નહીં. EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS માં આલ્ફા પારદર્શિતા નથી, અને ઓવરપ્રિન્ટ્સ નક્કી કરે છે કે ઓવરપ્રિન્ટ્સ જાળવવામાં આવે કે નહીં. Overprint: ઓવરપ્રિન્ટ: Overprints: ઓવરપ્રિન્ટ્સ: @@ -3112,6 +3153,12 @@ @msg The paths overlap, so they have no internal tangents પાથ એકબીજા પર ચઢેલા છે, તેથી તેમની કોઈ આંતરિક સ્પર્શરેખા નથી @msg One path lies inside the other, so they have no internal tangents એક પાથ બીજાની અંદર છે, તેથી તેમની કોઈ આંતરિક સ્પર્શરેખા નથી @msg The point lies inside the path, so it has no tangents બિંદુ પાથની અંદર છે, તેથી તેની કોઈ સ્પર્શરેખા નથી +# Path Precision Tools add-on: Add Bounding Rectangle and Add Bounding Circle. + Add Bounding Rectangle બાઉન્ડિંગ લંબચોરસ ઉમેરો + Add Bounding Circle બાઉન્ડિંગ વર્તુળ ઉમેરો + Add Bounding Rectangle… બાઉન્ડિંગ લંબચોરસ ઉમેરો… + Add Bounding Circle… બાઉન્ડિંગ વર્તુળ ઉમેરો… + One per Object દરેક ઑબ્જેક્ટ માટે એક Remove Guide ગાઇડ દૂર કરો Remove Item આઇટમ દૂર કરો Remove JavaScript File JavaScript ફાઇલ દૂર કરો @@ -3260,6 +3307,7 @@ A live rectangle's properties show one Corner Radius field for all four corners; off, each corner has its own field. લાઇવ લંબચોરસના ગુણધર્મો ચારેય ખૂણા માટે ખૂણાની ત્રિજ્યાનું એક જ ફીલ્ડ બતાવે છે; બંધ હોય ત્યારે દરેક ખૂણાનું પોતાનું ફીલ્ડ હોય છે. What edits in the Transform panel transform: the object, its pattern tiles or both; Default follows Transform Pattern Tiles. ટ્રાન્સફોર્મ પેનલમાંના ફેરફારો શું ટ્રાન્સફોર્મ કરે છે: ઑબ્જેક્ટ, તેની પૅટર્ન ટાઇલ્સ કે બંને; ડિફૉલ્ટ પૅટર્ન ટાઇલ્સ ટ્રાન્સફોર્મ કરો ને અનુસરે છે. With one symbol instance selected, the Transform panel uses the symbol's registration point as its reference point. એક સિમ્બોલ ઇન્સ્ટન્સ પસંદ હોય ત્યારે ટ્રાન્સફોર્મ પેનલ સિમ્બોલના રજિસ્ટ્રેશન પોઇન્ટને સંદર્ભ પોઇન્ટ તરીકે વાપરે છે. + Drawing a rectangle, ellipse, polygon, star or line opens the Transform panel if it is closed. લંબચોરસ, લંબવર્તુળ, બહુકોણ, તારો કે રેખા દોરવાથી ટ્રાન્સફોર્મ પેનલ બંધ હોય તો ખૂલે છે. Darkens the canvas outside the artboards while the Artboard tool is active. આર્ટબોર્ડ ટૂલ સક્રિય હોય ત્યારે આર્ટબોર્ડ બહારનો કેનવાસ ઘાટો કરે છે. With Fade Region Outside Artboard on, the area outside the artboards stays dark while you drag with the Artboard tool. આર્ટબોર્ડ બહારનો વિસ્તાર ઝાંખો કરો ચાલુ હોય ત્યારે, આર્ટબોર્ડ ટૂલથી ખેંચતી વખતે આર્ટબોર્ડ બહારનો વિસ્તાર ઘાટો રહે છે. How near, in pixels, the pointer must be to an object, anchor or handle for a click to select it. ક્લિક કોઈ ઑબ્જેક્ટ, એન્કર પોઇન્ટ કે હૅન્ડલને પસંદ કરે તે માટે પોઇન્ટર તેનાથી કેટલા પિક્સેલ નજીક હોવો જોઈએ. @@ -3456,6 +3504,7 @@ Save Perspective Grid Preset પર્સ્પેક્ટિવ ગ્રિડ પ્રીસેટ સાચવો Save Preset પ્રીસેટ સાચવો Save Preset… પ્રીસેટ સાચવો… + Save Summary… સારાંશ સાચવો… Save Print Preset પ્રિન્ટ પ્રીસેટ સાચવો Save Recovery Data પુનઃપ્રાપ્તિ ડેટા સાચવો Save Save for Web Preset વેબ માટેનો પ્રીસેટ સાચવો @@ -3800,6 +3849,7 @@ Show Live Paint Gaps લાઇવ પેઇન્ટ ગેપ બતાવો Show Note નોંધ બતાવો Show Options વિકલ્પો બતાવો + Show on Shape Creation શેપ બનાવતી વખતે બતાવો Show Original Path મૂળ પાથ બતાવો Show Package પૅકેજ બતાવો Show Panel પેનલ બતાવો @@ -3824,6 +3874,7 @@ Show Tile Edge ટાઇલ કિનારી બતાવો Show Tints/Shades ટિન્ટ/શેડ બતાવો Show Tool Group Labels ટૂલ ગ્રૂપ લેબલ બતાવો + Show Tool Cards ટૂલ કાર્ડ બતાવો Show Tool Tips ટૂલ ટિપ્સ બતાવો Show Toolbar ટૂલબાર બતાવો Show Transparency Grid પારદર્શિતા ગ્રિડ બતાવો @@ -4093,6 +4144,17 @@ Symbol Screener Tool સિમ્બોલ સ્ક્રીનર ટૂલ Symbol Scruncher સિમ્બોલ સ્ક્રન્ચર Symbol Scruncher Tool સિમ્બોલ સ્ક્રન્ચર ટૂલ + Tool: ટૂલ: + Symbol Set Density સિમ્બોલ સેટ ઘનતા + Symbol Sprayer Options સિમ્બોલ સ્પ્રેયર વિકલ્પો + Scrunch: સ્ક્રન્ચ: + Spin: સ્પિન: + Screen: સ્ક્રીન: + Stain: સ્ટેઇન: + Symbol Sizer Options સિમ્બોલ સાઇઝર વિકલ્પો + Proportional Resizing પ્રમાણસર કદ બદલવું + Resizing Affects Density કદ બદલવાથી ઘનતા બદલાય છે + Show Brush Size and Intensity બ્રશનું કદ અને તીવ્રતા બતાવો Symbol Set Density: સિમ્બોલ સેટ ઘનતા: Symbol Shifter સિમ્બોલ શિફ્ટર Symbol Shifter Tool સિમ્બોલ શિફ્ટર ટૂલ @@ -4120,6 +4182,8 @@ Tabs ટૅબ Tamil તમિલ Tangent Circle સ્પર્શક વર્તુળ + Tangent Circle Tool સ્પર્શક વર્તુળ ટૂલ + No tangent circle here અહીં કોઈ સ્પર્શક વર્તુળ નથી Tangent Circle… સ્પર્શક વર્તુળ… Taper ટેપર Target લક્ષ્ય @@ -4340,6 +4404,8 @@ Unembed… એમ્બેડ દૂર કરો… Ungroup અનગ્રુપ કરો Ungroup Color Group રંગ ગ્રુપ અનગ્રુપ કરો + Color Group Options રંગ ગ્રુપ વિકલ્પો + Color Group Options… રંગ ગ્રુપ વિકલ્પો… Uniform યુનિફોર્મ Uniformly Scaled સમાન રીતે સ્કેલ કરેલ Unite યુનાઇટ @@ -4615,6 +4681,9 @@ Box Channel બૉક્સ ચેનલ Color box રંગ બૉક્સ Color Wheel Options રંગ વ્હીલ વિકલ્પો + Show Harmony હાર્મની બતાવો + Harmony Rule હાર્મની નિયમ + Harmony color હાર્મની રંગ {name} (spot) {name} (સ્પૉટ) {pages} in all, {count} per copy કુલ {pages}, પ્રતિ નકલ {count} {page} of {count} {count} માંથી {page} @@ -4774,6 +4843,9 @@ antiAlias Sharp શાર્પ Edit Arrowheads… એરોહેડ્સ સંપાદિત કરો… Reload Arrowheads એરોહેડ્સ ફરી લોડ કરો Color Theme Picker કલર થીમ પિકર + Undo Changes ફેરફારો પૂર્વવત્ કરો + Redo Changes ફેરફારો ફરીથી કરો +@msg Recolor Artwork is not open કલાકૃતિનો રંગ બદલો ખુલ્લું નથી Click or drag across the art to pick its colors; Shift adds more આર્ટના રંગો પસંદ કરવા તેના પર ક્લિક કરો અથવા ડ્રેગ કરો; Shiftથી વધુ ઉમેરાય છે Prominent Colors મુખ્ય રંગો Save All Colors બધા રંગો સાચવો @@ -4965,6 +5037,9 @@ antiAlias Sharp શાર્પ embedding for preview and print પ્રીવ્યૂ અને પ્રિન્ટ માટે એમ્બેડ કરવાની મંજૂરી embedding allowed એમ્બેડ કરવાની મંજૂરી છે {file}; {embedding} {file}; {embedding} + unknown type અજ્ઞાત પ્રકાર + {type}; {uses} {type}; {uses} +@plural {n} use|{n} uses {n} ઉપયોગ|{n} ઉપયોગ substituted: shown in {family} {style} ({detail}) બદલાયેલ: {family} {style}માં બતાવ્યું ({detail}) missing: shown in {family} {style} ગુમ: {family} {style}માં બતાવ્યું missing ગુમ @@ -5433,6 +5508,50 @@ swatch [Registration] [રજિસ્ટ્રેશન] Standard Single-line Composer સ્ટાન્ડર્ડ સિંગલ-લાઇન કમ્પોઝર Standard Every-line Composer સ્ટાન્ડર્ડ એવરી-લાઇન કમ્પોઝર @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer આમાંથી એક હોવું જોઈએ: "singleLine", "everyLine", "standardSingleLine" અથવા "standardEveryLine" + Fine Stipple સૂક્ષ્મ બિંદુ છાંયાંકન + Dense Stipple ઘન બિંદુ છાંયાંકન + Soft Stipple નરમ બિંદુ છાંયાંકન + Bold Stipple ઘાટું બિંદુ છાંયાંકન + Paper Cutouts કાગળના કટઆઉટ + Coral Layers કોરલ સ્તરો + Mint Layers મિન્ટ સ્તરો + Midnight Layers મધ્યરાત્રિના સ્તરો + Sunflower Sheet સૂર્યમુખી શીટ + Rose Layers ગુલાબી સ્તરો + Monochrome Stack એકરંગી થપ્પો +# Tool cards (General › Show Tool Cards): one sentence on what each tool does. + Shows a card with what a toolbar tool does and what its keys do instead of its tip; it needs Show Tool Tips. ટૂલબારનું ટૂલ અને તેની કીઓ શું કરે છે તે ટિપને બદલે કાર્ડમાં બતાવે છે; ટૂલ ટિપ્સ બતાવો ચાલુ હોવું જરૂરી છે. + Selects whole objects and groups to move, resize or rotate them. આખા ઑબ્જેક્ટ અને જૂથો પસંદ કરે છે, જેથી તેમને ખસેડી, તેમનું કદ બદલી કે ફેરવી શકાય. + Selects anchor points and path segments to reshape a path. પાથનો આકાર બદલવા માટે એન્કર બિંદુઓ અને પાથ સેગમેન્ટ પસંદ કરે છે. + Draws paths point by point, with straight segments and smooth curves. સીધા સેગમેન્ટ અને સરળ વળાંકો સાથે બિંદુ-દર-બિંદુ પાથ દોરે છે. + Draws smooth curves through the points you click. તમે ક્લિક કરો તે બિંદુઓમાંથી પસાર થતા સરળ વળાંકો દોરે છે. + Adds text at a point, or in a frame you drag. કોઈ બિંદુ પર અથવા તમે ખેંચો તે ફ્રેમમાં ટેક્સ્ટ ઉમેરે છે. + Draws rectangles and squares. લંબચોરસ અને ચોરસ દોરે છે. + Draws rectangles with rounded corners. ગોળ ખૂણાવાળા લંબચોરસ દોરે છે. + Draws ellipses and circles. લંબવર્તુળ અને વર્તુળ દોરે છે. + Draws polygons with sides of equal length. સરખી લંબાઈની બાજુઓવાળા બહુકોણ દોરે છે. + Draws stars. તારા દોરે છે. + Turns objects around a reference point. ઑબ્જેક્ટને સંદર્ભ બિંદુની આસપાસ ફેરવે છે. + Flips objects across an axis through a reference point. ઑબ્જેક્ટને સંદર્ભ બિંદુમાંથી પસાર થતી ધરી પર ઉલટાવે છે. + Resizes objects from a reference point. સંદર્ભ બિંદુથી ઑબ્જેક્ટનું કદ બદલે છે. + Slants objects from a reference point. સંદર્ભ બિંદુથી ઑબ્જેક્ટને ત્રાંસા કરે છે. + Moves the view of the document. દસ્તાવેજના દૃશ્યને ખસેડે છે. + Magnifies or reduces the view. દૃશ્યને મોટું અથવા નાનું કરે છે. + Copies the color and other attributes of one object to the selection. એક ઑબ્જેક્ટનો રંગ અને અન્ય લક્ષણો પસંદગી પર કૉપિ કરે છે. + Sets the direction and length of a gradient. ગ્રેડિયન્ટની દિશા અને લંબાઈ સેટ કરે છે. + Creates, selects and resizes artboards. આર્ટબોર્ડ બનાવે છે, પસંદ કરે છે અને તેમનું કદ બદલે છે. + Changes the width of a stroke along its length. સ્ટ્રોકની પહોળાઈ તેની લંબાઈ સાથે બદલે છે. + Bends art by dragging pins placed on it. આર્ટ પર મૂકેલી પિન ખેંચીને તેને વાળે છે. + Pushes the outlines of paths in the direction you drag. પાથની રૂપરેખાને તમે ખેંચો તે દિશામાં ધકેલે છે. + Twists the outlines of paths into swirls. પાથની રૂપરેખાને વમળોમાં મરોડે છે. + Pulls the outlines of paths in toward the brush. પાથની રૂપરેખાને બ્રશ તરફ અંદર ખેંચે છે. + Pushes the outlines of paths out from the brush. પાથની રૂપરેખાને બ્રશથી બહારની તરફ ધકેલે છે. + Adds curved details along the outlines of paths. પાથની રૂપરેખા સાથે વળાંકવાળી વિગતો ઉમેરે છે. + Adds spiky details along the outlines of paths. પાથની રૂપરેખા સાથે અણીદાર વિગતો ઉમેરે છે. + Adds wrinkles along the outlines of paths. પાથની રૂપરેખા સાથે કરચલીઓ ઉમેરે છે. + Moves, copies and resizes objects on the perspective grid. પરસ્પેક્ટિવ ગ્રિડ પર ઑબ્જેક્ટને ખસેડે છે, કૉપિ કરે છે અને તેમનું કદ બદલે છે. + Makes a series of steps between two or more objects. બે કે વધુ ઑબ્જેક્ટ વચ્ચે પગલાંની એક શ્રેણી બનાવે છે. + Places dimension lines that show measured lengths. માપેલી લંબાઈ બતાવતી પરિમાણ રેખાઓ મૂકે છે. Tap ટૂંકું દબાણ Clear Hold હોલ્ડ સાફ કરો Hold Shortcuts હોલ્ડ શોર્ટકટ diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index a69ef68b0e..facc03da31 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -843,6 +843,7 @@ antiAlias Sharp शार्प Batch Trace Folder फ़ोल्डर बैच ट्रेस करें Batch… बैच… Bearing दिशा + Stylus Wheel स्टाइलस व्हील Before Last: अंत के पहले: Begin Recording रिकॉर्डिंग शुरू करें Begin Undo Group पूर्ववत समूह शुरू करें @@ -1092,6 +1093,9 @@ antiAlias Sharp शार्प Chrome… क्रोम… Circle वृत्त Circle Tool वृत्त टूल + Curvature Circle Tool वक्रता वृत्त टूल + Cusp नुकीला बिंदु + Straight segment सीधा सेगमेंट Circle too large वृत्त बहुत बड़ा है Circle (open) सर्किल (ओपन) Circle: वृत्त: @@ -1171,6 +1175,25 @@ antiAlias Sharp शार्प Preserve Embedded Profiles एम्बेड की गई प्रोफ़ाइल बनाए रखें Convert to Working Space वर्किंग स्पेस में बदलें Preserve Numbers संख्याएँ बनाए रखें + Profile Mismatches: प्रोफ़ाइल बेमेल: + Ask When Opening खोलते समय पूछें + Ask When Pasting पेस्ट करते समय पूछें + Missing Profiles: अनुपलब्ध प्रोफ़ाइल: + Embedded Profile Mismatch एम्बेड की गई प्रोफ़ाइल बेमेल + Missing Profile प्रोफ़ाइल अनुपलब्ध + Paste Profile Mismatch पेस्ट करते समय प्रोफ़ाइल बेमेल + “{name}” is not tagged with a {model} profile. "{name}" में कोई {model} प्रोफ़ाइल नहीं है। + “{name}” is tagged with the {model} profile “{profile}”, which is not the {model} working space “{working}”. "{name}" में {model} प्रोफ़ाइल "{profile}" है, जो {model} वर्किंग स्पेस "{working}" नहीं है। + Use the embedded profile एम्बेड की गई प्रोफ़ाइल का उपयोग करें + Convert the colors to the working space रंगों को वर्किंग स्पेस में बदलें + Discard the embedded profile एम्बेड की गई प्रोफ़ाइल हटाएं + Leave as is जैसा है वैसा रहने दें + Assign the working space वर्किंग स्पेस असाइन करें + Assign profile: प्रोफ़ाइल असाइन करें: + Preserve the color numbers रंगों की संख्याएँ बनाए रखें + Convert to keep the colors' appearance रंगों का रूप बनाए रखने के लिए बदलें +@msg `{path}` goes with `{key}`: "assign" only `{path}` केवल `{key}`: "assign" के साथ उपयोग होता है + The pasted colors come from a document whose {model} profile is “{from}”; this document's is “{to}”. पेस्ट किए गए रंग ऐसे दस्तावेज़ से आए हैं जिसकी {model} प्रोफ़ाइल "{from}" है; इस दस्तावेज़ की "{to}" है। Coarse Dots मोटे बिंदु Coincidence: संयोग: Collapse Panel Group पैनल समूह संक्षिप्त करें @@ -1242,6 +1265,9 @@ antiAlias Sharp शार्प Box Channel बॉक्स चैनल Color box कलर बॉक्स Color Wheel Options कलर व्हील ऑप्शन्स + Show Harmony सद्भाव दिखाएँ + Harmony Rule सद्भाव नियम + Harmony color सद्भाव रंग Color Type: रंग का प्रकार: Color wheel कलर व्हील Color: रंग: @@ -1887,10 +1913,25 @@ antiAlias Sharp शार्प Duplication डुप्लीकेशन Dutch डच DWG (use DXF) DWG (DXF का उपयोग करें) + PSD Import Options PSD आयात ऑप्शन्स + Place PSD PSD प्लेस करें + Convert Layers to Objects लेयर्स को ऑब्जेक्ट में बदलें + Import Hidden Layers छिपी लेयर्स आयात करें + Flatten Layers to a Single Image लेयर्स को एक इमेज में फ़्लैट करें + Import Slices स्लाइस आयात करें DXF Import Options DXF आयात ऑप्शन्स DXF Info DXF जानकारी DXF Options DXF ऑप्शन्स DXF Options Dialog DXF ऑप्शन्स डायलॉग + HP-GL Options HP-GL ऑप्शन्स + HP-GL Options Dialog HP-GL ऑप्शन्स डायलॉग + Curve Tolerance: कर्व टॉलरेंस: + Origin: ओरिजिन: + Pens: पेन: + One Pen per Color हर रंग के लिए एक पेन + Pen Table पेन टेबल + Draw the Nearest Path Next अगला सबसे नज़दीकी पाथ ड्रॉ करें + Draw Inner Paths First पहले अंदर के पाथ ड्रॉ करें Dynamic Symbol डायनामिक सिंबल e.g. 1-3, 5 उदाहरण के लिए 1-3, 5 Each Design Represents: प्रत्येक डिजाइन का प्रतिनिधित्व करता है: @@ -2168,6 +2209,15 @@ antiAlias Sharp शार्प Shading Color शेडिंग रंग Black Overprint काला ओवरप्रिंट Draw Hidden Faces छिपे हुए फलक बनाएँ + Map Art… आर्टवर्क मैप करें… + Map Art आर्टवर्क मैप करें + First Surface पहली सतह + Previous Surface पिछली सतह + Next Surface अगली सतह + Last Surface अंतिम सतह + Scale to Fit फ़िट होने तक स्केल करें + Shade Artwork आर्टवर्क पर छाया दें + Invisible Geometry अदृश्य ज्यामिति Eyedropper आईड्रॉपर Eyedropper Applies: आईड्रॉपपर लागू होता है: Eyedropper Options आईड्रॉपर ऑप्शन्स @@ -2620,6 +2670,8 @@ antiAlias Sharp शार्प Hide Bounding Box बाउंडिंग बॉक्स छिपाएँ Hide Code कोड छुपाएं Hide Corner Widget हिडन कॉर्नर विजेट + Hide Shape Widgets शेप विजेट छिपाएँ + Show Shape Widgets शेप विजेट दिखाएँ Hide Corner Widget for angles greater than से अधिक कोणों के लिए छुपा कॉर्नर विजेट Hide Edges हाइड एज Hide Extension Lines एक्सटेंशन लाइन छिपाएँ @@ -2907,6 +2959,15 @@ antiAlias Sharp शार्प Keywords: कीवर्ड: Kind प्रकार Kinsoku Set किनसोकू सेट + Kinsoku Shori Settings… किनसोकू शोरी सेटिंग्स… + Kinsoku Shori Settings किनसोकू शोरी सेटिंग्स + Kinsoku Sets किनसोकू सेट सूची + Kinsoku Set Base किनसोकू सेट का आधार + Based on: इस पर आधारित: + Cannot Start Line पंक्ति शुरू नहीं कर सकते + Cannot End Line पंक्ति समाप्त नहीं कर सकते + Hanging Punctuation लटकते विराम चिह्न + Inseparable Characters अविभाज्य वर्ण Kite पतंग Knife चाकू Knockout Group नॉकआउट समूह @@ -3764,6 +3825,8 @@ antiAlias Sharp शार्प Overprint and Transparency Flattener Options ओवरप्रिंट और ट्रांसपेरेंसी फ़्लैटनर ऑप्शन्स Custom… कस्टम… Custom Transparency Flattener Options कस्टम ट्रांसपेरेंसी फ़्लैटनर ऑप्शन्स + The PDF preset keeps the flattener preset but not the Custom… settings. PDF प्रीसेट फ़्लैटनर प्रीसेट रखता है, लेकिन कस्टम… सेटिंग्स नहीं। + PDF 1.3 files clip rasterized areas to their regions, and Overprint sets whether overprints are kept. PDF 1.3 फ़ाइलें रास्टराइज़ किए गए क्षेत्रों को उनके क्षेत्रों तक क्लिप करती हैं, और ओवरप्रिंट तय करता है कि ओवरप्रिंट रखे जाएँ या नहीं। EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS में अल्फा पारदर्शिता नहीं होती, और ओवरप्रिंट तय करता है कि ओवरप्रिंट रखे जाएँ या नहीं। Overprint Black ओवरप्रिंट ब्लैक Overprint Black… ओवरप्रिंट ब्लैक… @@ -3857,6 +3920,9 @@ antiAlias Sharp शार्प embedding for preview and print पूर्वावलोकन और प्रिंट के लिए एम्बेडिंग embedding allowed एम्बेडिंग की अनुमति है {file}; {embedding} {file}; {embedding} + unknown type अज्ञात प्रकार + {type}; {uses} {type}; {uses} +@plural {n} use|{n} uses {n} उपयोग|{n} उपयोग substituted: shown in {family} {style} ({detail}) प्रतिस्थापित: {family} {style} में दिखाया गया ({detail}) missing: shown in {family} {style} अनुपलब्ध: {family} {style} में दिखाया गया missing अनुपलब्ध @@ -4506,6 +4572,9 @@ antiAlias Sharp शार्प Reset Text Transform and Scale टेक्स्ट ट्रांसफॉर्म और स्केल को रीसेट करें Reset the rows to the artwork's colors आर्टवर्क के रंग के लिए पंक्तियों को रीसेट करें Color Theme Picker रंग थीम पिकर + Undo Changes परिवर्तन पूर्ववत करें + Redo Changes परिवर्तन फिर से करें +@msg Recolor Artwork is not open Recolor Artwork खुला नहीं है Click or drag across the art to pick its colors; Shift adds more आर्टवर्क के रंग लेने के लिए उस पर क्लिक करें या खींचें; Shift और जोड़ता है Prominent Colors प्रमुख रंग Save All Colors सभी रंग सेव करें @@ -4577,6 +4646,7 @@ antiAlias Sharp शार्प A live rectangle's properties show one Corner Radius field for all four corners; off, each corner has its own field. लाइव आयत की प्रॉपर्टीज़ चारों कोनों के लिए कोने की त्रिज्या का एक ही फ़ील्ड दिखाती हैं; बंद होने पर हर कोने का अपना फ़ील्ड होता है। What edits in the Transform panel transform: the object, its pattern tiles or both; Default follows Transform Pattern Tiles. रूपांतरण पैनल में किए गए बदलाव क्या रूपांतरित करते हैं: ऑब्जेक्ट, उसकी पैटर्न टाइलें या दोनों; डिफ़ॉल्ट ट्रांसफॉर्म पैटर्न टाइलें का पालन करता है। With one symbol instance selected, the Transform panel uses the symbol's registration point as its reference point. एक सिंबल इंस्टेंस चुना होने पर रूपांतरण पैनल सिंबल के रजिस्ट्रेशन पॉइंट को संदर्भ पॉइंट के रूप में इस्तेमाल करता है। + Drawing a rectangle, ellipse, polygon, star or line opens the Transform panel if it is closed. आयत, दीर्घवृत्त, बहुभुज, तारा या रेखा ड्रॉ करने पर रूपांतरण पैनल बंद हो तो खुल जाता है। Darkens the canvas outside the artboards while the Artboard tool is active. आर्टबोर्ड टूल सक्रिय रहने पर आर्टबोर्ड के बाहर का कैनवास गहरा करता है। With Fade Region Outside Artboard on, the area outside the artboards stays dark while you drag with the Artboard tool. आर्टबोर्ड के बाहर का क्षेत्र धुंधला करें चालू होने पर आर्टबोर्ड टूल से ड्रैग करते समय आर्टबोर्ड के बाहर का क्षेत्र गहरा बना रहता है। How near, in pixels, the pointer must be to an object, anchor or handle for a click to select it. किसी क्लिक से ऑब्जेक्ट, एंकर पॉइंट या हैंडल चुनने के लिए पॉइंटर को उससे कितने पिक्सेल पास होना चाहिए। @@ -4813,6 +4883,7 @@ antiAlias Sharp शार्प Save Preset प्रीसेट सेव करें Save Document Preset डॉक्यूमेंट प्रीसेट सेव करें Save Preset… प्रीसेट सेव करें… + Save Summary… सारांश सेव करें… Save Print Preset सेव करें प्रिंट प्रीसेट Save Recovery Data रिकवरी डेटा सेव करें Save Save for Web Preset सेव फॉर वेब प्रीसेट @@ -5223,6 +5294,7 @@ antiAlias Sharp शार्प Show Modified संशोधित दिखाएँ Show Note नोट दिखाएं Show Options ऑप्शन्स दिखाएँ + Show on Shape Creation शेप बनाते समय दिखाएँ Show Recent Colors हाल के रंग दिखाएँ Toggle RGB Percent RGB प्रतिशत में बदलें Show Original Path मूल पाथ दिखाएं @@ -5258,6 +5330,7 @@ antiAlias Sharp शार्प Show Tile Edge टाइल एज Show Tints/Shades शो टिंट्स / शेड्स Show Tool Group Labels टूल ग्रुप लेबल दिखाएं + Show Tool Cards टूल कार्ड दिखाएँ Show Tool Tips टूल युक्तियाँ दिखाएँ Show Toolbar शो टूलबार Show Transparency Grid पारदर्शिता ग्रिड दिखाएँ @@ -5408,6 +5481,8 @@ antiAlias Sharp शार्प Source code on GitHub GitHub पर स्रोत कोड Source Folder: स्रोत फ़ोल्डर: Source Image स्रोत इमेज + Split View विभाजित दृश्य + Divider विभाजक Source Sans 3 Source Sans 3 Space After Paragraph पैराग्राफ़ के बाद स्पेस Space Before Paragraph पैराग्राफ़ से पहले स्पेस @@ -5618,6 +5693,17 @@ antiAlias Sharp शार्प Symbol Screener Tool सिंबल स्क्रीनर टूल Symbol Scruncher सिंबल स्क्रंचर Symbol Scruncher Tool सिंबल स्क्रंचर टूल + Tool: टूल: + Symbol Set Density सिंबल सेट डेंसिटी + Symbol Sprayer Options सिंबल स्प्रेयर विकल्प + Scrunch: स्क्रंच: + Spin: स्पिन: + Screen: स्क्रीन: + Stain: स्टेन: + Symbol Sizer Options सिंबल साइज़र विकल्प + Proportional Resizing आनुपातिक रीसाइज़िंग + Resizing Affects Density रीसाइज़िंग से डेंसिटी बदलती है + Show Brush Size and Intensity ब्रश का साइज़ और तीव्रता दिखाएँ Symbol Set Density: सिंबल सेट डेंसिटी: Symbol Shifter सिंबल शिफ्टर Symbol Shifter Tool सिंबल शिफ़्टर टूल @@ -5661,6 +5747,8 @@ antiAlias Sharp शार्प Tail: पूंछ: Tamil तमिल Tangent Circle स्पर्शी वृत्त + Tangent Circle Tool स्पर्शी वृत्त टूल + No tangent circle here यहाँ कोई स्पर्शी वृत्त नहीं है Tangent Circle… स्पर्शी वृत्त… Taper टेपर Target लक्ष्य @@ -5996,6 +6084,8 @@ antiAlias Sharp शार्प Unembedded to {} एम्बेड हटाकर {} में रखा गया Ungroup समूह तोड़ें Ungroup Color Group रंग समूह का ग्रूपिंग हटाएँ + Color Group Options रंग समूह ऑप्शन्स + Color Group Options… रंग समूह ऑप्शन्स… Unicode यूनिकोड Unicode (UTF-16) यूनिकोड (UTF-16) Unicode (UTF-8) यूनिकोड (UTF-8) @@ -7000,6 +7090,7 @@ antiAlias Sharp शार्प @msg a graph has at most {_1} series, so it transposes with at most that many categories एक ग्राफ में सबसे {_1} श्रृंखला है, इसलिए यह उस कई श्रेणियों के साथ ट्रांसपोजित होता है। @msg a graph's records don't end where they should: its art was read as it is एक ग्राफ का रिकॉर्ड अंत नहीं है जहां उन्हें होना चाहिए: इसकी कला को पढ़ा गया क्योंकि यह है @msg a graphic style named `{to}` already exists `{to}` नामक एक ग्राफिक स्टाइल पहले से मौजूद है +@msg a swatch or color group named `{name}` already exists `{name}` नामक एक स्वॉच या रंग समूह पहले से मौजूद है @msg a group crosses a multi-layer mask एक समूह एक बहुलेयर मास्क पार करता है @msg a key object sits on that point एक प्रमुख ऑब्जेक्ट उस बिंदु पर बैठती है @msg a layer can't be merged into its own sublayer एक लेयर को अपने खुद के सबलेयर में विलय नहीं किया जा सकता है @@ -7774,6 +7865,7 @@ liquify-list-end {0}, {1} {0} और {1} @msg give one of assets, layers, selection or fullDocument assets, layers, selection या fullDocument में से एक दें @msg give only one of onto, above, below, icon and a column place केवल ऊपर, नीचे, आइकन और एक स्तंभ स्थान देने के लिए @msg give only one of onto, below and above नीचे और ऊपर केवल एक देना +@msg give only one of `index`, `indices` and `t` `index`, `indices` और `t` में से केवल एक दें @msg give origin: [x, y], or reset: true origin: [x, y] दें, या reset: true @msg give overprintFill, overprintStroke, showCenter, imageMap, url or note overprintFill, overprintStroke, showCenter, imageMap, url या नोट @msg give path (a file) or folder पाथ (एक फ़ाइल) या फ़ोल्डर देना @@ -8112,6 +8204,11 @@ liquify-list-end {0}, {1} {0} और {1} @msg no anchor points selected कोई एंकर पॉइंट सिलेक्ट नहीं है @msg `points` must be two or three [x, y] pairs of numbers `points` में संख्याओं के दो या तीन [x, y] जोड़े होने चाहिए @msg direct-select two or three anchor points, or give `points` दो या तीन एंकर पॉइंट्स डायरेक्ट-सिलेक्ट करें, या `points` दें +@msg the path is straight there, so no circle matches its curvature वहाँ पाथ सीधा है, इसलिए कोई वृत्त उसकी वक्रता से मेल नहीं खाता +@msg the path has a cusp there, so it has no single curvature वहाँ पाथ में नुकीला बिंदु है, इसलिए उसकी कोई एक वक्रता नहीं है +@msg the path has a corner there, so it has no single curvature वहाँ पाथ में कोना है, इसलिए उसकी कोई एक वक्रता नहीं है +@msg a guide has no curvature circle गाइड का कोई वक्रता वृत्त नहीं होता +@msg the circle that matches the path there would reach past the canvas वहाँ पाथ से मेल खाने वाला वृत्त कैनवास से बाहर चला जाएगा @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} @@ -8771,6 +8868,16 @@ liquify-list-end {0}, {1} {0} और {1} @msg The paths overlap, so they have no internal tangents पाथ एक-दूसरे पर चढ़े हुए हैं, इसलिए उनकी कोई आंतरिक स्पर्शरेखा नहीं है @msg One path lies inside the other, so they have no internal tangents एक पाथ दूसरे के अंदर है, इसलिए उनकी कोई आंतरिक स्पर्शरेखा नहीं है @msg The point lies inside the path, so it has no tangents बिंदु पाथ के अंदर है, इसलिए उसकी कोई स्पर्शरेखा नहीं है +# Path Precision Tools add-on: Add Bounding Rectangle and Add Bounding Circle. + Add Bounding Rectangle बाउंडिंग आयत जोड़ें + Add Bounding Circle बाउंडिंग वृत्त जोड़ें + Add Bounding Rectangle… बाउंडिंग आयत जोड़ें… + Add Bounding Circle… बाउंडिंग वृत्त जोड़ें… + One per Object प्रत्येक ऑब्जेक्ट के लिए एक +@msg nothing to enclose घेरने के लिए कुछ नहीं +@msg `offset` must be 0 or more `offset` 0 या उससे अधिक होना चाहिए +@msg the shape would have no size आकृति का कोई आकार नहीं होगा +@msg the shape would reach past the edge of the canvas आकृति कैनवास के किनारे से आगे निकल जाएगी @msg select plain rectangles, ellipses or regular polygons to convert बदलने के लिए सादे आयत, अंडाकार या नियमित बहुभुजों सिलेक्ट करें @msg Select point type पॉइंट टाइप सिलेक्ट करें @msg select two or three paths or compound paths दो या तीन पाथ या यौगिक पाथ सिलेक्ट करें @@ -9186,6 +9293,7 @@ liquify-list-end {0}, {1} {0} और {1} @msg the RTF file is too large to place as type (at most {_1} MB) RTF फ़ाइल टाइप के रूप में प्लेस करने के लिए बहुत बड़ी है (अधिकतम {_1} MB) @msg the runtime panicked रनटाइम क्रैश हो गया @msg the Save PDF dialog didn't open सेव करें PDF संवाद खुला नहीं था +@msg the Save PDF dialog is not open सेव करें PDF संवाद खुला नहीं है @msg the scale is not a usable number स्केल एक प्रयोग योग्य संख्या नहीं है @msg the screen color sampler is already open स्क्रीन रंग नमूना पहले से ही खुला है @msg the search couldn't start: try again in a moment खोज शुरू नहीं हो सका: एक पल में फिर से प्रयास करें @@ -9528,6 +9636,49 @@ variable-list-end {0}, {1} {0} और {1} @msg the PSD file's layer groups are nested too deeply PSD फ़ाइल के लेयर समूह बहुत गहराई तक नेस्ट किए गए हैं @msg a layer of the PSD file is too large to read PSD फ़ाइल की एक लेयर पढ़ने के लिए बहुत बड़ी है @msg the PSD file's layers take more memory to read than allowed PSD फ़ाइल की लेयर पढ़ने के लिए अनुमति से अधिक मेमोरी चाहिए +@msg the file is no longer loaded फ़ाइल अब लोड नहीं है +@msg the layers can't be read ({e}): the file was placed as its merged image लेयर पढ़ी नहीं जा सकतीं ({e}): फ़ाइल अपनी मर्ज की गई इमेज के रूप में प्लेस की गई +@msg 1 type layer came in as pixels: the text isn't editable 1 टाइप लेयर पिक्सेल के रूप में आई: टेक्स्ट एडिट नहीं किया जा सकता +@msg {n} type layers came in as pixels: the text isn't editable {n} टाइप लेयर पिक्सेल के रूप में आईं: टेक्स्ट एडिट नहीं किया जा सकता +@msg 1 adjustment layer was not applied 1 एडजस्टमेंट लेयर लागू नहीं हुई +@msg {n} adjustment layers were not applied {n} एडजस्टमेंट लेयर लागू नहीं हुईं +@msg 1 fill layer was not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels) 1 फ़िल लेयर ड्रॉ नहीं हुई (ग्रेडिएंट या पैटर्न फ़िल, ऐसा रंग जो पढ़ा नहीं जा सकता, या ऐसी आकृति जो कोई पिक्सेल नहीं रखती) +@msg {n} fill layers were not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels) {n} फ़िल लेयर ड्रॉ नहीं हुईं (ग्रेडिएंट या पैटर्न फ़िल, ऐसा रंग जो पढ़ा नहीं जा सकता, या ऐसी आकृति जो कोई पिक्सेल नहीं रखती) +@msg the layer effects of 1 layer weren't drawn 1 लेयर के लेयर इफ़ेक्ट ड्रॉ नहीं हुए +@msg the layer effects of {n} layers weren't drawn {n} लेयर के लेयर इफ़ेक्ट ड्रॉ नहीं हुए +@msg the vector masks of 1 layer weren't applied 1 लेयर के वेक्टर मास्क लागू नहीं हुए +@msg the vector masks of {n} layers weren't applied {n} लेयर के वेक्टर मास्क लागू नहीं हुए +@msg the knockout of 1 layer wasn't applied 1 लेयर का नॉकआउट लागू नहीं हुआ +@msg the knockout of {n} layers wasn't applied {n} लेयर का नॉकआउट लागू नहीं हुआ +@msg 1 layer was left out (hidden layers and the layers clipped to them) 1 लेयर छोड़ दी गई (छिपी लेयर और उन पर क्लिप की गई लेयर) +@msg {n} layers were left out (hidden layers and the layers clipped to them) {n} लेयर छोड़ दी गईं (छिपी लेयर और उन पर क्लिप की गई लेयर) +@msg 1 layer clipped to a fill layer that wasn't drawn was left out ड्रॉ न हुई फ़िल लेयर पर क्लिप की गई 1 लेयर छोड़ दी गई +@msg {n} layers clipped to fill layers that weren't drawn were left out ड्रॉ न हुई फ़िल लेयर पर क्लिप की गई {n} लेयर छोड़ दी गईं +@msg layers in blend modes VectorCraft doesn't have ({modes}) were merged with the layers below them उन ब्लेंड मोड की लेयर जो VectorCraft में नहीं हैं ({modes}), अपने नीचे की लेयर के साथ मर्ज कर दी गईं +@msg 1 layer in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed ऐसे ब्लेंड मोड की 1 लेयर जो VectorCraft में नहीं है, सामान्य के रूप में आई: मर्ज करने के लिए अनुमति से अधिक मेमोरी चाहिए +@msg {n} layers in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed ऐसे ब्लेंड मोड की {n} लेयर जो VectorCraft में नहीं हैं, सामान्य के रूप में आईं: मर्ज करने के लिए अनुमति से अधिक मेमोरी चाहिए +@msg 1 layer clipped to the layer below came in unclipped: the merge needs more memory than allowed नीचे की लेयर पर क्लिप की गई 1 लेयर बिना क्लिप के आई: मर्ज करने के लिए अनुमति से अधिक मेमोरी चाहिए +@msg {n} layers clipped to the layer below came in unclipped: the merge needs more memory than allowed नीचे की लेयर पर क्लिप की गई {n} लेयर बिना क्लिप के आईं: मर्ज करने के लिए अनुमति से अधिक मेमोरी चाहिए +@msg hiddenLayers applies to a PSD file placed with layers: true hiddenLayers उस PSD फ़ाइल पर लागू होता है जो layers: true के साथ प्लेस की जाती है +@msg importSlices: a linked PSD file is placed as its flat image; give link: false to embed it with its slices importSlices: लिंक की गई PSD फ़ाइल अपनी फ़्लैट इमेज के रूप में प्लेस होती है; उसे उसकी स्लाइस के साथ एम्बेड करने के लिए link: false दें +@msg layers: a linked PSD file is placed as its flat image; leave link out or give link: false layers: लिंक की गई PSD फ़ाइल अपनी फ़्लैट इमेज के रूप में प्लेस होती है; link छोड़ दें या link: false दें +@msg the slices can't be read ({e}) and were left out स्लाइस पढ़ी नहीं जा सकतीं ({e}) और छोड़ दी गईं +@msg 1 slice lies outside the canvas or has no size and was left out 1 स्लाइस कैनवस के बाहर है या उसका कोई आकार नहीं है और छोड़ दी गई +@msg {n} slices lie outside the canvas or have no size and were left out {n} स्लाइस कैनवस के बाहर हैं या उनका कोई आकार नहीं है और छोड़ दी गईं +@msg 1 slice would lie outside the canvas and was left out 1 स्लाइस कैनवस के बाहर पड़ती और छोड़ दी गई +@msg {n} slices would lie outside the canvas and were left out {n} स्लाइस कैनवस के बाहर पड़तीं और छोड़ दी गईं +@msg the slices' descriptor holds too many values स्लाइस के डिस्क्रिप्टर में बहुत अधिक मान हैं +@msg the slices' descriptor has a version other than 16 स्लाइस के डिस्क्रिप्टर का संस्करण 16 नहीं है +@msg the slices are stored in version {v}, which isn't read स्लाइस संस्करण {v} में सहेजी गई हैं, जो पढ़ा नहीं जाता +@msg the file has {count} slices, more than the {MAX_SLICES} read फ़ाइल में {count} स्लाइस हैं, पढ़ी जाने वाली {MAX_SLICES} से अधिक +@msg the slices' descriptor has no list of slices स्लाइस के डिस्क्रिप्टर में स्लाइस की कोई सूची नहीं है +@msg the slices' descriptor lists something other than a slice स्लाइस का डिस्क्रिप्टर स्लाइस के अलावा कुछ और सूचीबद्ध करता है +@msg a slice in the slices' descriptor has no bounds स्लाइस के डिस्क्रिप्टर में एक स्लाइस की कोई सीमा नहीं है +@msg a slice's bounds in the slices' descriptor aren't numbers स्लाइस के डिस्क्रिप्टर में एक स्लाइस की सीमाएँ संख्याएँ नहीं हैं +@msg a text in the slices has more than the {MAX_TEXT} characters read स्लाइस के एक टेक्स्ट में पढ़े जाने वाले {MAX_TEXT} अक्षरों से अधिक हैं +@msg the slices' descriptor nests too deep स्लाइस का डिस्क्रिप्टर बहुत गहराई तक नेस्ट है +@msg the slices' descriptor has a reference of an unknown kind ({_1}) स्लाइस के डिस्क्रिप्टर में अज्ञात प्रकार का संदर्भ है ({_1}) +@msg the slices' descriptor has a value of an unknown type ({_1}) स्लाइस के डिस्क्रिप्टर में अज्ञात टाइप का मान है ({_1}) @msg the layers can't be read ({e}): the file opened as its merged image लेयर पढ़ी नहीं जा सकतीं ({e}): फ़ाइल अपनी मर्ज की गई इमेज के रूप में खुली @msg zone must be a string zone एक स्ट्रिंग होनी चाहिए @msg zone must be tab, center, left, right, top or bottom zone को tab, center, left, right, top या bottom होना चाहिए @@ -10014,6 +10165,39 @@ theme Appearance अपीयरेंस No objects are selected. कोई ऑब्जेक्ट सिलेक्ट नहीं है। Open a document to mark its fold lines. फ़ोल्ड लाइनें मार्क करने के लिए कोई डॉक्यूमेंट ओपन करें। Remove Fold Line Role लाइन प्रकार हटाएँ +# Tool cards (General › Show Tool Cards): one sentence on what each tool does. + Shows a card with what a toolbar tool does and what its keys do instead of its tip; it needs Show Tool Tips. टूलबार का टूल और उसकी कुंजियाँ क्या करती हैं, यह टिप की जगह एक कार्ड में दिखाता है; इसके लिए टूल युक्तियाँ दिखाएँ चालू होना चाहिए। + Selects whole objects and groups to move, resize or rotate them. पूरे ऑब्जेक्ट और समूह चुनता है, ताकि उन्हें खिसकाया, आकार बदला या घुमाया जा सके। + Selects anchor points and path segments to reshape a path. पाथ का आकार बदलने के लिए एंकर पॉइंट और पाथ सेगमेंट चुनता है। + Draws paths point by point, with straight segments and smooth curves. सीधे सेगमेंट और चिकने वक्रों के साथ बिंदु-दर-बिंदु पाथ बनाता है। + Draws smooth curves through the points you click. आपके क्लिक किए गए बिंदुओं से होकर चिकने वक्र बनाता है। + Adds text at a point, or in a frame you drag. किसी बिंदु पर, या आपके द्वारा खींचे गए फ़्रेम में टेक्स्ट जोड़ता है। + Draws rectangles and squares. आयत और वर्ग बनाता है। + Draws rectangles with rounded corners. गोल कोनों वाले आयत बनाता है। + Draws ellipses and circles. दीर्घवृत्त और वृत्त बनाता है। + Draws polygons with sides of equal length. बराबर लंबाई की भुजाओं वाले बहुभुज बनाता है। + Draws stars. तारे बनाता है। + Turns objects around a reference point. ऑब्जेक्ट को किसी संदर्भ बिंदु के चारों ओर घुमाता है। + Flips objects across an axis through a reference point. ऑब्जेक्ट को संदर्भ बिंदु से होकर जाने वाले अक्ष पर पलटता है। + Resizes objects from a reference point. संदर्भ बिंदु से ऑब्जेक्ट का आकार बदलता है। + Slants objects from a reference point. संदर्भ बिंदु से ऑब्जेक्ट को तिरछा करता है। + Moves the view of the document. दस्तावेज़ के दृश्य को खिसकाता है। + Magnifies or reduces the view. दृश्य को बड़ा या छोटा करता है। + Copies the color and other attributes of one object to the selection. एक ऑब्जेक्ट का रंग और अन्य गुण चयन पर कॉपी करता है। + Sets the direction and length of a gradient. ग्रेडिएंट की दिशा और लंबाई सेट करता है। + Creates, selects and resizes artboards. आर्टबोर्ड बनाता है, चुनता है और उनका आकार बदलता है। + Changes the width of a stroke along its length. स्ट्रोक की चौड़ाई उसकी लंबाई के साथ बदलता है। + Bends art by dragging pins placed on it. आर्ट पर लगाए गए पिन खींचकर उसे मोड़ता है। + Pushes the outlines of paths in the direction you drag. पाथ की रूपरेखा को उस दिशा में धकेलता है जिधर आप खींचते हैं। + Twists the outlines of paths into swirls. पाथ की रूपरेखा को भँवरों में मरोड़ता है। + Pulls the outlines of paths in toward the brush. पाथ की रूपरेखा को ब्रश की ओर अंदर खींचता है। + Pushes the outlines of paths out from the brush. पाथ की रूपरेखा को ब्रश से बाहर की ओर धकेलता है। + Adds curved details along the outlines of paths. पाथ की रूपरेखा के साथ घुमावदार विवरण जोड़ता है। + Adds spiky details along the outlines of paths. पाथ की रूपरेखा के साथ नुकीले विवरण जोड़ता है। + Adds wrinkles along the outlines of paths. पाथ की रूपरेखा के साथ सिलवटें जोड़ता है। + Moves, copies and resizes objects on the perspective grid. पर्सपेक्टिव ग्रिड पर ऑब्जेक्ट को खिसकाता, कॉपी करता और उनका आकार बदलता है। + Makes a series of steps between two or more objects. दो या अधिक ऑब्जेक्ट के बीच चरणों की एक शृंखला बनाता है। + Places dimension lines that show measured lengths. मापी गई लंबाई दिखाने वाली आयाम रेखाएँ लगाता है। Tap जल्दी दबाना Clear Hold होल्ड साफ़ करें Hold Shortcuts होल्ड शॉर्टकट @@ -10044,7 +10228,18 @@ theme Appearance अपीयरेंस @msg A panel is not joined to the rest by a crease. कोई पैनल किसी क्रीज़ लाइन से बाकी से जुड़ा नहीं है। @msg A fold line is on a non-printing layer. एक फ़ोल्ड लाइन नॉन-प्रिंटिंग लेयर पर है। @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} पैनल: {panels}, हिंज: {hinges}, एरर: {errors}, वॉर्निंग: {warnings} + Paper Cutouts कागज़ की कतरनें + Coral Layers कोरल परतें + Mint Layers मिंट परतें + Midnight Layers आधी रात की परतें + Sunflower Sheet सूरजमुखी शीट + Rose Layers गुलाबी परतें + Monochrome Stack मोनोक्रोम स्टैक Dashed Arrow बिंदीदार तीर + Fine Stipple बारीक बिंदु छायांकन + Dense Stipple घना बिंदु छायांकन + Soft Stipple हल्का बिंदु छायांकन + Bold Stipple गाढ़ा बिंदु छायांकन Pressure Sensitive दबाव संवेदनशील Flex Ribbon लचीला फीता Pulse Stroke स्पंदित रेखा @@ -10060,3 +10255,7 @@ theme Appearance अपीयरेंस @msg Other blanks not shown: {count} दूसरे ब्लैंक नहीं दिखाए गए: {count} @msg A joint does not close by {gap} pt. एक जोड़ {gap} pt से बंद नहीं होता। @msg Two panels pass through each other. दो पैनल एक-दूसरे के आर-पार जाते हैं। + +# #5804 native-picked raster editor (draft translations; native review welcome). + Edit Original with: मूल फ़ाइल इसमें एडिट करें: +file-filter Applications ऐप्स diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index dde077e4a5..2d1af1b3a9 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -417,6 +417,7 @@ font-technology Variable Változó Basic Latin Alap latin Batch Kötegelt feldolgozás Bearing Irány + Stylus Wheel Tollkerék Begin Recording Felvétel indítása Exclude from playback Kizárás a lejátszásból Include in playback Bevonás a lejátszásba @@ -661,6 +662,9 @@ font-technology Variable Változó Choose… Kiválasztás… Circle Kör Circle Tool Kör eszköz + Curvature Circle Tool Simulókör eszköz + Cusp Csúcspont + Straight segment Egyenes szakasz Circle too large A kör túl nagy Circle (open) Kör (nyitott) Classic Defaults Klasszikus alapértékek @@ -723,6 +727,25 @@ font-technology Variable Változó Preserve Embedded Profiles Beágyazott profilok megtartása Convert to Working Space Konvertálás a munkaszíntérbe Preserve Numbers Számértékek megtartása + Profile Mismatches: Profileltérések: + Ask When Opening Kérdezzen megnyitáskor + Ask When Pasting Kérdezzen beillesztéskor + Missing Profiles: Hiányzó profilok: + Embedded Profile Mismatch Eltérő beágyazott profil + Missing Profile Hiányzó profil + Paste Profile Mismatch Profileltérés beillesztéskor + “{name}” is not tagged with a {model} profile. „{name}” nem rendelkezik {model}-profillal. + “{name}” is tagged with the {model} profile “{profile}”, which is not the {model} working space “{working}”. „{name}” {model}-profilja „{profile}”, amely nem a(z) „{working}” {model}-munkaszíntér. + Use the embedded profile A beágyazott profil használata + Convert the colors to the working space A színek konvertálása a munkaszíntérbe + Discard the embedded profile A beágyazott profil elvetése + Leave as is Változatlanul hagyás + Assign the working space A munkaszíntér hozzárendelése + Assign profile: Profil hozzárendelése: + Preserve the color numbers A színértékek megtartása + Convert to keep the colors' appearance Konvertálás a színek megjelenésének megtartásával +@msg `{path}` goes with `{key}`: "assign" only `{path}` csak a(z) `{key}`: "assign" értékkel használható + The pasted colors come from a document whose {model} profile is “{from}”; this document's is “{to}”. A beillesztett színek olyan dokumentumból származnak, amelynek {model}-profilja „{from}”; ennek a dokumentumnak „{to}”. Coarse Dots Durva pontok Collapse Panels to Icons Panelek ikonná csukása Collapse to Icons Ikonná csukás @@ -787,6 +810,9 @@ font-technology Variable Változó Box Channel Négyzet csatornája Color box Színnégyzet Color Wheel Options Színkör beállításai + Show Harmony Harmónia megjelenítése + Harmony Rule Harmóniaszabály + Harmony color Harmóniaszín Color Type: Színtípus: Color: Szín: Colorization Színezés @@ -1318,10 +1344,25 @@ font-technology Variable Változó Duplication Kettőzés Dutch Holland DWG (use DXF) DWG (használd a DXF-et) + PSD Import Options PSD-importálás beállításai + Place PSD PSD elhelyezése + Convert Layers to Objects Rétegek átalakítása objektumokká + Import Hidden Layers Rejtett rétegek importálása + Flatten Layers to a Single Image Rétegek egyetlen képpé simítása + Import Slices Szeletek importálása DXF Import Options DXF-importálás beállításai DXF Info DXF-adatok DXF Options DXF-beállítások DXF Options Dialog DXF-beállítások párbeszédablak + HP-GL Options HP-GL-beállítások + HP-GL Options Dialog HP-GL-beállítások párbeszédablak + Curve Tolerance: Görbék tűréshatára: + Origin: Origó: + Pens: Tollak: + One Pen per Color Színenként egy toll + Pen Table Tolltáblázat + Draw the Nearest Path Next A legközelebbi útvonal rajzolása következőként + Draw Inner Paths First A belső útvonalak rajzolása először e.g. 1-3, 5 pl. 1-3, 5 Each page prints as one image, at the document's raster effects resolution. Minden oldal egyetlen képként nyomtatódik, a dokumentum raszteres effektusainak felbontásával. Earth Tones Földszínek @@ -1569,6 +1610,15 @@ font-technology Variable Változó Shading Color Árnyékolás színe Black Overprint Felülnyomó fekete Draw Hidden Faces Rejtett lapok rajzolása + Map Art… Grafika leképezése… + Map Art Grafika leképezése + First Surface Első felület + Previous Surface Előző felület + Next Surface Következő felület + Last Surface Utolsó felület + Scale to Fit Méretezés a felülethez + Shade Artwork Grafika árnyékolása + Invisible Geometry Láthatatlan geometria Eyedropper Pipetta Sample Color from Screen Szín mintavétele a képernyőről This system has no screen color sampler Ezen a rendszeren nincs képernyős színmintavevő @@ -2073,6 +2123,8 @@ file-filter Templates Sablonok Hide Bounding Box Befoglaló keret elrejtése Hide Code Kód elrejtése Hide Corner Widget Sarokfogantyú elrejtése + Hide Shape Widgets Alakzatfogantyúk elrejtése + Show Shape Widgets Alakzatfogantyúk megjelenítése Hide Corner Widget for angles greater than Sarokfogantyú elrejtése, ha a szög nagyobb, mint Hide Edges Élek elrejtése Hide Gradient Annotator Színátmenet-jelölő elrejtése @@ -2431,6 +2483,15 @@ file-filter Templates Sablonok Kind Típus Kinsoku Set Kinsoku-készlet Kinsoku Shori Type Kinsoku Shori típusa + Kinsoku Shori Settings… Kinsoku Shori beállításai… + Kinsoku Shori Settings Kinsoku Shori beállításai + Kinsoku Sets Kinsoku-készletek + Kinsoku Set Base Kinsoku-készlet alapja + Based on: Alapja: + Cannot Start Line Nem kezdhet sort + Cannot End Line Nem zárhat sort + Hanging Punctuation Függő írásjelek + Inseparable Characters Elválaszthatatlan karakterek Kite Deltoid Knife Kés Knockout Group Kiütő csoport @@ -3130,6 +3191,8 @@ file-filter Templates Sablonok Overprint and Transparency Flattener Options Felülnyomás és átlátszóság-lapítás beállításai Custom… Egyéni… Custom Transparency Flattener Options Egyéni átlátszóság-lapítási beállítások + The PDF preset keeps the flattener preset but not the Custom… settings. A PDF-előbeállítás megtartja a lapítási előbeállítást, de az Egyéni… beállításokat nem. + PDF 1.3 files clip rasterized areas to their regions, and Overprint sets whether overprints are kept. A PDF 1.3-fájlok a raszterizált területeket a saját régióikra vágják, és a Felülnyomás beállítás dönti el, hogy megmaradnak-e a felülnyomások. EPS has no alpha transparency, and Overprints sets whether overprints are kept. Az EPS-ben nincs alfa-átlátszóság, és a Felülnyomások beállítás dönti el, hogy megmaradnak-e a felülnyomások. Overprint Black… Fekete felülnyomása… Overprint Fill Kitöltés felülnyomása @@ -3202,6 +3265,9 @@ file-filter Templates Sablonok embedding for preview and print beágyazás előnézethez és nyomtatáshoz embedding allowed beágyazás engedélyezett {file}; {embedding} {file}; {embedding} + unknown type ismeretlen típus + {type}; {uses} {type}; {uses} +@plural {n} use|{n} uses {n} használat substituted: shown in {family} {style} ({detail}) helyettesítve: megjelenítés ezzel: {family} {style} ({detail}) missing: shown in {family} {style} hiányzik: megjelenítés ezzel: {family} {style} missing hiányzik @@ -3721,6 +3787,9 @@ mark-style Japanese Japán Rotate View to Selection Nézet elforgatása a kijelöléshez Reset the rows to the artwork's colors Sorok visszaállítása a grafika színeire Color Theme Picker Színtéma-választó + Undo Changes Módosítások visszavonása + Redo Changes Módosítások újra +@msg Recolor Artwork is not open A Grafika átszínezése nincs megnyitva Click or drag across the art to pick its colors; Shift adds more Kattintson vagy húzzon a grafikán a színei felvételéhez; a Shift továbbiakat ad hozzá Prominent Colors Domináns színek Save All Colors Összes szín mentése @@ -3791,6 +3860,7 @@ mark-style Japanese Japán A live rectangle's properties show one Corner Radius field for all four corners; off, each corner has its own field. Egy élő téglalap tulajdonságai egyetlen Sarokkerekítés sugara mezőt mutatnak mind a négy sarokhoz; kikapcsolva minden saroknak saját mezője van. What edits in the Transform panel transform: the object, its pattern tiles or both; Default follows Transform Pattern Tiles. Mit alakítanak át az Átalakítás panel módosításai: az objektumot, a mintázatcsempéit vagy mindkettőt; az Alapértelmezett a Mintázatcsempék átalakítása beállítást követi. With one symbol instance selected, the Transform panel uses the symbol's registration point as its reference point. Ha egy szimbólumpéldány van kijelölve, az Átalakítás panel a szimbólum regisztrációs pontját használja referenciapontként. + Drawing a rectangle, ellipse, polygon, star or line opens the Transform panel if it is closed. Téglalap, ellipszis, sokszög, csillag vagy vonal rajzolása megnyitja az Átalakítás panelt, ha zárva van. Darkens the canvas outside the artboards while the Artboard tool is active. Elsötétíti a vásznat a rajztáblákon kívül, amíg a Rajztábla eszköz aktív. With Fade Region Outside Artboard on, the area outside the artboards stays dark while you drag with the Artboard tool. Ha A rajztáblán kívüli terület elhalványítása be van kapcsolva, a rajztáblákon kívüli terület sötét marad, miközben a Rajztábla eszközzel húz. How near, in pixels, the pointer must be to an object, anchor or handle for a click to select it. Hány pixelnyire kell a mutatónak egy objektumhoz, horgonyponthoz vagy fogantyúhoz lennie, hogy egy kattintás kijelölje. @@ -4000,6 +4070,7 @@ mark-style Japanese Japán Save Document Preset Dokumentum-előbeállítás mentése Preset {number} Előbeállítás {number} Save Preset… Előbeállítás mentése… + Save Summary… Összegzés mentése… Save Print Preset Nyomtatási előbeállítás mentése Save Recovery Data Helyreállítási adatok mentése Save Save for Web Preset Webes mentési előbeállítás mentése @@ -4347,6 +4418,7 @@ mark-style Japanese Japán Show Modified Módosultak megjelenítése Show Note Megjegyzés megjelenítése Show Options Beállítások megjelenítése + Show on Shape Creation Megjelenítés alakzat létrehozásakor Show Recent Colors Legutóbbi színek megjelenítése Toggle RGB Percent RGB százalékos megjelenítésének váltása Show Original Path Eredeti útvonal megjelenítése @@ -4376,6 +4448,7 @@ mark-style Japanese Japán Show Tile Edge Csempeszél megjelenítése Show Tints/Shades Világosabb/sötétebb árnyalatok Show Tool Group Labels Eszközcsoportok címkéinek megjelenítése + Show Tool Cards Eszközkártyák megjelenítése Show Tool Tips Elemleírások megjelenítése Show Transparency Grid Átlátszósági rács megjelenítése Show Video Rulers Videovonalzók megjelenítése @@ -4488,6 +4561,8 @@ mark-style Japanese Japán Sort by Status Rendezés állapot szerint Source code on GitHub Forráskód a GitHubon Source Image Forráskép + Split View Osztott nézet + Divider Elválasztó Source Sans 3 Source Sans 3 Space After Paragraph Térköz a bekezdés után Space Before Paragraph Térköz a bekezdés előtt @@ -4665,6 +4740,17 @@ mark-style Japanese Japán Symbol Libraries Szimbólumkönyvtárak Symbol Screener Tool Szimbólumhalványító Symbol Scruncher Tool Szimbólumtömörítő + Tool: Eszköz: + Symbol Set Density Szimbólumkészlet sűrűsége + Symbol Sprayer Options Szimbólumszóró beállításai + Scrunch: Tömörítés: + Spin: Forgatás: + Screen: Halványítás: + Stain: Színezés: + Symbol Sizer Options Szimbólumméretező beállításai + Proportional Resizing Arányos átméretezés + Resizing Affects Density Az átméretezés befolyásolja a sűrűséget + Show Brush Size and Intensity Ecsetméret és erősség megjelenítése Symbol Set Density: Szimbólumkészlet sűrűsége: Symbol Shifter Tool Szimbólumtoló Symbol Sizer Tool Szimbólumméretező @@ -4992,6 +5078,8 @@ mark-style Japanese Japán Unembed… Beágyazás megszüntetése… Ungroup Csoportbontás Ungroup Color Group Színcsoport bontása + Color Group Options Színcsoport beállításai + Color Group Options… Színcsoport beállításai… Unicode Unicode Unicode (UTF-16) Unicode (UTF-16) Unicode (UTF-8) Unicode (UTF-8) @@ -5378,6 +5466,7 @@ imageTrace Outline Körvonal @msg a freeform gradient keeps at least one point a szabad formájú színátmenetben legalább egy pont marad @msg a gradient needs at least two stops a színátmenethez legalább két színátmenet-pont kell @msg a graphic style named `{to}` already exists már van ilyen nevű grafikai stílus: `{to}` +@msg a swatch or color group named `{name}` already exists már van ilyen nevű színminta vagy színcsoport: `{name}` @msg a key object sits on that point ezen a ponton kulcsobjektum van @msg a layer couldn't be read egy réteg nem olvasható @msg a page is missing hiányzik egy oldal @@ -5770,6 +5859,7 @@ liquify-list-end {0}, {1} {0} és {1} @msg give corners of the path: anchors where its sides meet at an angle add meg az útvonal sarkait: azokat a horgonypontokat, ahol az oldalai szögben találkoznak @msg give horizontal or vertical add meg a horizontal vagy a vertical értéket @msg give only one of onto, below and above az onto, below és above közül csak egyet adj meg +@msg give only one of `index`, `indices` and `t` az `index`, `indices` és `t` közül csak egyet adj meg @msg give the path `id` and the width point `index` add meg az útvonal `id` és a szélességi pont `index` értékét @msg gradient “{name}” isn't defined in the file: a plain colour stands in for it a színátmenet nincs megadva a fájlban: „{name}”; helyette egyszínű kitöltés áll @msg group must be true or false a group értéke true vagy false lehet @@ -5881,6 +5971,11 @@ liquify-list-end {0}, {1} {0} és {1} @msg no anchor points selected nincs kijelölt horgonypont @msg `points` must be two or three [x, y] pairs of numbers a `points` két vagy három [x, y] számpár legyen @msg direct-select two or three anchor points, or give `points` jelölj ki közvetlen kijelöléssel két vagy három horgonypontot, vagy add meg a `points` értéket +@msg the path is straight there, so no circle matches its curvature az útvonal ott egyenes, így egyetlen kör sem illeszkedik a görbületéhez +@msg the path has a cusp there, so it has no single curvature az útvonalnak ott csúcspontja van, így nincs egyértelmű görbülete +@msg the path has a corner there, so it has no single curvature az útvonalnak ott sarka van, így nincs egyértelmű görbülete +@msg a guide has no curvature circle a segédvonalnak nincs görbületi köre +@msg the circle that matches the path there would reach past the canvas az útvonalhoz ott illeszkedő kör túlnyúlna a vásznon @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 @@ -6322,6 +6417,7 @@ liquify-list-end {0}, {1} {0} és {1} @msg HEIC and HEIF images can't be opened in this build a HEIC- és HEIF-képek ebben a buildben nem nyithatók meg @msg the PSD image is too large to read ({_1} × {_2} pixels) a PSD-kép túl nagy a beolvasáshoz ({_1} × {_2} pixel) @msg the Save PDF dialog didn't open a PDF mentése párbeszédablak nem nyílt meg +@msg the Save PDF dialog is not open a PDF mentése párbeszédablak nincs megnyitva @msg the scale is not a usable number a méretarány nem használható szám @msg the search couldn't start: try again in a moment a keresés nem indult el: próbáld újra egy kicsit később @msg the selected stroke's profile is already listed as {_1} a kijelölt körvonal profilja már szerepel a listán: {_1} @@ -6430,6 +6526,49 @@ variable-list-end {0}, {1} {0} és {1} @msg the PSD file's layer groups are nested too deeply a PSD-fájl rétegcsoportjai túl mélyen vannak egymásba ágyazva @msg a layer of the PSD file is too large to read a PSD-fájl egyik rétege túl nagy a beolvasáshoz @msg the PSD file's layers take more memory to read than allowed a PSD-fájl rétegeinek beolvasása több memóriát igényel a megengedettnél +@msg the file is no longer loaded a fájl már nincs betöltve +@msg the layers can't be read ({e}): the file was placed as its merged image a rétegek nem olvashatók ({e}): a fájl az egyesített képeként lett elhelyezve +@msg 1 type layer came in as pixels: the text isn't editable 1 szövegréteg képpontokként érkezett: a szöveg nem szerkeszthető +@msg {n} type layers came in as pixels: the text isn't editable {n} szövegréteg képpontokként érkezett: a szöveg nem szerkeszthető +@msg 1 adjustment layer was not applied 1 korrekciós réteg nem lett alkalmazva +@msg {n} adjustment layers were not applied {n} korrekciós réteg nem lett alkalmazva +@msg 1 fill layer was not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels) 1 kitöltőréteg nem lett megrajzolva (színátmenetes vagy mintás kitöltés, nem olvasható szín, vagy képpontokat nem tároló alakzat) +@msg {n} fill layers were not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels) {n} kitöltőréteg nem lett megrajzolva (színátmenetes vagy mintás kitöltés, nem olvasható szín, vagy képpontokat nem tároló alakzat) +@msg the layer effects of 1 layer weren't drawn 1 réteg rétegeffektusai nem lettek megrajzolva +@msg the layer effects of {n} layers weren't drawn {n} réteg rétegeffektusai nem lettek megrajzolva +@msg the vector masks of 1 layer weren't applied 1 réteg vektoros maszkjai nem lettek alkalmazva +@msg the vector masks of {n} layers weren't applied {n} réteg vektoros maszkjai nem lettek alkalmazva +@msg the knockout of 1 layer wasn't applied 1 réteg kiütése nem lett alkalmazva +@msg the knockout of {n} layers wasn't applied {n} réteg kiütése nem lett alkalmazva +@msg 1 layer was left out (hidden layers and the layers clipped to them) 1 réteg kimaradt (rejtett rétegek és a hozzájuk vágott rétegek) +@msg {n} layers were left out (hidden layers and the layers clipped to them) {n} réteg kimaradt (rejtett rétegek és a hozzájuk vágott rétegek) +@msg 1 layer clipped to a fill layer that wasn't drawn was left out kimaradt 1 réteg, amely egy meg nem rajzolt kitöltőréteghez van vágva +@msg {n} layers clipped to fill layers that weren't drawn were left out kimaradt {n} réteg, amely meg nem rajzolt kitöltőrétegekhez van vágva +@msg layers in blend modes VectorCraft doesn't have ({modes}) were merged with the layers below them a VectorCraftban nem létező keverési módú rétegek ({modes}) egyesítve lettek az alattuk lévő rétegekkel +@msg 1 layer in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed 1 réteg a VectorCraftban nem létező keverési módban Normál módban érkezett: az egyesítéshez több memória kell a megengedettnél +@msg {n} layers in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed {n} réteg a VectorCraftban nem létező keverési módokban Normál módban érkezett: az egyesítéshez több memória kell a megengedettnél +@msg 1 layer clipped to the layer below came in unclipped: the merge needs more memory than allowed 1 alatta lévő réteghez vágott réteg vágás nélkül érkezett: az egyesítéshez több memória kell a megengedettnél +@msg {n} layers clipped to the layer below came in unclipped: the merge needs more memory than allowed {n} alatta lévő réteghez vágott réteg vágás nélkül érkezett: az egyesítéshez több memória kell a megengedettnél +@msg hiddenLayers applies to a PSD file placed with layers: true a hiddenLayers a layers: true beállítással elhelyezett PSD-fájlra vonatkozik +@msg importSlices: a linked PSD file is placed as its flat image; give link: false to embed it with its slices importSlices: a csatolt PSD-fájl a lapos képeként kerül elhelyezésre; adja meg a link: false beállítást, hogy a szeleteivel együtt legyen beágyazva +@msg layers: a linked PSD file is placed as its flat image; leave link out or give link: false layers: a csatolt PSD-fájl a lapos képeként kerül elhelyezésre; hagyja el a link beállítást, vagy adja meg: link: false +@msg the slices can't be read ({e}) and were left out a szeletek nem olvashatók ({e}), ezért kimaradtak +@msg 1 slice lies outside the canvas or has no size and was left out 1 szelet a vásznon kívül esik vagy nincs mérete, ezért kimaradt +@msg {n} slices lie outside the canvas or have no size and were left out {n} szelet a vásznon kívül esik vagy nincs mérete, ezért kimaradt +@msg 1 slice would lie outside the canvas and was left out 1 szelet a vásznon kívül esne, ezért kimaradt +@msg {n} slices would lie outside the canvas and were left out {n} szelet a vásznon kívül esne, ezért kimaradt +@msg the slices' descriptor holds too many values a szeletek leírója túl sok értéket tartalmaz +@msg the slices' descriptor has a version other than 16 a szeletek leírójának verziója nem 16 +@msg the slices are stored in version {v}, which isn't read a szeletek {v} verzióban vannak tárolva, amely nem olvasható +@msg the file has {count} slices, more than the {MAX_SLICES} read a fájlban {count} szelet van, több a beolvasott {MAX_SLICES} darabnál +@msg the slices' descriptor has no list of slices a szeletek leírójában nincs szeletlista +@msg the slices' descriptor lists something other than a slice a szeletek leírója szeleten kívül mást is felsorol +@msg a slice in the slices' descriptor has no bounds a szeletek leírójában egy szeletnek nincsenek határai +@msg a slice's bounds in the slices' descriptor aren't numbers a szeletek leírójában egy szelet határai nem számok +@msg a text in the slices has more than the {MAX_TEXT} characters read a szeletek egyik szövege hosszabb a beolvasott {MAX_TEXT} karakternél +@msg the slices' descriptor nests too deep a szeletek leírója túl mélyen van egymásba ágyazva +@msg the slices' descriptor has a reference of an unknown kind ({_1}) a szeletek leírójában ismeretlen fajtájú hivatkozás van ({_1}) +@msg the slices' descriptor has a value of an unknown type ({_1}) a szeletek leírójában ismeretlen típusú érték van ({_1}) @msg the layers can't be read ({e}): the file opened as its merged image a rétegek nem olvashatók ({e}): a fájl az egyesített képeként nyílt meg @msg zone must be a string a zone értéke szöveg lehet @msg zone must be tab, center, left, right, top or bottom a zone értéke tab, center, left, right, top vagy bottom lehet @@ -8113,6 +8252,8 @@ breakText Glyphs Glifák # Path Precision Tools add-on: Tangent Circle. Tangent Circle… Érintőkör… Tangent Circle Érintőkör + Tangent Circle Tool Érintőkör eszköz + No tangent circle here Itt nincs érintőkör Circle: Kör: @msg `ids` names an object twice `ids`: egy objektumot kétszer nevez meg @msg select two or three paths or compound paths jelölj ki két vagy három útvonalat vagy összetett útvonalat @@ -8128,6 +8269,16 @@ breakText Glyphs Glifák @msg `circle` is past the last circle found ({found}) a `circle` az utolsó talált kör után van ({found}) @msg object {value} is not a path or compound path a(z) {value} objektum nem útvonal és nem összetett útvonal @msg these shapes are too small to measure ezek az alakzatok túl kicsik a méréshez +# Path Precision Tools add-on: Add Bounding Rectangle and Add Bounding Circle. + Add Bounding Rectangle Befoglaló téglalap hozzáadása + Add Bounding Circle Befoglaló kör hozzáadása + Add Bounding Rectangle… Befoglaló téglalap hozzáadása… + Add Bounding Circle… Befoglaló kör hozzáadása… + One per Object Objektumonként egy +@msg nothing to enclose nincs mit körülvenni +@msg `offset` must be 0 or more `offset`: 0 vagy nagyobb érték kell +@msg the shape would have no size az alakzatnak nem lenne mérete +@msg the shape would reach past the edge of the canvas az alakzat túlnyúlna a vászon szélén # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Dokumentumeszközök Save a Timestamped Copy Másolat mentése időbélyeggel @@ -10396,6 +10547,39 @@ breakText Glyphs Glifák No objects are selected. Nincs kijelölt objektum. Open a document to mark its fold lines. Nyiss meg egy dokumentumot a hajtásvonalai megjelöléséhez. Remove Fold Line Role Vonaltípus eltávolítása +# Tool cards (General › Show Tool Cards): one sentence on what each tool does. + Shows a card with what a toolbar tool does and what its keys do instead of its tip; it needs Show Tool Tips. Az elemleírás helyett kártyán mutatja, mit csinál az eszköztár egy eszköze és a billentyűi; ehhez az Elemleírások megjelenítése szükséges. + Selects whole objects and groups to move, resize or rotate them. Teljes objektumokat és csoportokat jelöl ki áthelyezéshez, átméretezéshez vagy forgatáshoz. + Selects anchor points and path segments to reshape a path. Horgonypontokat és útvonalszakaszokat jelöl ki egy útvonal alakjának módosításához. + Draws paths point by point, with straight segments and smooth curves. Pontról pontra rajzol útvonalakat egyenes szakaszokkal és sima görbékkel. + Draws smooth curves through the points you click. Sima görbéket rajzol a kattintott pontokon keresztül. + Adds text at a point, or in a frame you drag. Szöveget ad hozzá egy pontban vagy egy kihúzott keretben. + Draws rectangles and squares. Téglalapokat és négyzeteket rajzol. + Draws rectangles with rounded corners. Lekerekített sarkú téglalapokat rajzol. + Draws ellipses and circles. Ellipsziseket és köröket rajzol. + Draws polygons with sides of equal length. Egyenlő hosszúságú oldalú sokszögeket rajzol. + Draws stars. Csillagokat rajzol. + Turns objects around a reference point. Objektumokat forgat egy referenciapont körül. + Flips objects across an axis through a reference point. Objektumokat tükröz egy referenciaponton átmenő tengelyre. + Resizes objects from a reference point. Objektumokat méretez át egy referenciaponttól. + Slants objects from a reference point. Objektumokat dönt meg egy referenciaponttól. + Moves the view of the document. A dokumentum nézetét mozgatja. + Magnifies or reduces the view. Nagyítja vagy kicsinyíti a nézetet. + Copies the color and other attributes of one object to the selection. Egy objektum színét és egyéb jellemzőit másolja a kijelölésre. + Sets the direction and length of a gradient. Beállítja egy színátmenet irányát és hosszát. + Creates, selects and resizes artboards. Rajztáblákat hoz létre, jelöl ki és méretez át. + Changes the width of a stroke along its length. Egy körvonal szélességét módosítja a hossza mentén. + Bends art by dragging pins placed on it. A rajzot a rá helyezett tűk húzásával hajlítja. + Pushes the outlines of paths in the direction you drag. Az útvonalak körvonalát a húzás irányába tolja. + Twists the outlines of paths into swirls. Az útvonalak körvonalát örvényekké csavarja. + Pulls the outlines of paths in toward the brush. Az útvonalak körvonalát az ecset felé húzza. + Pushes the outlines of paths out from the brush. Az útvonalak körvonalát kifelé tolja az ecsettől. + Adds curved details along the outlines of paths. Ívelt részleteket ad az útvonalak körvonala mentén. + Adds spiky details along the outlines of paths. Tüskés részleteket ad az útvonalak körvonala mentén. + Adds wrinkles along the outlines of paths. Ráncokat ad az útvonalak körvonala mentén. + Moves, copies and resizes objects on the perspective grid. Objektumokat mozgat, másol és méretez át a perspektivikus rácson. + Makes a series of steps between two or more objects. Lépések sorozatát hozza létre két vagy több objektum között. + Places dimension lines that show measured lengths. Méretvonalakat helyez el, amelyek mért hosszakat mutatnak. Tap Rövid lenyomás Clear Hold Nyomva tartás törlése Hold Shortcuts Nyomva tartásos billentyűparancsok @@ -10426,7 +10610,18 @@ breakText Glyphs Glifák @msg A panel is not joined to the rest by a crease. Egy panelt egyetlen bigvonal sem köt a többihez. @msg A fold line is on a non-printing layer. Egy hajtásvonal nem nyomtatható rétegen van. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panelek: {panels}, zsanérok: {hinges}, hibák: {errors}, figyelmeztetések: {warnings} + Paper Cutouts Papírkivágások + Coral Layers Korallrétegek + Mint Layers Mentás rétegek + Midnight Layers Éjféli rétegek + Sunflower Sheet Napraforgólap + Rose Layers Rózsaszín rétegek + Monochrome Stack Monokróm köteg Dashed Arrow Szaggatott nyíl + Fine Stipple Finom pontozás + Dense Stipple Sűrű pontozás + Soft Stipple Lágy pontozás + Bold Stipple Erős pontozás Pressure Sensitive Nyomásérzékeny Flex Ribbon Rugalmas szalag Pulse Stroke Lüktető vonás @@ -10442,3 +10637,7 @@ breakText Glyphs Glifák @msg Other blanks not shown: {count} További kiterítékek nincsenek megjelenítve: {count} @msg A joint does not close by {gap} pt. Egy illesztés {gap} pt-tal nem záródik. @msg Two panels pass through each other. Két panel áthatol egymáson. + +# #5804 native-picked raster editor (draft translations; native review welcome). + Edit Original with: Eredeti szerkesztése ezzel: +file-filter Applications Alkalmazások diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index b813a940bd..d3667c0085 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -25,6 +25,639 @@ @msg {key} must be [x, y] with finite coordinates {key} harus berupa [x, y] dengan koordinat berhingga @msg ids must contain 1–10000 object ids ids harus berisi 1–10000 ID objek +# Status and error messages: 3D assets, type on a path, scripts and their File and $ objects, presets, +# PDF page sizes, Objects on Path, plug-ins, file readers and data sets. Names in backticks, command ids, +# double-quoted values and bare true, false and null stay as the English writes them; names the user +# gave keep the English's quotation marks, and numbers use a period between thousands (2.048). +@msg {what} can't be exported in 3D: {e} {what} tidak dapat diekspor dalam 3D: {e} +@msg asset {id} isn't a 3D asset aset {id} bukan aset 3D +@msg asset {id} is a 3D asset: assets.export3D writes it aset {id} adalah aset 3D: assets.export3D yang menulisnya +@msg no 3D assets yet: collect an object with a 3D effect first (assets.add3D) belum ada aset 3D: kumpulkan dulu objek dengan efek 3D (assets.add3D) +@msg select an object with a 3D effect (or give its ids) pilih objek dengan efek 3D (atau berikan id-nya) +@msg select point type or type on a path pilih teks titik atau teks pada jalur +@msg type on a path in a thread cannot use Dynamic Text: {frames} teks pada jalur dalam rangkaian tidak dapat menggunakan Teks dinamis: {frames} +@msg type on an open or compound path cannot be centered on its top or bottom: {open} teks pada jalur terbuka atau majemuk tidak dapat diletakkan di tengah pada sisi atas atau bawahnya: {open} +@msg type on a path with no length or no height cannot be centered: {flat} teks pada jalur tanpa panjang atau tanpa tinggi tidak dapat diletakkan di tengah: {flat} +@msg type on a path in a thread cannot be centered on its top or bottom: {frames} teks pada jalur dalam rangkaian tidak dapat diletakkan di tengah pada sisi atas atau bawahnya: {frames} +@msg select type on a closed path pilih teks pada jalur tertutup +@msg `Custom` stands for changed settings: save the preset under another name `Custom` berarti pengaturan yang diubah: simpan preset dengan nama lain +@msg the selection has no gradient fill seleksi tidak memiliki isian gradien +@msg the selection has no gradient stroke seleksi tidak memiliki goresan gradien +@msg the selection has no pattern fill seleksi tidak memiliki isian pola +@msg the selection has no pattern stroke seleksi tidak memiliki goresan pola +@msg no gradient swatch `{name}` tidak ada swatch gradien `{name}` +@msg no pattern swatch `{name}` tidak ada swatch pola `{name}` +@msg the library item is damaged item pustaka rusak +@msg its zlib compression is damaged kompresi zlib-nya rusak +@msg its Zstandard compression is damaged kompresi Zstandard-nya rusak +@msg it decompresses to more than {_1} MB hasil dekompresinya lebih dari {_1} MB +@msg its editing data is for a different page data penyuntingannya untuk halaman lain +@msg `fontHeightReference` must be "emBox", "capHeight", "xHeight" or "icfBox" `fontHeightReference` harus "emBox", "capHeight", "xHeight" atau "icfBox" +@msg Choose a .js or .jsx script Pilih skrip .js atau .jsx +@msg Ran {name} {name} dijalankan +@msg The script was stopped and its changes were undone Skrip dihentikan dan perubahannya dibatalkan +@msg a script is running: stop it or wait for it to finish skrip sedang berjalan: hentikan atau tunggu hingga selesai +@msg this is a compiled script, which cannot be run; use its source text ini skrip terkompilasi, yang tidak dapat dijalankan; gunakan teks sumbernya +@msg the script is not UTF-8 text skrip bukan teks UTF-8 +@msg the script is too large to run skrip terlalu besar untuk dijalankan +@msg a drag or an undo group is open; finish it before running a script seretan atau grup urungkan sedang terbuka; selesaikan sebelum menjalankan skrip +@msg the script left a document that cannot be kept skrip meninggalkan dokumen yang tidak dapat dipertahankan +@msg the script is no longer in the Scripts folder skrip tidak lagi berada di folder Skrip +@msg the script's run is no longer available proses skrip tidak lagi tersedia +@msg a failed command changed undo steps that could not be put back, so the script was stopped perintah yang gagal mengubah langkah urungkan yang tidak dapat dikembalikan, sehingga skrip dihentikan +@msg a recovery copy could not be written, so the script was not run salinan pemulihan tidak dapat ditulis, sehingga skrip tidak dijalankan +@msg Script file access denied Akses berkas skrip ditolak +@msg Script file exceeds 8 MiB Berkas skrip melebihi 8 MiB +@msg Script file is not open Berkas skrip tidak terbuka +@msg Script file cannot be decoded Berkas skrip tidak dapat didekode +@msg Script file is not a regular file Berkas skrip bukan berkas biasa +@msg Script file does not exist Berkas skrip tidak ada +@msg Script file could not be read Berkas skrip tidak dapat dibaca +@msg Script folder has more than 2,048 entries Folder skrip memiliki lebih dari 2.048 entri +@msg Script file open mode must be r, w, e or a Mode buka berkas skrip harus r, w, e atau a +@msg Script file writing is not available Penulisan berkas skrip tidak tersedia +@msg Script file dialogs are not available Dialog berkas skrip tidak tersedia +@msg Script files cannot be opened in another application Berkas skrip tidak dapat dibuka di aplikasi lain +@msg Script file access is unavailable on the web Akses berkas skrip tidak tersedia di web +@msg Script has 256 files open Skrip membuka 256 berkas +@msg Script file path exceeds 32,767 characters Jalur berkas skrip melebihi 32.767 karakter +@msg Script folder mask takes too many steps to match Masker folder skrip memerlukan terlalu banyak langkah untuk dicocokkan +@msg the script opened more file data than one run may open (32 MiB) skrip membuka lebih banyak data berkas daripada yang boleh dibuka satu proses (32 MiB) +@msg File.seek: takes a position and a mode File.seek: menerima posisi dan mode +@msg vc.run: give a command id, as a string vc.run: berikan id perintah, sebagai string +@msg vc.run: takes a command id and an object of parameters vc.run: menerima id perintah dan objek parameter +@msg vc.run: the parameters must be an object vc.run: parameter harus berupa objek +@msg vc.run: the result{place} is too large for a script vc.run: hasil{place} terlalu besar untuk skrip +@msg $.evalFile requires a file path $.evalFile memerlukan jalur berkas +@msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: batas waktu harus berupa jumlah milidetik yang berhingga, 0 atau lebih +@msg $.evalFile: takes a file path and a timeout $.evalFile: menerima jalur berkas dan batas waktu +@msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: baris {line}, kolom {column} dari {file}: {e} (dilempar) +@msg {name}: line {line}, column {column}: {e} (thrown) {name}: baris {line}, kolom {column}: {e} (dilempar) +@msg {name}: {e} (thrown) {name}: {e} (dilempar) +@msg {name}: line {line}, column {column} of {file}: {e} (limit) {name}: baris {line}, kolom {column} dari {file}: {e} (batas) +@msg {name}: line {line}, column {column}: {e} (limit) {name}: baris {line}, kolom {column}: {e} (batas) +@msg {name}: {e} (limit) {name}: {e} (batas) +@msg {name}: line {line}, column {column} of {file}: {e} (syntax) {name}: baris {line}, kolom {column} dari {file}: {e} (sintaksis) +@msg {name}: line {line}, column {column}: {e} (syntax) {name}: baris {line}, kolom {column}: {e} (sintaksis) +@msg {name}: {e} (syntax) {name}: {e} (sintaksis) +@msg {name}: line {line}, column {column} of {file}: {e} (stopped) {name}: baris {line}, kolom {column} dari {file}: {e} (dihentikan) +@msg {name}: line {line}, column {column}: {e} (stopped) {name}: baris {line}, kolom {column}: {e} (dihentikan) +@msg {name}: {e} (stopped) {name}: {e} (dihentikan) +@msg {name}: line {line}, column {column} of {file}: {e} (internal) {name}: baris {line}, kolom {column} dari {file}: {e} (galat internal) +@msg {name}: line {line}, column {column}: {e} (internal) {name}: baris {line}, kolom {column}: {e} (galat internal) +@msg {name}: {e} (internal) {name}: {e} (galat internal) +@msg {e} (these files stay written: {paths}) {e} (berkas-berkas ini tetap tertulis: {paths}) +@msg $.{name}: give a name, as a string $.{name}: berikan nama, sebagai string +@msg $.locale: give a locale such as "en" or "de_DE", or null for the interface's $.locale: berikan lokal seperti "en" atau "de_DE", atau null untuk lokal antarmuka +@msg $.localize: give true or false $.localize: berikan true atau false +@msg $.flags: only 512, which turns localization on, or 0 can be set $.flags: hanya 512, yang menyalakan lokalisasi, atau 0 yang dapat ditetapkan +@msg $.flags: give a number $.flags: berikan angka +@msg $.appEncoding: scripts here read and write UTF-8 only $.appEncoding: skrip di sini hanya membaca dan menulis UTF-8 +@msg $.appEncoding: give an encoding's name, as a string $.appEncoding: berikan nama pengodean, sebagai string +@msg $.memCache: the memory cache size cannot be set $.memCache: ukuran cache memori tidak dapat ditetapkan +@msg $.setenv: give a value, as a string $.setenv: berikan nilai, sebagai string +@msg $.setenv: only {_1} can be set $.setenv: hanya {_1} yang dapat ditetapkan +@msg $.setenv: a value has at most {MAX_ENV_BYTES} letters, digits and _ . - @ $.setenv: nilai berisi paling banyak {MAX_ENV_BYTES} huruf, angka, dan _ . - @ +@msg $.sleep: give a number of milliseconds from 0 to {MAX_SLEEP_MS} $.sleep: berikan jumlah milidetik dari 0 sampai {MAX_SLEEP_MS} +@msg $.sleep: give a number of milliseconds $.sleep: berikan jumlah milidetik +@msg $.sleep: a run cannot wait inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code $.sleep: proses tidak dapat menunggu di dalam callback fungsi bawaan, getter, konversi, atau berkas yang dijalankan $.evalFile; panggil dari kode skrip itu sendiri +@msg $.bp: scripts here have no debugger $.bp: skrip di sini tidak memiliki debugger +@msg $.colorPicker: scripts cannot show a dialog yet $.colorPicker: skrip belum dapat menampilkan dialog +@msg {name}: give a message {name}: berikan pesan +@msg {name}: give the text the field starts with {name}: berikan teks awal kolom isian +@msg {name}: the message is longer than 16 KiB {name}: pesan lebih panjang dari 16 KiB +@msg {name}: the title is longer than 256 bytes {name}: judul lebih panjang dari 256 byte +@msg {name}: the text the field starts with is longer than 16 KiB {name}: teks awal kolom isian lebih panjang dari 16 KiB +@msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: dialog tidak dapat dibuka di dalam callback fungsi bawaan, getter, konversi, atau berkas yang dijalankan $.evalFile; panggil dari kode skrip itu sendiri +@msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: jawaban berikutnya di `answers` untuk {_1}, bukan {name} +@msg {name}: `answers` has no answer left for this dialog {name}: `answers` tidak memiliki jawaban tersisa untuk dialog ini +@msg `answers` must be a list of answers `answers` harus berupa daftar jawaban +@msg `answers` has more than {MAX_ANSWERS} answers `answers` berisi lebih dari {MAX_ANSWERS} jawaban +@msg `answers` is larger than 1 MiB `answers` lebih besar dari 1 MiB +@msg must be an object with `kind` and `value` harus berupa objek dengan `kind` dan `value` +@msg must have exactly `kind` and `value` harus memiliki tepat `kind` dan `value` +@msg is an alert's answer, whose `value` must be "ok" adalah jawaban alert, yang `value`-nya harus "ok" +@msg is a confirm's answer, whose `value` must be true or false adalah jawaban confirm, yang `value`-nya harus true atau false +@msg is longer than 16 KiB lebih panjang dari 16 KiB +@msg is a prompt's answer, whose `value` must be a string or null adalah jawaban prompt, yang `value`-nya harus berupa string atau null +@msg must have `kind` alert, confirm or prompt harus memiliki `kind` alert, confirm, atau prompt +@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` hanya untuk proses tanpa orang yang dapat ditanya: di aplikasi, pengguna menjawab setiap dialog +@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` harus berupa bilangan bulat dari 1 sampai {_1} +@msg `args{place}` is nested more than 64 levels deep `args{place}` bersarang lebih dari 64 tingkat +@msg `args` must be an object `args` harus berupa objek +@msg `args` is larger than 1 MiB `args` lebih besar dari 1 MiB +@msg `path` is empty `path` kosong +@msg `installed` takes a `path`, not a `source` `installed` menerima `path`, bukan `source` +@msg `path` must name a .js or .jsx file `path` harus menyebut file .js atau .jsx +@msg give exactly one of `path` and `source` berikan tepat satu dari `path` dan `source` +@msg [{j}] `{_1}`: {why} [{j}] `{_1}`: {why} +@msg `answers[{i}]` {e} `answers[{i}]` {e} +@msg vc.document{place} is too large for a script vc.document{place} terlalu besar untuk skrip +@msg vc.log: the log of this run is full vc.log: log proses ini penuh +@msg this function's script run has ended proses skrip fungsi ini telah berakhir +@msg the script made more host calls than one run may make skrip melakukan lebih banyak panggilan host daripada yang boleh dilakukan satu proses +@msg the script passed more data to and from commands than one run may pass skrip mengirim lebih banyak data ke dan dari perintah daripada yang boleh dikirim satu proses +@msg the script added more objects and data to the documents than one run may add skrip menambahkan lebih banyak objek dan data ke dokumen daripada yang boleh ditambahkan satu proses +@msg {what}: the object is not a File or a Folder {what}: objek bukan File atau Folder +@msg {what}: the count must be a finite number, 0 or more {what}: jumlah harus berupa angka berhingga, 0 atau lebih +@msg File.seek: the position must be a finite number File.seek: posisi harus berupa angka berhingga +@msg File.seek: the mode must be 0, 1 or 2 File.seek: mode harus 0, 1 atau 2 +@msg script file is compiled: {value} berkas skrip terkompilasi: {value} +@msg `name` must be the name of a script engine `name` harus berupa nama mesin skrip +@msg the main script engine is new for each run and is never kept, so it cannot be dropped mesin skrip utama dibuat baru untuk setiap proses dan tidak pernah disimpan, sehingga tidak dapat dibuang +@msg there is no script engine named {name} tidak ada mesin skrip bernama {name} +@msg Running a script Menjalankan skrip +@msg Data Recovery can't keep copies in {path}: {e} Pemulihan data tidak dapat menyimpan salinan di {path}: {e} +@msg Plug-ins can't be loaded from {path}: {e} Plug-in tidak dapat dimuat dari {path}: {e} +@msg select a path pilih jalur +@msg Save writes {_1}, not {_2}: use file.saveAsTemplate to write it Simpan menulis {_1}, bukan {_2}: gunakan file.saveAsTemplate untuk menulisnya +@msg aiVersion 7 writes legacy .ai files, not .ait templates aiVersion 7 menulis berkas .ai lama, bukan templat .ait +@msg `groupColors` must be an array `groupColors` harus berupa larik +@msg `preserve` must be an object `preserve` harus berupa objek +@msg `{key}` must be an array `{key}` harus berupa larik +@msg `{key}` must be a #rrggbb color `{key}` harus berupa warna #rrggbb +@msg `{key}` must be a #rrggbb color or a layer color name `{key}` harus berupa warna #rrggbb atau nama warna lapisan +@msg unknown Live Paint option `{key}` opsi Live Paint tidak dikenal `{key}` +@msg unknown Shape Builder option `{key}` opsi Pembangun bentuk tidak dikenal `{key}` +@msg `{key}` must be a profile name or null `{key}` harus berupa nama profil atau null +@msg `top` and `below` can't both be true `top` dan `below` tidak boleh keduanya true +@msg `select` must be true or false `select` harus true atau false +@msg `minAnchors` and `maxAnchors` must be whole numbers `minAnchors` dan `maxAnchors` harus bilangan bulat +@msg `{key}` must be a number not below 0 `{key}` harus berupa angka tidak kurang dari 0 +@msg `{key}` must be four numbers not below 0: [tl, tr, br, bl] `{key}` harus berupa empat angka tidak kurang dari 0: [tl, tr, br, bl] +@msg `{key}` must be [x, y, width, height]: four finite numbers, width and height not negative `{key}` harus berupa [x, y, width, height]: empat angka berhingga, width dan height tidak negatif +@msg `{min_key}` is greater than `{max_key}` `{min_key}` lebih besar dari `{max_key}` +@msg give at least one of `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` berikan setidaknya satu dari `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` +@msg a process color can't colorize a grayscale image with transparency: use a spot color, black or white warna proses tidak dapat mewarnai gambar skala abu-abu yang memiliki transparansi: gunakan warna spot, hitam atau putih +@msg a key object sits on that point objek kunci berada di titik itu +@msg `name` is empty `name` kosong +@msg `newName` is empty `newName` kosong +@msg `{name}` is a built-in preset and can't change: save it under another name `{name}` adalah preset bawaan dan tidak dapat diubah: simpan dengan nama lain +@msg `{name}` is a built-in preset and stays `{name}` adalah preset bawaan dan tetap ada +@msg a spine keeps at least two points rangka mempertahankan setidaknya dua titik +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel` berupa null, nama warna lapisan, atau #rrggbb +@msg the Simplify slider is not open penggeser Sederhanakan tidak terbuka +@msg the Smooth slider is not open penggeser Haluskan tidak terbuka +@msg handle must be in or out handle harus in atau out +@msg index must be ≥ 0 index harus ≥ 0 +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller halaman artboard {n} berukuran {size}, lebih panjang dari batas halaman PDF 14.400 pt (200 in): halaman ditulis dengan UserUnit {unit}, sehingga aplikasi yang mengabaikan UserUnit menampilkannya sekian kali lebih kecil +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller: turn on Write pages longer than 200 in at full size in points halaman artboard {n} berukuran {size}, lebih panjang dari batas halaman PDF 14.400 pt (200 in): halaman ditulis dengan UserUnit {unit}, sehingga aplikasi yang mengabaikan UserUnit menampilkannya sekian kali lebih kecil: aktifkan Tulis halaman yang lebih panjang dari 200 in dalam ukuran penuh, dalam poin +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in halaman artboard {n} berukuran {size}, lebih panjang dari batas halaman PDF 14.400 pt (200 in): halaman {label} ditulis tanpa UserUnit, dalam poin, dan aplikasi yang mematuhi batas itu memotong halaman menjadi 200 in +@msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 PDF 1.5 tidak memiliki UserUnit, yang diperlukan halaman lebih panjang dari 14.400 pt (200 in) untuk mempertahankan ukurannya: berkas ditulis sebagai PDF 1.6 +@msg PDF 1.4 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to stay within PDF/A-2's page limit of 14,400 units: the file is written as PDF 1.6 PDF 1.4 tidak memiliki UserUnit, yang diperlukan halaman lebih panjang dari 14.400 pt (200 in) agar tetap dalam batas halaman PDF/A-2 sebesar 14.400 unit: berkas ditulis sebagai PDF 1.6 +@msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units halaman artboard {n} berukuran {size}, terlalu panjang dan sempit untuk sisi halaman PDF 3 sampai 14.400 unit: halaman ditulis dengan UserUnit {unit}, yang menjaga sisi pendek tetap 3 unit atau lebih, dan aplikasi yang mematuhi batas itu memotong sisi panjang menjadi 14.400 unit +@msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard berkas {label} menyimpan bilangan real hingga {max}, dan halaman artboard {n}, sepanjang {side} pt, memerlukan bilangan yang lebih besar: pilih PDF 1.6 atau lebih baru tanpa standar PDF/X, atau artboard yang lebih kecil +@msg line {line}: value for `{var}` must be true or false baris {line}: nilai untuk `{var}` harus true atau false +@msg line {line}: value for `{var}` is longer than {MAX_GRAPH_CSV} bytes baris {line}: nilai untuk `{var}` lebih panjang dari {MAX_GRAPH_CSV} byte +@msg a bristle brush name can have at most {max} characters: `{name}` has {count} nama kuas bulu paling banyak {max} karakter: `{name}` memiliki {count} +@msg `{file}` isn't a VectorCraft document, a PDF or a PDF-compatible .ai file `{file}` bukan dokumen VectorCraft, PDF, atau berkas .ai yang kompatibel dengan PDF +@msg no saved preset named `{name}` tidak ada preset tersimpan bernama `{name}` +@msg no saved preset named `{name}` to rename tidak ada preset tersimpan bernama `{name}` untuk diganti namanya +@msg `{ID}`: the reference would be larger than {MAX_BYTES} bytes `{ID}`: referensi akan lebih besar dari {MAX_BYTES} byte +@msg the artboard is locked artboard terkunci +@msg no such spine point tidak ada titik rangka seperti itu +@msg `with` must be a list of at most 10000 spine point indexes `with` harus berupa daftar berisi paling banyak 10000 indeks titik rangka +@msg `with` moves points, not a handle `with` memindahkan titik, bukan handle +@msg no such spine segment tidak ada segmen rangka seperti itu +@msg node {_1} is on a locked artboard simpul {_1} berada di artboard yang terkunci +@msg not a blend bukan blend +@msg not a PICT file bukan berkas PICT +@msg thumbnail: no page {n} (the file has 1) gambar mini: tidak ada halaman {n} (berkas memiliki 1) +@msg select a blend or give `id` pilih blend atau berikan `id` +@msg select an Objects on Path group pilih grup Objek pada jalur +@msg choose the object to detach with its Select/Move widget pilih objek yang akan dilepas dengan widget Pilih/Pindahkan-nya +@msg a path inside a compound path, blend, envelope, repeat or Intertwine group can't take objects jalur di dalam jalur majemuk, blend, amplop, perulangan, atau grup Jalin tidak dapat menerima objek +@msg a clipping path can't take objects jalur kliping tidak dapat menerima objek +@msg objects inside a blend, envelope, repeat or Intertwine group can't be attached to a path objek di dalam blend, amplop, perulangan, atau grup Jalin tidak dapat dilekatkan ke jalur +@msg a clipping path can't be attached to a path jalur kliping tidak dapat dilekatkan ke jalur +@msg `background` must be edges, corners or colors `background` harus edges, corners atau colors +@msg `match` must be distance or channels `match` harus distance atau channels +@msg `{key}` must be from 0 to 100 `{key}` harus dari 0 sampai 100 +@msg `colors` must list 1 to 16 colors, each hex (#rrggbb or #rgb) or black, white, red, green or blue `colors` harus berisi 1 sampai 16 warna, masing-masing heksadesimal (#rrggbb atau #rgb) atau black, white, red, green atau blue +@msg the linked image shows its preview: embed or relink it first gambar tertaut menampilkan pratinjaunya: sematkan atau tautkan ulang terlebih dahulu +@msg a CMYK image has no transparency to set gambar CMYK tidak memiliki transparansi untuk ditetapkan +@msg every pixel matches the background: no image would be left setiap piksel cocok dengan latar belakang: tidak akan ada gambar yang tersisa +@msg an image of {w} × {h} pixels is too large to change gambar berukuran {w} × {h} piksel terlalu besar untuk diubah +@msg select an image with a color mask pilih gambar dengan masker warna +@msg the color mask's settings are out of range pengaturan masker warna berada di luar rentang +@msg a CMYK image can't take a color mask gambar CMYK tidak dapat diberi masker warna +@msg the mask would hide every pixel masker akan menyembunyikan setiap piksel +@msg Recolor completed; {locked} and {hidden} were left unchanged Pewarnaan ulang selesai; {locked} dan {hidden} dibiarkan tanpa perubahan +@msg Recolor completed; {objects} were left unchanged Pewarnaan ulang selesai; {objects} dibiarkan tanpa perubahan +@msg Recolor completed; {objects} was left unchanged Pewarnaan ulang selesai; {objects} dibiarkan tanpa perubahan +@msg 1 locked object 1 objek terkunci +@msg {n} locked objects {n} objek terkunci +@msg 1 hidden object 1 objek tersembunyi +@msg {n} hidden objects {n} objek tersembunyi +@msg t, dx and dy must be finite t, dx dan dy harus berhingga +@msg the blend has no spine blend tidak memiliki rangka +@msg the spine has no segments rangka tidak memiliki segmen +@msg panels can't be shown in Presentation Mode panel tidak dapat ditampilkan dalam Mode presentasi +@msg unknown preset `{name}`: not a built-in or saved preset (see imageTrace.presets) preset tidak dikenal `{name}`: bukan preset bawaan atau tersimpan (lihat imageTrace.presets) +@msg variables are locked variabel terkunci +@msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} lebih dari {MAX_CSV_ROWS} himpunan data: Impor himpunan data membaca paling banyak {MAX_CSV_ROWS} +@msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} lebih dari {MAX_CSV_COLS} variabel: Impor himpunan data membaca paling banyak {MAX_CSV_COLS} +@msg `{key}: {top}` and `options.{key}: {inner}` disagree: give the option once `{key}: {top}` dan `options.{key}: {inner}` tidak sesuai: berikan opsi itu satu kali saja +@msg x and y must be finite x dan y harus berhingga +@msg {_1} is an exporter (File › Export › Export As…) {_1} adalah pengekspor (Berkas › Ekspor › Ekspor sebagai…) +@msg `documentData` is {size} bytes (limit {MAX_DOCUMENT_DATA}) `documentData` berukuran {size} byte (batas {MAX_DOCUMENT_DATA}) +@msg a mask that covers several layers comes in as a clipping group in each layer it covers masker yang mencakup beberapa lapisan dibaca sebagai grup kliping di setiap lapisan yang dicakupnya +@msg a graph's records don't end where they should: its art was read as it is catatan grafik tidak berakhir di tempat yang semestinya: karyanya dibaca apa adanya +@msg `{w}` takes no operands `{w}` tidak menerima operan +@msg a wraparound group is inside a compound path grup pembungkus berada di dalam jalur majemuk +@msg it ends inside a multi-layer mask berakhir di dalam masker multi-lapisan +@msg a multi-layer mask's operators are out of order operator masker multi-lapisan tidak berurutan +@msg a multi-layer mask needs one clipping path masker multi-lapisan memerlukan satu jalur kliping +@msg a group crosses a multi-layer mask grup melintasi masker multi-lapisan +@msg graphs come in as plain art, without their data or settings grafik dibaca sebagai karya biasa, tanpa data atau pengaturannya +@msg the active document changed while the question was open; nothing was deleted dokumen aktif berubah saat pertanyaan terbuka; tidak ada yang dihapus +@msg The link is inside a symbol, graph design, pattern or opacity mask and has no place on the canvas Tautan berada di dalam simbol, desain grafik, pola, atau masker opasitas dan tidak memiliki tempat di kanvas +@msg source must be the id of a Shaper Group's original shape source harus berupa id bentuk asli Grup Shaper +@msg group must be the id of a Shaper Group group harus berupa id Grup Shaper +@msg the shape is not an editable original shape of that Shaper Group bentuk itu bukan bentuk asli yang dapat diedit dari Grup Shaper tersebut +@msg id {value} is a layer, not an object id {value} adalah lapisan, bukan objek +@msg id {value} is a layer, not an object; move layers with layer.move id {value} adalah lapisan, bukan objek; pindahkan lapisan dengan layer.move +@msg the PCX file is cut short berkas PCX terpotong +@msg the PCX file's header is damaged header berkas PCX rusak +@msg PCX files with {bits}-bit pixels in {planes} planes can't be read berkas PCX dengan piksel {bits}-bit dalam {planes} bidang tidak dapat dibaca +@msg the Pixar file is cut short berkas Pixar terpotong +@msg the Pixar file's header is damaged header berkas Pixar rusak +@msg the Pixar file's image data is damaged data gambar berkas Pixar rusak +@msg the JPEG 2000 file can't be read berkas JPEG 2000 tidak dapat dibaca +@msg the JPEG 2000 file has an unsupported color space or JPX content berkas JPEG 2000 memiliki ruang warna atau konten JPX yang tidak didukung +@msg the HEIC or HEIF file can't be read berkas HEIC atau HEIF tidak dapat dibaca +@msg the HEIC or HEIF file holds a kind of image that can't be read berkas HEIC atau HEIF berisi jenis gambar yang tidak dapat dibaca +@msg HEIC and HEIF images can't be opened in this build gambar HEIC dan HEIF tidak dapat dibuka di build ini +@msg the JPEG XL file is cut short berkas JPEG XL terpotong +@msg the JPEG XL container is too large to read kontainer JPEG XL terlalu besar untuk dibaca +@msg CMYK JPEG XL images can't be read gambar JPEG XL CMYK tidak dapat dibaca +@msg the JPEG XL file can't be read: {e} berkas JPEG XL tidak dapat dibaca: {e} +@msg Extrude & Bevel Ekstrusi & bevel +@msg Revolve Revolusi +@msg Inflate Gelembungkan +@msg Rotate Putar +@msg Extrude & Bevel (Classic) Ekstrusi & bevel (klasik) +@msg Revolve (Classic) Revolusi (klasik) +@msg Rotate (Classic) Putar (klasik) +@msg This effect Efek ini +@msg clipping paths jalur kliping +@msg other objects objek lain +@msg {label} requires a group holding a shape with at least two anchors {label} memerlukan grup yang berisi bentuk dengan setidaknya dua titik jangkar +@msg Revolve requires a group holding a shape with at least two anchors Revolusi memerlukan grup yang berisi bentuk dengan setidaknya dua titik jangkar +@msg Revolve requires a shape with at least two anchors Revolusi memerlukan bentuk dengan setidaknya dua titik jangkar +@msg {label} on a group needs paths, compound paths, type, groups, clipping groups, blends and symbol instances: release or expand its {what} first. {label} pada grup memerlukan jalur, jalur majemuk, teks, grup, grup kliping, blend, dan instans simbol: lepaskan atau perluas {what}-nya terlebih dahulu. +@msg {label} on a group takes at most {MAX_MEMBERS} objects {label} pada grup menerima paling banyak {MAX_MEMBERS} objek +@msg A 3D effect on a group or layer goes on the group itself, not on its fill or stroke Efek 3D pada grup atau lapisan diterapkan pada grup itu sendiri, bukan pada isian atau goresannya +@msg a 3D effect on a group's fill or stroke draws nothing efek 3D pada isian atau goresan grup tidak menggambar apa pun +@msg a 3D effect on a group's fill or stroke draws nothing to export efek 3D pada isian atau goresan grup tidak menggambar apa pun untuk diekspor +@msg The 3D object is too complex to export Objek 3D terlalu rumit untuk diekspor +@msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) objek tidak memiliki efek 3D (Ekstrusi & bevel, Revolusi, Gelembungkan, atau Putar) +@msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` harus berupa objek yang hanya berisi `mode`, bernilai shaded atau wireframe +@msg its 3D effect builds no solid efek 3D-nya tidak membangun bentuk padat +@msg bevel must be none or one of {_1} bevel harus none atau salah satu dari {_1} +@msg {_1} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects {_1} tidak dapat membangun bentuk padat dari karya ini: instans simbol, blend, dan grup klipingnya berisi terlalu banyak objek +@msg {label} can't build a solid from the instance of symbol "{symbol}": the symbol's art isn't available {label} tidak dapat membangun bentuk padat dari instans simbol "{symbol}": karya simbol tidak tersedia +@msg {_1}: the clipping path is too complex to cut the art with {_1}: jalur kliping terlalu rumit untuk memotong karya +@msg {_1} takes at most {MAX_MEMBERS} objects {_1} menerima paling banyak {MAX_MEMBERS} objek +@msg {_1} can't build solids from art nested more than {MAX_DEPTH} levels deep {_1} tidak dapat membangun bentuk padat dari karya yang bersarang lebih dari {MAX_DEPTH} tingkat +@msg Revolve paint is too complex for this surface; reduce Segments or simplify the gradient Cat Revolusi terlalu rumit untuk permukaan ini; kurangi Segmen atau sederhanakan gradien +@msg Revolve edge must be left or right edge Revolusi harus left atau right +@msg Revolve cap must be a boolean cap Revolusi harus berupa boolean +@msg the revolved object has no fill or stroke objek hasil revolusi tidak memiliki isian atau goresan +@msg lightColor must be an opaque RGB color in #rrggbb form lightColor harus berupa warna RGB buram dalam bentuk #rrggbb +@msg lights must contain one to ten lights lights harus berisi satu sampai sepuluh cahaya +@msg each light must be an object setiap cahaya harus berupa objek +@msg unknown light setting: use color, intensity, rotation, height, softness or behind pengaturan cahaya tidak dikenal: gunakan color, intensity, rotation, height, softness atau behind +@msg light {key} must be a number from {min} to {max} {key} cahaya harus berupa angka dari {min} sampai {max} +@msg light color must use opaque #rrggbb color cahaya harus menggunakan #rrggbb buram +@msg light behind must be true or false behind cahaya harus true atau false +@msg shadow must be true or false shadow harus true atau false +@msg shadowPosition must be behind or below shadowPosition harus behind atau below +@msg {key} must be a number from {min} to {max} {key} harus berupa angka dari {min} sampai {max} +@msg each of `{GRAPHICS}` must be an object setiap `{GRAPHICS}` harus berupa objek +@msg `{GRAPHICS}` entries take symbol, face, x, y, scale and rotation, not `{k}` entri `{GRAPHICS}` menerima symbol, face, x, y, scale dan rotation, bukan `{k}` +@msg each of `{GRAPHICS}` needs `symbol`, the name of a symbol setiap `{GRAPHICS}` memerlukan `symbol`, nama sebuah simbol +@msg `{GRAPHICS}` face must be front or back face `{GRAPHICS}` harus front atau back +@msg `{GRAPHICS}` face must be front, back or side face `{GRAPHICS}` harus front, back, atau side +@msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} `{GRAPHICS}` harus berupa angka dari {lo} sampai {hi} +@msg `{GRAPHICS}` must be an array `{GRAPHICS}` harus berupa larik +@msg Graphics map onto the Plane, Extrude and Revolve object types Grafis dipetakan ke jenis objek Plane, Extrude, dan Revolve +@msg Revolve maps graphics onto its side: map them onto the front Revolusi memetakan grafis ke sisinya: petakan ke bagian depan +@msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Grafis terlalu rumit untuk permukaan ini: sederhanakan karya simbol atau kurangi Segmen +@msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` menerima paling banyak {MAX_GRAPHICS} grafis +@msg A plane has one face: map its graphics onto the front Bidang memiliki satu sisi: petakan grafisnya ke bagian depan +@msg The graphics are too complex: simplify the symbols' art Grafis terlalu rumit: sederhanakan karya simbol +@msg A graphic's art may be nested at most {MAX_LEVELS} levels deep: simplify the symbol's art Karya grafis boleh bersarang paling dalam {MAX_LEVELS} tingkat: sederhanakan karya simbol +@msg A graphic's art may nest symbols at most {MAX_NESTING} levels deep: simplify the symbol's art Karya grafis boleh menyarangkan simbol paling dalam {MAX_NESTING} tingkat: sederhanakan karya simbol +@msg A graphic's art holds too many objects: simplify the symbol's art Karya grafis berisi terlalu banyak objek: sederhanakan karya simbol +@msg A graphic draws at most {MAX_PIECES} fills and strokes: simplify the symbol's art Grafis menggambar paling banyak {MAX_PIECES} isian dan goresan: sederhanakan karya simbol +@msg `surface` must be one of {_1} `surface` harus salah satu dari {_1} +@msg {label} draws the source art for this object instead of its 3D surface {label} menggambar karya sumber untuk objek ini, bukan permukaan 3D-nya +@msg {label} draws no faces for this object {label} tidak menggambar sisi apa pun untuk objek ini +@msg the wireframe has more than {MAX_WIRE_EDGES} edges kerangka kawat memiliki lebih dari {MAX_WIRE_EDGES} tepi +@msg the params must be an object, not {got} parameter harus berupa objek, bukan {got} +@msg unknown parameter `{path}`; the object takes no keys parameter tidak dikenal `{path}`; objek tidak menerima kunci apa pun +@msg unknown parameter `{path}`; it takes: {keys} parameter tidak dikenal `{path}`; yang diterima: {keys} +@msg missing `{path}` `{path}` tidak ada +@msg `{path}` must be {expected}, not {got} `{path}` harus {expected}, bukan {got} +@msg `{path}` is nested too deeply `{path}` bersarang terlalu dalam +@msg {path}: not a PNG, JPEG, WebP, TIFF or BMP image {path}: bukan gambar PNG, JPEG, WebP, TIFF, atau BMP +@msg the image is {iw} × {ih} pixels and the artboard at that width is {rw} × {rh} pixels: their proportions differ gambar berukuran {iw} × {ih} piksel dan artboard pada lebar itu berukuran {rw} × {rh} piksel: proporsinya berbeda +@msg `threshold` must be a number from 0 to 1 `threshold` harus berupa angka dari 0 sampai 1 +@msg background {v}: a color such as "#808080" background {v}: warna seperti "#808080" +@msg comparing with an image file isn't available in the browser membandingkan dengan berkas gambar tidak tersedia di peramban +@msg columns {first} and {column} both name the variable `{name}` kolom {first} dan {column} sama-sama menamai variabel `{name}` +@msg nothing in data set {name} was applied: no object is bound to a variable it has a value for tidak ada isi himpunan data {name} yang diterapkan: tidak ada objek yang terikat ke variabel yang memiliki nilai di dalamnya +@msg no bound object reports a value (locked objects and embedded images report none) tidak ada objek terikat yang melaporkan nilai (objek terkunci dan gambar tersemat tidak melaporkan apa pun) +@msg Edit Original opens image and document files only; “{name}” is not one Edit asli hanya membuka berkas gambar dan dokumen; “{name}” bukan salah satunya +@msg only http, https and mailto URLs open in the browser, not “{url}” hanya URL http, https, dan mailto yang dibuka di peramban, bukan “{url}” +@msg {id} opens another app: only the person at the keyboard can run it {id} membuka aplikasi lain: hanya orang di depan papan tik yang dapat menjalankannya +@msg “{name}” is not a file “{name}” bukan berkas +@msg a mask has more than one art block masker memiliki lebih dari satu blok karya +@msg mask art ends outside a mask dictionary karya masker berakhir di luar kamus masker +@msg cancelled; nothing was changed dibatalkan; tidak ada yang diubah +@msg a linked image can't become a gradient mesh: embed it first gambar tertaut tidak dapat menjadi mesh gradien: sematkan terlebih dahulu +@msg the image has no usable size or position gambar tidak memiliki ukuran atau posisi yang dapat digunakan +@msg the image's pixels can't be read piksel gambar tidak dapat dibaca +@msg Persistent libraries not found: {files} Pustaka permanen tidak ditemukan: {files} +@msg `{given}` isn't a library panel (see window.swatchLibrary) `{given}` bukan panel pustaka (lihat window.swatchLibrary) +@msg library panel `{given}` isn't open panel pustaka `{given}` tidak terbuka +@msg too many changed shortcuts terlalu banyak pintasan yang diubah +@msg library panel `{given}` isn't missing its library panel pustaka `{given}` tidak kehilangan pustakanya +@msg too many library panels were opened in this session terlalu banyak panel pustaka yang dibuka dalam sesi ini +@msg The image is {_1} × {_2} pixels, more than {LARGE_TRACE_SIDE} on a side: it is traced, but more slowly. A lower-fidelity preset or a smaller copy of the image traces faster. Gambar berukuran {_1} × {_2} piksel, lebih dari {LARGE_TRACE_SIDE} per sisi: gambar tetap dilacak, tetapi lebih lambat. Preset dengan fidelitas lebih rendah atau salinan gambar yang lebih kecil dilacak lebih cepat. +@msg The image was traced at {_1} × {_2} pixels, scaled down from {_3} × {_4} ({_5} megapixels at most). Gambar dilacak pada {_1} × {_2} piksel, diperkecil dari {_3} × {_4} (paling banyak {_5} megapiksel). +@msg byColor must be true or false byColor harus true atau false +@msg byColor can't split Auto Grouping groups: trace without Auto Grouping byColor tidak dapat memisahkan grup Pengelompokan otomatis: lacak tanpa Pengelompokan otomatis +@msg byColor can't regroup a trace with a live Pathfinder effect: expand without byColor byColor tidak dapat mengelompokkan ulang hasil lacak dengan efek Pathfinder langsung: perluas tanpa byColor +@msg Flat Logo mode does not use keepColors: it traces the colors named in logoColors, or the colors it finds. Mode Logo flat tidak menggunakan keepColors: mode ini melacak warna yang disebut dalam logoColors, atau warna yang ditemukannya. +@msg Nothing was traced: none of the colors the trace found matches keepColors ({_1}). Tidak ada yang dilacak: tidak satu pun warna yang ditemukan pelacakan cocok dengan keepColors ({_1}). +@msg Nothing was traced: Ignore Color leaves out every area of the colors keepColors lists. Tidak ada yang dilacak: Abaikan warna melewatkan setiap area dari warna yang didaftarkan keepColors. +@msg Nothing was traced: the colors that match keepColors produce no paths. Tidak ada yang dilacak: warna yang cocok dengan keepColors tidak menghasilkan jalur. +@msg keepColors: none of the colors the trace found matches {c}, so nothing of it is traced. keepColors: tidak satu pun warna yang ditemukan pelacakan cocok dengan {c}, sehingga tidak ada bagiannya yang dilacak. +@msg `colorGroup` needs `library: "document"` `colorGroup` memerlukan `library: "document"` +@msg `colorGroup` needs `palette: "documentLibrary"` `colorGroup` memerlukan `palette: "documentLibrary"` +@msg `colorGroup` needs `mode: "color"` `colorGroup` memerlukan `mode: "color"` +@msg no color group `{name}` in the document (see swatch.list) tidak ada grup warna `{name}` di dokumen (lihat swatch.list) +@msg Flat Logo traced the image at {_1} × {_2} pixels, averaged down from {_3} × {_4}. Logo flat melacak gambar pada {_1} × {_2} piksel, dirata-ratakan dari {_3} × {_4}. +@msg {label} keeps 1 of the document's {n} artboards: the file reopens with one. Turn on Preserve Editing Capabilities to keep them all. {label} hanya mempertahankan 1 dari {n} artboard dokumen: berkas dibuka kembali dengan satu artboard. Aktifkan Pertahankan kemampuan pengeditan untuk mempertahankan semuanya. +@msg `spread` must be pad, repeat or reflect `spread` harus pad, repeat atau reflect +@msg `repeats` must be a whole number from 1 to {MAX_REPEATS} `repeats` harus berupa bilangan bulat dari 1 sampai {MAX_REPEATS} +@msg `spread` applies to linear, radial, conic and diamond gradients `spread` berlaku untuk gradien linear, radial, conic, dan diamond +@msg {_1} finished, but the document or the plug-in changed meanwhile: run it again {_1} selesai, tetapi dokumen atau plug-in berubah sementara itu: jalankan lagi +@msg Running “{name}”… Menjalankan “{name}”… +@msg a live effect runs while the document is drawn, so it can't be `heavy` efek langsung berjalan saat dokumen digambar, sehingga tidak dapat `heavy` +@msg an exporter always gets an export's budget: leave `budget` out pengekspor selalu mendapat anggaran ekspor: hilangkan `budget` +@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}” meminta anggaran berat (setiap proses hingga {minutes} menit dan {times} kali instruksi biasa): seseorang harus menyetujuinya di aplikasi desktop, atau berikan `allowHeavy: true` dalam sesi yang dimulai dengan --allow-plugin-grants +@msg `name` must be 1-64 printable characters `name` harus berupa 1-64 karakter yang dapat dicetak +@msg `version`, `description` or `author` is too long `version`, `description` atau `author` terlalu panjang +@msg `warnings` must be a list of strings `warnings` harus berupa daftar string +@msg `{k}` must be one of {_1} `{k}` harus salah satu dari {_1} +@msg `{k}` must be {what} `{k}` harus {what} +@msg an exporter declares 1 to {MAX_EXTENSIONS} `extensions` pengekspor mendeklarasikan 1 sampai {MAX_EXTENSIONS} `extensions` +@msg at most {MAX_UNGROUPED} parameters outside groups: give the others a `group` paling banyak {MAX_UNGROUPED} parameter di luar grup: berikan `group` pada yang lain +@msg can't encode the input tidak dapat mengodekan masukan +@msg expected {{"dataBase64": "…"}} diharapkan {{"dataBase64": "…"}} +@msg expected {{"objects": [...]}} diharapkan {{"objects": [...]}} +@msg export `{name}`: {e} ekspor `{name}`: {e} +@msg extension {e} is listed twice ekstensi {e} tercantum dua kali +@msg extension {e}: use 1-16 lower-case letters and digits, without the dot ekstensi {e}: gunakan 1-16 huruf kecil dan angka, tanpa titik +@msg invalid id {_1}: use 1-64 characters from A-Z a-z 0-9 . _ - id tidak valid {_1}: gunakan 1-64 karakter dari A-Z a-z 0-9 . _ - +@msg invalid parameter name {k} nama parameter tidak valid {k} +@msg manifest is not UTF-8 manifes bukan UTF-8 +@msg manifest is too long (limit {MAX_MANIFEST_BYTES} bytes) manifes terlalu panjang (batas {MAX_MANIFEST_BYTES} byte) +@msg manifest is {_1} bytes (limit {MAX_MANIFEST_BYTES}) manifes berukuran {_1} byte (batas {MAX_MANIFEST_BYTES}) +@msg module is {_1} bytes (limit {_2}) modul berukuran {_1} byte (batas {_2}) +@msg needs approval: it asks for {0}, which the user grants when installing it on its own memerlukan persetujuan: plug-in meminta {0}, yang diberikan pengguna saat memasangnya sendiri +@msg not JSON: {e} bukan JSON: {e} +@msg not a WebAssembly binary (missing \0asm header) bukan biner WebAssembly (header \0asm tidak ada) +@msg parameter `{k}`: {what} parameter `{k}`: {what} +@msg parameter `{name}`: {what} parameter `{name}`: {what} +@msg plug-in parameters must be a JSON object parameter plug-in harus berupa objek JSON +@msg the module must export its linear memory as `memory` modul harus mengekspor memori liniernya sebagai `memory` +@msg the objects to change are no longer in the document objek yang akan diubah tidak lagi ada di dokumen +@msg the runtime panicked runtime mengalami panik +@msg unexpected host trap trap host yang tidak terduga +@msg vc_abi_version returned {v}; this host implements version {ABI_VERSION} vc_abi_version mengembalikan {v}; host ini menerapkan versi {ABI_VERSION} +@msg vc_alloc returned 0 (out of memory) vc_alloc mengembalikan 0 (memori habis) +@msg vc_alloc returned a block outside memory vc_alloc mengembalikan blok di luar memori +@msg vc_run returned error code {packed} vc_run mengembalikan kode galat {packed} +@msg {_1} is not a file {_1} bukan berkas +@msg {_1} is {_2} bytes (limit {_3}) {_1} berukuran {_2} byte (batas {_3}) +@msg {_1} objects (limit {MAX_OBJECTS}) {_1} objek (batas {MAX_OBJECTS}) +@msg {at}: {msg} {at}: {msg} +@msg {what} points outside memory {what} menunjuk ke luar memori +@msg `angle` must be a number `angle` harus berupa angka +@msg `aspect` must be from 0.01 to 100 `aspect` harus dari 0.01 sampai 100 +@msg `cap` must be "butt", "round" or "square" `cap` harus "butt", "round" atau "square" +@msg `fillRule` must be "nonzero" or "evenodd" `fillRule` harus "nonzero" atau "evenodd" +@msg `helpUrl` must be an https:// address of at most {MAX_HELP_URL} bytes `helpUrl` harus berupa alamat https:// paling panjang {MAX_HELP_URL} byte +@msg `help` must be 1-{MAX_HELP} printable characters `help` harus berupa 1-{MAX_HELP} karakter yang dapat dicetak +@msg `id` must be an effect id of 1-{MAX_EFFECT_ID} bytes `id` harus berupa id efek sepanjang 1-{MAX_EFFECT_ID} byte +@msg `id` must be the id of an input object `id` harus berupa id objek masukan +@msg `join` must be "miter", "round" or "bevel" `join` harus "miter", "round" atau "bevel" +@msg `label` and `group` must be 1-{MAX_LABEL} printable characters `label` dan `group` harus berupa 1-{MAX_LABEL} karakter yang dapat dicetak +@msg `maxLength` must be 1-{MAX_TEXT}, and the default no longer `maxLength` harus 1-{MAX_TEXT}, dan nilai default tidak lebih panjang +@msg `minItems` and `maxItems` must be 0-{MAX_LIST}, `maxItems` at least 1, and the default that many `minItems` dan `maxItems` harus 0-{MAX_LIST}, `maxItems` setidaknya 1, dan nilai default sebanyak itu +@msg `name` must be a string `name` harus berupa string +@msg `opacity` must be a number `opacity` harus berupa angka +@msg `type` must be "path" or "compound" `type` harus "path" atau "compound" +@msg `unit` must be 1-{MAX_UNIT} printable characters `unit` harus berupa 1-{MAX_UNIT} karakter yang dapat dicetak +@msg `visibleWhen` lists 1 to {MAX_CONDITION_VALUES} values for `{other}` `visibleWhen` mencantumkan 1 sampai {MAX_CONDITION_VALUES} nilai untuk `{other}` +@msg `visibleWhen` names `{other}`, which isn't a parameter declared before this one `visibleWhen` menyebut `{other}`, yang bukan parameter yang dideklarasikan sebelum parameter ini +@msg `visibleWhen` names at most {MAX_CONDITIONS} parameters `visibleWhen` menyebut paling banyak {MAX_CONDITIONS} parameter +@msg `visibleWhen` takes `{other}`'s values, of a checkbox or a choice `visibleWhen` menerima nilai `{other}`, dari kotak centang atau pilihan +@msg `visible` must be true or false `visible` harus true atau false +@msg `{key}` must be a number from {_1} to {_2} `{key}` harus berupa angka dari {_1} sampai {_2} +@msg `{key}` must be an array of at most {MAX_ITEMS} entries `{key}` harus berupa larik berisi paling banyak {MAX_ITEMS} entri +@msg a color default must be a color object or a hex string such as "#3a7bd5" nilai default warna harus berupa objek warna atau string heksadesimal seperti "#3a7bd5" +@msg a color object or a hex string such as "#3a7bd5" objek warna atau string heksadesimal seperti "#3a7bd5" +@msg a freeform gradient holds at most {MAX_ITEMS} points and lines gradien bentuk bebas berisi paling banyak {MAX_ITEMS} titik dan garis +@msg a freeform gradient line names a point it doesn't have garis gradien bentuk bebas menyebut titik yang tidak dimilikinya +@msg a gradient needs 1-{MAX_ITEMS} stops gradien memerlukan 1-{MAX_ITEMS} perhentian +@msg a list of numbers daftar angka +@msg a list of {min_items} to {max_items} numbers daftar berisi {min_items} sampai {max_items} angka +@msg a new object needs a `path` objek baru memerlukan `path` +@msg a number angka +@msg a painted live effect returns only `objects` efek langsung yang dicat hanya mengembalikan `objects` +@msg a painted live effect's piece has only `path`, `fillRule`, `fills` and `strokes` potongan efek langsung yang dicat hanya memiliki `path`, `fillRule`, `fills` dan `strokes` +@msg a read-only object was left out objek baca-saja dihilangkan +@msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given objek baca-saja dihilangkan: kembalikan objek itu, sebagai {{"id": …}} saja atau seperti yang diberikan +@msg a string string +@msg a stroke has only `paint`, `width`, `join`, `cap` and `miterLimit` goresan hanya memiliki `paint`, `width`, `join`, `cap` dan `miterLimit` +@msg a stroke must be {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} goresan harus berupa {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} +@msg an effect must be {{"id", "params"?, "visible"?}} efek harus berupa {{"id", "params"?, "visible"?}} +@msg an effect on a fill returns only `fills` efek pada isian hanya mengembalikan `fills` +@msg an effect on a stroke returns only `strokes` efek pada goresan hanya mengembalikan `strokes` +@msg an object must be a JSON object objek harus berupa objek JSON +@msg bad range rentang tidak valid +@msg choices must be 1-64 non-empty, printable strings pilihan harus berupa 1-64 string yang tidak kosong dan dapat dicetak +@msg coordinate out of range (limit ±{MAX_COORD} pt) koordinat di luar rentang (batas ±{MAX_COORD} pt) +@msg default is not one of the options nilai default bukan salah satu opsi +@msg each piece needs a `path` setiap potongan memerlukan `path` +@msg is listed twice tercantum dua kali +@msg pattern transform out of range transformasi pola di luar rentang +@msg read-only field '{field}' changed bidang baca-saja '{field}' berubah +@msg stops must be in order of `offset` perhentian harus berurutan menurut `offset` +@msg the document has no pattern {pattern} dokumen tidak memiliki pola {pattern} +@msg the document has no swatch {n} dokumen tidak memiliki swatch {n} +@msg `plates` requires a stop linked to a spot swatch `plates` memerlukan perhentian yang ditautkan ke swatch warna spot +@msg the output keluaran +@msg the path has no anchor points jalur tidak memiliki titik jangkar +@msg too many anchor points (limit {MAX_ANCHORS}) terlalu banyak titik jangkar (batas {MAX_ANCHORS}) +@msg true or false true atau false +@msg a number >= {_1} angka >= {_1} +@msg a number > {_1} angka > {_1} +@msg a number <= {_1} angka <= {_1} +@msg a number < {_1} angka < {_1} +@msg a number {_1} to {_2} angka {_1} sampai {_2} +@msg a number >= {_1} and < {_2} angka >= {_1} dan < {_2} +@msg a number > {_1} and <= {_2} angka > {_1} dan <= {_2} +@msg a number > {_1} and < {_2} angka > {_1} dan < {_2} +@msg a number ({_1}) angka ({_1}) +@msg a number >= {_1} ({_2}) angka >= {_1} ({_2}) +@msg a number > {_1} ({_2}) angka > {_1} ({_2}) +@msg a number <= {_1} ({_2}) angka <= {_1} ({_2}) +@msg a number < {_1} ({_2}) angka < {_1} ({_2}) +@msg a number {_1} to {_2} ({_3}) angka {_1} sampai {_2} ({_3}) +@msg a number >= {_1} and < {_2} ({_3}) angka >= {_1} dan < {_2} ({_3}) +@msg a number > {_1} and <= {_2} ({_3}) angka > {_1} dan <= {_2} ({_3}) +@msg a number > {_1} and < {_2} ({_3}) angka > {_1} dan < {_2} ({_3}) +@msg an integer bilangan bulat +@msg an integer >= {_1} bilangan bulat >= {_1} +@msg an integer <= {_1} bilangan bulat <= {_1} +@msg an integer {_1} to {_2} bilangan bulat {_1} sampai {_2} +@msg one of {_1} salah satu dari {_1} +@msg an object id (a non-negative integer) id objek (bilangan bulat tidak negatif) +@msg a list of object ids daftar id objek +@msg a color (a string, [r, g, b] or an object) warna (string, [r, g, b] atau objek) +@msg [x, y] (two numbers) [x, y] (dua angka) +@msg an object objek +@msg a list daftar +@msg unknown key `{k}`; the keys here are {_1} kunci tidak dikenal `{k}`; kunci di sini adalah {_1} +@msg {_1} is listed twice {_1} tercantum dua kali +@msg {_1} is not the id of an input object {_1} bukan id objek masukan +@msg {_1} is read-only {_1} baca-saja +@msg {what} must be from {lo} to {hi} {what} harus dari {lo} sampai {hi} +@msg a color component komponen warna +@msg a plate pelat +@msg Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself. Otomatisasi meminta pemasangan plug-in ini. Untuk memasangnya, pilih Objek › Plug-in › Instal plug-in… sendiri. +@msg “{name}” is another module than the plug-in with id {_1} and would get the settings and cache kept for it: install it with `replace: true` once the user agrees “{name}” adalah modul yang berbeda dari plug-in dengan id {_1} dan akan mendapat pengaturan serta cache yang disimpan untuk plug-in itu: pasang dengan `replace: true` setelah pengguna setuju +@msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call “{name}” mencantumkan `{id}` dalam `commandAllowlist`, yang tidak boleh dipanggil plug-in +@msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} +@msg vc_call `{shown}`: the manifest's `commandAllowlist` doesn't list it vc_call `{shown}`: `commandAllowlist` manifes tidak mencantumkannya +@msg vc_call `{shown}`: the id or the arguments lie outside the module's memory vc_call `{shown}`: id atau argumen berada di luar memori modul +@msg vc_call `{shown}`: the id or the arguments are not UTF-8 vc_call `{shown}`: id atau argumen bukan UTF-8 +@msg vc_call `{shown}`: the arguments are not a JSON object vc_call `{shown}`: argumen bukan objek JSON +@msg only a filter with the usual budget declares `commandAllowlist` hanya filter dengan anggaran biasa yang mendeklarasikan `commandAllowlist` +@msg command calls ({MAX_CALLS} calls and {MAX_CALL_BYTES} bytes per run) panggilan perintah ({MAX_CALLS} panggilan dan {MAX_CALL_BYTES} byte per proses) +@msg command call size (vc_call `{shown}`: {len} bytes, limit {MAX_CALL_DATA}) ukuran panggilan perintah (vc_call `{shown}`: {len} byte, batas {MAX_CALL_DATA}) +@msg at most {MAX_ALLOWED_COMMANDS} commands in `commandAllowlist` paling banyak {MAX_ALLOWED_COMMANDS} perintah dalam `commandAllowlist` +@msg a plug-in may not call this command plug-in tidak boleh memanggil perintah ini +@msg `commandAllowlist` needs the permission `commands`, and `commands` needs a `commandAllowlist` `commandAllowlist` memerlukan izin `commands`, dan `commands` memerlukan `commandAllowlist` +@msg `commandAllowlist` names `{shown}`, which is not a command id or is listed twice `commandAllowlist` menyebut `{shown}`, yang bukan id perintah atau tercantum dua kali +@msg permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API} izin `{permission}` memerlukan API plug-in tingkat {PROGRESS_API}: berikan `api` {PROGRESS_API} +@msg the module imports `env.{name}` with another type than the host's: it is {signature} modul mengimpor `env.{name}` dengan tipe yang berbeda dari milik host: tipenya {signature} +@msg the module imports `env.{name}`, which a plug-in may use only at plug-in API level {PROGRESS_API} (`api` {PROGRESS_API}) and with the permission `{permission}` modul mengimpor `env.{name}`, yang hanya boleh digunakan plug-in pada API plug-in tingkat {PROGRESS_API} (`api` {PROGRESS_API}) dan dengan izin `{permission}` +@msg the module imports `{from}.{name}`, which the host doesn't offer: a plug-in may import only the `env.vc_*` functions that docs/plugins.md lists (plug-in API level 2), and no WASI, files or network modul mengimpor `{from}.{name}`, yang tidak disediakan host: plug-in hanya boleh mengimpor fungsi `env.vc_*` yang tercantum di docs/plugins.md (API plug-in tingkat 2), tanpa WASI, berkas, atau jaringan +@msg `api` is {_1}; this host implements plug-in API levels 1 to {API_LEVEL} `api` bernilai {_1}; host ini menerapkan API plug-in tingkat 1 sampai {API_LEVEL} +@msg `paintOutput` may only be true `paintOutput` hanya boleh true +@msg `paintOutput` is only for a live effect (`kind` "effect") at `api` 2 `paintOutput` hanya untuk efek langsung (`kind` "effect") pada `api` 2 +@msg `grant` must be a list of permission names `grant` harus berupa daftar nama izin +@msg `grant` names an unknown permission `{shown}` `grant` menyebut izin yang tidak dikenal `{shown}` +@msg a plug-in of kind `{_1}` needs the permission `{_2}` plug-in berjenis `{_1}` memerlukan izin `{_2}` +@msg at most {MAX_PERMISSIONS} `permissions` paling banyak {MAX_PERMISSIONS} `permissions` +@msg permission `{shown}` doesn't apply to a plug-in of kind `{_1}` izin `{shown}` tidak berlaku untuk plug-in berjenis `{_1}` +@msg permission `{shown}` is listed twice izin `{shown}` tercantum dua kali +@msg only a filter declares `inputs` hanya filter yang mendeklarasikan `inputs` +@msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` menyebut jenis objek yang tidak dikenal `{shown}`: gunakan type, image atau symbolInstance +@msg `inputs` lists `{shown}` twice `inputs` mencantumkan `{shown}` dua kali +@msg `inputs` needs `api` 2 or later `inputs` memerlukan `api` 2 atau lebih baru +@msg `inputs` needs the permission `doc.read` `inputs` memerlukan izin `doc.read` +@msg memory budget (object {_1} needs {size} bytes of input, {left} left) anggaran memori (objek {_1} memerlukan {size} byte masukan, tersisa {left}) +@msg object budget (more than {MAX_OBJECTS} read-only objects) anggaran objek (lebih dari {MAX_OBJECTS} objek baca-saja) +@msg instruction budget anggaran instruksi +@msg time budget anggaran waktu +@msg memory budget (the selection is too large to hand over) anggaran memori (seleksi terlalu besar untuk diserahkan) +@msg output size ({what} is {len} bytes, limit {max}) ukuran keluaran ({what} berukuran {len} byte, batas {max}) +@msg the plug-in's grant can't be removed from the plug-in store izin yang diberikan kepada plug-in tidak dapat dihapus dari penyimpanan plug-in +@msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it izin `{shown}` dicadangkan untuk API plug-in yang lebih baru; host ini tidak memberikannya +@msg unknown permission `{shown}` izin tidak dikenal `{shown}` +@msg “{name}” asks for the permissions {asked}: a person has to approve them in the desktop app, or pass `grant` in a session started with --allow-plugin-grants “{name}” meminta izin {asked}: seseorang harus menyetujuinya di aplikasi desktop, atau berikan `grant` dalam sesi yang dimulai dengan --allow-plugin-grants +@msg `grant` and `allowHeavy` take effect only in a session started with --allow-plugin-grants: approve the plug-in in the desktop app `grant` dan `allowHeavy` hanya berlaku dalam sesi yang dimulai dengan --allow-plugin-grants: setujui plug-in di aplikasi desktop +@msg Only the person at the keyboard can approve installing a plug-in Hanya orang di depan papan tik yang dapat menyetujui pemasangan plug-in +@msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed “{name}” tidak diberi `{p}`, yang diperlukan keluarannya: tidak ada yang diubah +@msg a heavy filter runs in the background, so it can't declare `commands` filter berat berjalan di latar belakang, sehingga tidak dapat mendeklarasikan `commands` +@msg at most {MAX_COMMANDS} `commands` paling banyak {MAX_COMMANDS} `commands` +@msg command {name} is declared twice perintah {name} dideklarasikan dua kali +@msg command {name}: `label` must be 1-64 printable characters perintah {name}: `label` harus berupa 1-64 karakter yang dapat dicetak +@msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter perintah {name}: gunakan id sepanjang 1-{MAX_COMMAND_ID} karakter dari a-z 0-9 _ yang diawali huruf +@msg command {name}: {e} perintah {name}: {e} +@msg manifest: {e} manifes: {e} +@msg manifest: {e} at line {line} column {column} manifes: {e} pada baris {line} kolom {column} +@msg `commands` must be a list of commands, each with an `id` and a `label` `commands` harus berupa daftar perintah, masing-masing dengan `id` dan `label` +@msg command {name} must be an object with an `id` and a `label` perintah {name} harus berupa objek dengan `id` dan `label` +@msg missing field `{key}` bidang `{key}` tidak ada +@msg duplicate field `{key}` bidang `{key}` ganda +@msg only a filter or a live effect declares `commands` hanya filter atau efek langsung yang mendeklarasikan `commands` +@msg “{name}” › {label}: {e} “{name}” › {label}: {e} +@msg the module doesn't have the SHA-256 `hash` gives: nothing was installed modul tidak memiliki SHA-256 yang diberikan `hash`: tidak ada yang dipasang +@msg select one object pilih satu objek +@msg Global Edit is off Edit global nonaktif +@msg only an object of the Global Edit other than the one it started from can be left out hanya objek Edit global selain objek awalnya yang dapat dikecualikan +@msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all atau rentang seperti 1, 3-5, bukan {v} +@msg `{_1}` has no symbols to place `{_1}` tidak memiliki simbol untuk ditempatkan +@msg missing `library` (see symbol.libraries) `library` tidak ada (lihat symbol.libraries) +@msg no symbol `{n}` tidak ada simbol `{n}` +@msg no symbol `{n}` in `{_1}` tidak ada simbol `{n}` di `{_1}` +@msg no symbol library `{key}` (see symbol.libraries) tidak ada pustaka simbol `{key}` (lihat symbol.libraries) +@msg the document has no symbols to save dokumen tidak memiliki simbol untuk disimpan +@msg `{_1}` has no brushes to apply `{_1}` tidak memiliki kuas untuk diterapkan +@msg missing `library` (see brush.libraries) `library` tidak ada (lihat brush.libraries) +@msg no brush `{n}` tidak ada kuas `{n}` +@msg no brush `{n}` in `{_1}` tidak ada kuas `{n}` di `{_1}` +@msg no brush library `{key}` (see brush.libraries) tidak ada pustaka kuas `{key}` (lihat brush.libraries) +@msg the document has no brushes to save dokumen tidak memiliki kuas untuk disimpan +@msg a {width}×{height} screenshot's byte count overflows jumlah byte tangkapan layar {width}×{height} meluap +@msg the window's {what} ({points} points × {scale} DPI) cannot size a screenshot {what} jendela ({points} poin × {scale} DPI) tidak dapat menentukan ukuran tangkapan layar +@msg {label} must be a number {label} harus berupa angka +@msg {label} must be a number of at least 0.1 {label} harus berupa angka setidaknya 0.1 +@msg {label} must be a number from {min} to {max} {label} harus berupa angka dari {min} sampai {max} +@msg {label} must be a whole number from {min} to {max} {label} harus berupa bilangan bulat dari {min} sampai {max} +@msg features lists at most {max} tags features mencantumkan paling banyak {max} tag +@msg unknown OpenType feature `{t}` fitur OpenType tidak dikenal `{t}` +@msg {label} must be a number above 0 and at most {max} {label} harus berupa angka di atas 0 dan paling besar {max} +@msg {label} must be at most {max} characters {label} paling banyak {max} karakter +@msg {label} must be one character {label} harus satu karakter +@msg at most {max} tab stops paling banyak {max} perhentian tab +@msg unknown align `{other}` align tidak dikenal `{other}` +@msg no character style `{name}` tidak ada gaya karakter `{name}` +@msg {_1} is an importer (File › Open With) {_1} adalah pengimpor (Berkas › Buka Dengan) +@msg missing `importer` (see document.formats) `importer` tidak ada (lihat document.formats) +@msg `importer` must be a plug-in format id (see document.formats) `importer` harus berupa id format plug-in (lihat document.formats) +@msg “{shown}” opens {_1} files, not `{_2}` “{shown}” membuka berkas {_1}, bukan `{_2}` +@msg `{_1}` is a plug-in of kind `{_2}`, not an importer `{_1}` adalah plug-in berjenis `{_2}`, bukan pengimpor +@msg `{_1}` is a plug-in of kind `{_2}`, not an exporter `{_1}` adalah plug-in berjenis `{_2}`, bukan pengekspor +@msg `{_1}` is an importer: open a file with document.open {{"importer": "{_2}"}} `{_1}` adalah pengimpor: buka berkas dengan document.open {{"importer": "{_2}"}} +@msg `{_1}` is an exporter: export with document.export {{"format": "{_2}"}} `{_1}` adalah pengekspor: ekspor dengan document.export {{"format": "{_2}"}} +@msg `{_1}` is a live effect: apply it with effect.apply {{"effect": "{_2}"}} `{_1}` adalah efek langsung: terapkan dengan effect.apply {{"effect": "{_2}"}} +@msg the importer returned no objects pengimpor tidak mengembalikan objek apa pun +@msg an importer returns `objects` and `warnings`, not `{key}` pengimpor mengembalikan `objects` dan `warnings`, bukan `{key}` +@msg the file is larger than the {MAX_INPUT_BYTES} bytes an importer reads berkas lebih besar dari {MAX_INPUT_BYTES} byte yang dibaca pengimpor +@msg an importer declares 1 to {MAX_EXTENSIONS} `extensions` pengimpor mendeklarasikan 1 sampai {MAX_EXTENSIONS} `extensions` +@msg only an exporter or an importer declares `extensions` hanya pengekspor atau pengimpor yang mendeklarasikan `extensions` +@msg an importer always gets an import's budget: leave `budget` out pengimpor selalu mendapat anggaran impor: hilangkan `budget` +@msg only paths and compound paths can be aligned to the pixel grid hanya jalur dan jalur majemuk yang dapat diselaraskan ke kisi piksel +@msg `first` and `last` must be numbers of lines the console holds, first before last `first` dan `last` harus berupa nomor baris yang ada di konsol, first sebelum last +@msg no plug-in effect is deferred tidak ada efek plug-in yang ditunda +@msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. Dibuka dengan {n} efek plug-in yang ditunda. Efek › Segarkan efek yang ditunda menjalankannya. +@msg The selected art has no islands to bridge Karya terseleksi tidak memiliki pulau untuk dijembatani +@msg No bridge of this width fits across the selected art Tidak ada jembatan selebar ini yang muat melintasi karya terseleksi +@msg Some islands could not be joined to the area around the art Beberapa pulau tidak dapat disambungkan ke area di sekitar karya +@msg `width` must be from {lo} to {hi} pt `width` harus dari {lo} sampai {hi} pt +@msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` harus berupa bilangan bulat dari 1 sampai {MAX_BRIDGES_PER_ISLAND} +@msgplural Loaded “{name}”: {n} step has an unknown command and was kept: “{action}”, step {step}, `{command}`|Loaded “{name}”: {n} steps have unknown commands and were kept; the first: “{action}”, step {step}, `{command}` “{name}” dimuat: {n} langkah memiliki perintah yang tidak dikenal dan dipertahankan; yang pertama: “{action}”, langkah {step}, `{command}` + File Berkas New… Baru… New Without Dialog Baru tanpa dialog @@ -516,6 +1149,17 @@ Shading Color Warna pengarsiran Black Overprint Hitam overprint Draw Hidden Faces Gambar sisi tersembunyi + Map Art… Petakan karya seni… + Map Art Petakan karya seni + First Surface Permukaan pertama + Previous Surface Permukaan sebelumnya + Next Surface Permukaan berikutnya + Last Surface Permukaan terakhir + Horizontal Scale Skala horizontal + Vertical Scale Skala vertikal + Scale to Fit Skalakan agar pas + Shade Artwork Beri bayangan karya seni + Invisible Geometry Geometri tak terlihat Revolve… Revolusi… Inflate… Gelembungkan… Materials… Material… @@ -627,6 +1271,8 @@ Hide Gradient Annotator Sembunyikan anotator gradien Show Gradient Annotator Tampilkan anotator gradien Hide Corner Widget Sembunyikan widget sudut + Hide Shape Widgets Sembunyikan widget bentuk + Show Shape Widgets Tampilkan widget bentuk Show Corner Widget Tampilkan widget sudut Guides Panduan Hide Guides Sembunyikan panduan @@ -746,6 +1392,9 @@ Box Channel Saluran kotak Color box Kotak warna Color Wheel Options Opsi roda warna + Show Harmony Tampilkan harmoni + Harmony Rule Aturan harmoni + Harmony color Warna harmoni CSS Properties Properti CSS Document Info Info dokumen Flattener Preview Pratinjau perata @@ -977,6 +1626,25 @@ Preserve Embedded Profiles Pertahankan Profil Tersemat Convert to Working Space Konversi ke Ruang Kerja Preserve Numbers Pertahankan Angka + Profile Mismatches: Ketidakcocokan Profil: + Ask When Opening Tanya Saat Membuka + Ask When Pasting Tanya Saat Menempel + Missing Profiles: Profil yang Hilang: + Embedded Profile Mismatch Ketidakcocokan Profil Tersemat + Missing Profile Profil Hilang + Paste Profile Mismatch Ketidakcocokan Profil Saat Menempel + “{name}” is not tagged with a {model} profile. “{name}” tidak memiliki profil {model}. + “{name}” is tagged with the {model} profile “{profile}”, which is not the {model} working space “{working}”. “{name}” memiliki profil {model} “{profile}”, yang bukan ruang kerja {model} “{working}”. + Use the embedded profile Gunakan profil tersemat + Convert the colors to the working space Konversi warna ke ruang kerja + Discard the embedded profile Buang profil tersemat + Leave as is Biarkan apa adanya + Assign the working space Tetapkan ruang kerja + Assign profile: Tetapkan profil: + Preserve the color numbers Pertahankan angka warna + Convert to keep the colors' appearance Konversi agar tampilan warna tetap sama +@msg `{path}` goes with `{key}`: "assign" only `{path}` hanya dipakai dengan `{key}`: "assign" + The pasted colors come from a document whose {model} profile is “{from}”; this document's is “{to}”. Warna yang ditempel berasal dari dokumen dengan profil {model} “{from}”; profil dokumen ini “{to}”. CMYK CMYK Texture Tekstur Craquelure… Craquelure… @@ -1058,6 +1726,15 @@ lighting Light Cahaya Document Raster Effects Settings Dialog Dialog pengaturan efek raster dokumen Drop Shadow Bayangan jatuh DXF Options Dialog Dialog opsi DXF + HP-GL Options Opsi HP-GL + HP-GL Options Dialog Dialog opsi HP-GL + Curve Tolerance: Toleransi kurva: + Origin: Titik asal: + Pens: Pena: + One Pen per Color Satu pena per warna + Pen Table Tabel pena + Draw the Nearest Path Next Gambar jalur terdekat berikutnya + Draw Inner Paths First Gambar jalur bagian dalam lebih dulu Edit Toolbar Edit bilah alat Edit Views Edit tampilan Effect… Efek… @@ -1620,6 +2297,7 @@ digits Malayalam Malayalam Roman Baseline Baseline Romawi Select a text object to edit its character attributes. Pilih objek teks untuk mengedit atribut karakternya. Show Options Tampilkan opsi + Show on Shape Creation Tampilkan saat membuat bentuk Show Recent Colors Tampilkan warna terbaru Toggle RGB Percent Alihkan RGB dalam persen Small Caps Kapital kecil @@ -1647,6 +2325,48 @@ digits Malayalam Malayalam Composite Fonts Font komposit Export Composite Fonts Ekspor font komposit Import Composite Fonts Impor font komposit +@msg each font must be {{name, parts}} setiap font harus berupa {{name, parts}} +@msg unknown key `{k}`; a font takes name and parts kunci tidak dikenal `{k}`; font menerima name dan parts +@msg each font needs a name setiap font memerlukan nama +@msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` tidak dapat menjadi nama font komposit (1 sampai {COMPOSITE_NAME_MAX} karakter, tanpa karakter kontrol) +@msg `{name}`: parts must be an object `{name}`: parts harus berupa objek +@msg `{name}`: unknown class `{k}`; the classes are kanji, kana, punctuation, symbols, roman and numerals `{name}`: kelas tidak dikenal `{k}`; kelasnya adalah kanji, kana, punctuation, symbols, roman, dan numerals +@msg `{name}`: {_1} must be an object `{name}`: {_1} harus berupa objek +@msg `{name}`: unknown key `{k}` in {_1} `{name}`: kunci tidak dikenal `{k}` di {_1} +@msg `{name}`: give the kanji part `{name}`: berikan bagian kanji +@msg a document keeps at most {COMPOSITE_FONTS_MAX} composite fonts dokumen menyimpan paling banyak {COMPOSITE_FONTS_MAX} font komposit +@msg two composite fonts are named `{_1}` dua font komposit bernama `{_1}` +@msg `{_1}` is the name of an installed font `{_1}` adalah nama font yang terpasang +@msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: {_2} diatur dengan `{font}`, sebuah font komposit +@msg give fonts: [{{name, parts}}…] berikan fonts: [{{name, parts}}…] +@msg path is empty path kosong +@msg fonts must be a list of composite fonts fonts harus berupa daftar font komposit +@msg names must be strings names harus berupa string +@msg no composite font named `{n}` tidak ada font komposit bernama `{n}` +@msg names must be a list of names names harus berupa daftar nama +@msg no composite fonts to export tidak ada font komposit untuk diekspor +@msg not a composite fonts file: {e} bukan berkas font komposit: {e} +@msg not a composite fonts file: no compositeFonts list bukan berkas font komposit: tidak ada daftar compositeFonts +@msg the file holds more than {COMPOSITE_FONTS_MAX} composite fonts berkas berisi lebih dari {COMPOSITE_FONTS_MAX} font komposit +@msg the file is larger than 4 MB berkas lebih besar dari 4 MB +@msg dataBase64 is not base64 dataBase64 bukan base64 +@msg give one of path, data or dataBase64 berikan salah satu dari path, data, atau dataBase64 +@msg the file holds no composite fonts berkas tidak berisi font komposit +@msg the file holds two composite fonts named `{_1}` berkas berisi dua font komposit bernama `{_1}` +@msg `{_1}` can't name a composite font `{_1}` tidak dapat menjadi nama font komposit +@msg {k}: give a font {k}: berikan font +@msg `{name}`: {k}: give a font `{name}`: {k}: berikan font +@msg {k}: size must be {_1} to {_2}% {k}: size harus {_1} sampai {_2}% +@msg `{name}`: {k}: size must be {_1} to {_2}% `{name}`: {k}: size harus {_1} sampai {_2}% +@msg {k}: baseline must be {_1} to {_2}% {k}: baseline harus {_1} sampai {_2}% +@msg `{name}`: {k}: baseline must be {_1} to {_2}% `{name}`: {k}: baseline harus {_1} sampai {_2}% +@msg {k}: scale must be {_1} to {_2}% {k}: skala harus {_1} sampai {_2}% +@msg `{name}`: {k}: scale must be {_1} to {_2}% `{name}`: {k}: skala harus {_1} sampai {_2}% +@msg {k}: only kana, roman and numerals can be scaled {k}: hanya kana, roman, dan numerals yang dapat diskalakan +@msg `{name}`: {k}: only kana, roman and numerals can be scaled `{name}`: {k}: hanya kana, roman, dan numerals yang dapat diskalakan +@msg {k}: only kana can be scaled at the center {k}: hanya kana yang dapat diskalakan dari tengah +@msg `{name}`: {k}: only kana can be scaled at the center `{name}`: {k}: hanya kana yang dapat diskalakan dari tengah +@msg no composite font tidak ada font komposit Delete Font Hapus font Kanji Kanji Kana Kana @@ -1846,6 +2566,8 @@ digits Malayalam Malayalam Snap Curves To Lines Kancingkan kurva ke garis Tracing Result with Outlines Hasil penelusuran dengan garis luar Source Image Gambar sumber + Split View Tampilan terbagi + Divider Pembatas Threshold Ambang batas Trace Telusuri Trace the image with the Default preset Telusuri gambar dengan preset Default @@ -1970,6 +2692,15 @@ digits Malayalam Malayalam YakumonoZenkaku YakumonoZenkaku Kinsoku Set Set Kinsoku Kinsoku Shori Type Jenis Kinsoku Shori + Kinsoku Shori Settings… Pengaturan Kinsoku Shori… + Kinsoku Shori Settings Pengaturan Kinsoku Shori + Kinsoku Sets Daftar Set Kinsoku + Kinsoku Set Base Dasar Set Kinsoku + Based on: Berdasarkan: + Cannot Start Line Tidak dapat memulai baris + Cannot End Line Tidak dapat mengakhiri baris + Hanging Punctuation Tanda baca gantung + Inseparable Characters Karakter tak terpisahkan Push In First Dorong masuk dahulu Push Out First Dorong keluar dahulu Push Out Only Hanya dorong keluar @@ -2369,6 +3100,12 @@ digits Malayalam Malayalam Units: Satuan: Use Typographer's Quotes Gunakan tanda kutip tipografis Center Artwork Pusatkan karya seni + PSD Import Options Opsi impor PSD + Place PSD Tempatkan PSD + Convert Layers to Objects Ubah lapisan menjadi objek + Import Hidden Layers Impor lapisan tersembunyi + Flatten Layers to a Single Image Ratakan lapisan menjadi satu gambar + Import Slices Impor slice DXF Import Options Opsi impor DXF Layout: Tata letak: Merge Layers Gabungkan lapisan @@ -2513,6 +3250,7 @@ digits Malayalam Malayalam Save As Preset… Simpan sebagai Preset… Save Changes Simpan Perubahan Save Preset… Simpan preset… + Save Summary… Simpan ringkasan… Vectors Vektor A saved copy of the selected preset Salinan tersimpan dari preset terpilih Built-in presets don't change: New makes a copy you can edit. Preset bawaan tidak berubah: Baru membuat salinan yang dapat Anda edit. @@ -2746,6 +3484,8 @@ digits Malayalam Malayalam Overprint and Transparency Flattener Options Opsi overprint dan perataan transparansi Custom… Kustom… Custom Transparency Flattener Options Opsi perataan transparansi kustom + The PDF preset keeps the flattener preset but not the Custom… settings. Preset PDF menyimpan preset perataan, tetapi tidak menyimpan pengaturan Kustom…. + PDF 1.3 files clip rasterized areas to their regions, and Overprint sets whether overprints are kept. File PDF 1.3 memangkas area yang dirasterisasi ke wilayahnya, dan Overprint menentukan apakah overprint dipertahankan. EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS tidak memiliki transparansi alfa, dan Overprint menentukan apakah overprint dipertahankan. Place the pages with the placement again Tempatkan halaman lagi dengan penempatan tersebut Placement: Penempatan: @@ -2841,6 +3581,9 @@ digits Malayalam Malayalam Recolor this row Warnai ulang baris ini Reset the rows to the artwork's colors Setel ulang baris ke warna karya seni Color Theme Picker Pemilih tema warna + Undo Changes Urungkan perubahan + Redo Changes Ulangi perubahan +@msg Recolor Artwork is not open Warnai ulang karya seni tidak terbuka Click or drag across the art to pick its colors; Shift adds more Klik atau seret melintasi karya seni untuk mengambil warnanya; Shift menambahkan lagi Prominent Colors Warna menonjol Save All Colors Simpan semua warna @@ -3128,6 +3871,17 @@ antiAlias Sharp Tajam Swatch Name: Nama swatch: Diameter: Diameter: Symbolism Tools Options Opsi alat simbolisme + Tool: Alat: + Symbol Set Density Kepadatan set simbol + Symbol Sprayer Options Opsi penyemprot simbol + Scrunch: Perapatan: + Spin: Putaran: + Screen: Penyaringan: + Stain: Pewarnaan: + Symbol Sizer Options Opsi pengubah ukuran simbol + Proportional Resizing Ubah ukuran secara proporsional + Resizing Affects Density Perubahan ukuran memengaruhi kepadatan + Show Brush Size and Intensity Tampilkan ukuran dan intensitas kuas Symbol Set Density: Kepadatan set simbol: Intensity: Intensitas: Place PDF Tempatkan PDF @@ -3188,6 +3942,7 @@ antiAlias Sharp Tajam Width Point Edit Edit titik lebar Art Seni Bearing Arah + Stylus Wheel Roda stylus Bristle Bristle Calligraphic Kaligrafis Dots Titik @@ -3318,6 +4073,9 @@ theme Appearance Tampilan embedding for preview and print penyematan untuk pratinjau dan cetak embedding allowed penyematan diizinkan {file}; {embedding} {file}; {embedding} + unknown type jenis tidak dikenal + {type}; {uses} {type}; {uses} +@plural {n} use|{n} uses {n} penggunaan substituted: shown in {family} {style} ({detail}) diganti: ditampilkan dengan {family} {style} ({detail}) missing: shown in {family} {style} tidak ada: ditampilkan dengan {family} {style} missing tidak ada @@ -3888,6 +4646,7 @@ theme Appearance Tampilan Show Pixel Grid (Above 600% Zoom) Tampilkan grid piksel (di atas zoom 600%) Show Slice Numbers Tampilkan nomor irisan Show The Home Screen When No Documents Are Open Tampilkan layar beranda saat tidak ada dokumen terbuka + Show Tool Cards Tampilkan kartu alat Show Tool Tips Tampilkan tips alat Size/Leading Ukuran/Leading Snapping Tolerance Toleransi kancing @@ -4013,6 +4772,8 @@ theme Appearance Tampilan Spot Colors (0) Warna spot (0) Swatch Options Opsi sampel Ungroup Color Group Lepaskan grup warna + Color Group Options Opsi grup warna + Color Group Options… Opsi grup warna… Copy to User Defined Salin ke Buatan Pengguna Swatch Library Pustaka sampel Clear All Tabs Hapus semua tab @@ -4311,6 +5072,7 @@ font-technology Variable Variabel A live rectangle's properties show one Corner Radius field for all four corners; off, each corner has its own field. Properti persegi panjang dinamis menampilkan satu bidang Radius sudut untuk keempat sudut; saat nonaktif, setiap sudut punya bidangnya sendiri. What edits in the Transform panel transform: the object, its pattern tiles or both; Default follows Transform Pattern Tiles. Apa yang ditransformasi oleh pengeditan di panel Transformasi: objek, ubin polanya, atau keduanya; Default mengikuti Transformasi ubin pola. With one symbol instance selected, the Transform panel uses the symbol's registration point as its reference point. Saat satu instans simbol dipilih, panel Transformasi memakai titik registrasi simbol sebagai titik referensi. + Drawing a rectangle, ellipse, polygon, star or line opens the Transform panel if it is closed. Menggambar persegi panjang, elips, poligon, bintang, atau garis membuka panel Transformasi jika panel itu tertutup. Darkens the canvas outside the artboards while the Artboard tool is active. Menggelapkan kanvas di luar artboard selama alat Artboard aktif. With Fade Region Outside Artboard on, the area outside the artboards stays dark while you drag with the Artboard tool. Saat Redupkan wilayah di luar artboard aktif, area di luar artboard tetap gelap selama Anda menyeret dengan alat Artboard. How near, in pixels, the pointer must be to an object, anchor or handle for a click to select it. Seberapa dekat, dalam piksel, penunjuk harus berada dari objek, titik jangkar, atau pegangan agar klik memilihnya. @@ -4403,6 +5165,9 @@ font-technology Variable Variabel Couldn't copy to the system clipboard: {e} Tidak dapat menyalin ke papan klip sistem: {e} Couldn't paste from the clipboard: {e} Tidak dapat menempel dari papan klip: {e} Channel Saluran + Curvature Circle Tool Alat Lingkaran kelengkungan + Cusp Titik tajam + Straight segment Segmen lurus Circle Lingkaran Circle Tool Alat lingkaran Circle too large Lingkaran terlalu besar @@ -5032,6 +5797,12 @@ imageTrace Outline Kontur @msg percent must be above 0 and at most 6400, not {p} percent harus di atas 0 dan paling banyak 6400, bukan {p} @msg pick a colour, gradient or pattern to save as a swatch pilih warna, gradien, atau pola untuk disimpan sebagai swatch @msg plane must be left, right or ground plane harus left, right, atau ground +@msg tolerance must be 0 or more tolerance harus 0 atau lebih +@msg give `at` or `clear`, not both berikan `at` atau `clear`, bukan keduanya +@msg anchorPoint must be true or false anchorPoint harus true atau false +@msg gridlineIntersection must be true or false gridlineIntersection harus true atau false +@msg the perspective grid is hidden kisi perspektif disembunyikan +@msg Automatic Plane Positioning is off: turn on anchorPoint or gridlineIntersection (perspective.widget.options) Penempatan bidang otomatis nonaktif: aktifkan anchorPoint atau gridlineIntersection (perspective.widget.options) @msg plug-in ABI: {0} ABI plug-in: {0} @msg plug-in exceeded its {0} plug-in melampaui {0}-nya @msg plug-in failed: {0} plug-in gagal: {0} @@ -5097,6 +5868,7 @@ imageTrace Outline Kontur @msg the PDF is password-protected: give its password PDF dilindungi kata sandi: berikan kata sandinya @msg the PDF password is wrong kata sandi PDF salah @msg the Save PDF dialog didn't open dialog Simpan PDF tidak terbuka +@msg the Save PDF dialog is not open dialog Simpan PDF tidak sedang terbuka @msg the WMF header is damaged header WMF rusak @msg the art could not be sampled karya seni tidak dapat diambil sampelnya @msg the art has no bounds karya seni tidak memiliki batas @@ -5287,6 +6059,7 @@ imageTrace Outline Kontur @msg onto must name a panel floating in another group onto harus menyebutkan panel yang mengambang di grup lain @msg below and above must name a panel floating in another group below dan above harus menyebutkan panel yang mengambang di grup lain @msg give only one of onto, below and above berikan hanya satu dari onto, below, dan above +@msg give only one of `index`, `indices` and `t` berikan hanya satu dari `index`, `indices`, dan `t` @msg column must be true or a number from 1 column harus true atau angka mulai dari 1 @msg x and y must both be numbers x dan y harus keduanya angka @msg "{0}" is not a colour: write it as #rrggbb "{0}" bukan warna: tulis sebagai #rrggbb @@ -5974,6 +6747,8 @@ mark-style Japanese Jepang Save Variable Library… Simpan pustaka variabel… @msg a variable library holds text variables, and the document has none pustaka variabel berisi variabel teks, dan dokumen tidak memilikinya @msg variable `{name}` can't be saved in a variable library: rename it to start with a letter or `_`, without spaces or symbols other than `-`, `_` and `.` variabel `{name}` tidak dapat disimpan dalam pustaka variabel: ganti namanya agar diawali huruf atau `_`, tanpa spasi atau simbol selain `-`, `_`, dan `.` +@msg {k} has control characters {k} berisi karakter kontrol +@msg {k} has control characters or line breaks {k} berisi karakter kontrol atau jeda baris @msg data set `{name}` holds a control character, which a variable library can't hold himpunan data `{name}` berisi karakter kontrol, yang tidak dapat dimuat dalam pustaka variabel @msg data set `{name}` starts or ends with white space, which a variable library can't hold himpunan data `{name}` diawali atau diakhiri spasi, yang tidak dapat dimuat dalam pustaka variabel @msg variables that aren't text were left out: {kinds} variabel yang bukan teks dihilangkan: {kinds} @@ -7365,6 +8140,8 @@ breakText Glyphs Glif # Path Precision Tools add-on: Tangent Circle. Tangent Circle… Lingkaran singgung… Tangent Circle Lingkaran singgung + Tangent Circle Tool Alat lingkaran singgung + No tangent circle here Tidak ada lingkaran singgung di sini Circle: Lingkaran: @msg `ids` names an object twice `ids` menyebut satu objek dua kali @msg select two or three paths or compound paths pilih dua atau tiga jalur atau jalur gabungan @@ -7380,6 +8157,16 @@ breakText Glyphs Glif @msg `circle` is past the last circle found ({found}) `circle` melewati lingkaran terakhir yang ditemukan ({found}) @msg object {value} is not a path or compound path objek {value} bukan jalur atau jalur gabungan @msg these shapes are too small to measure bentuk ini terlalu kecil untuk diukur +# Path Precision Tools add-on: Add Bounding Rectangle and Add Bounding Circle. + Add Bounding Rectangle Tambahkan persegi panjang pembatas + Add Bounding Circle Tambahkan lingkaran pembatas + Add Bounding Rectangle… Tambahkan persegi panjang pembatas… + Add Bounding Circle… Tambahkan lingkaran pembatas… + One per Object Satu per objek +@msg nothing to enclose tidak ada yang bisa dilingkupi +@msg `offset` must be 0 or more `offset` harus 0 atau lebih +@msg the shape would have no size bentuk tidak akan memiliki ukuran +@msg the shape would reach past the edge of the canvas bentuk akan melewati tepi kanvas # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Alat dokumen Save a Timestamped Copy Simpan salinan bercap waktu @@ -7701,6 +8488,50 @@ breakText Glyphs Glif @msg A joint does not close by {gap} pt. Sebuah sambungan tidak menutup sejauh {gap} pt. @msg Two panels pass through each other. Dua panel saling menembus. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer harus "singleLine", "everyLine", "standardSingleLine", atau "standardEveryLine" + Fine Stipple Arsiran titik halus + Dense Stipple Arsiran titik rapat + Soft Stipple Arsiran titik lembut + Bold Stipple Arsiran titik tebal + Paper Cutouts Potongan Kertas + Coral Layers Lapisan Koral + Mint Layers Lapisan Mint + Midnight Layers Lapisan Tengah Malam + Sunflower Sheet Lembar Bunga Matahari + Rose Layers Lapisan Mawar + Monochrome Stack Tumpukan Monokrom +# Tool cards (General › Show Tool Cards): one sentence on what each tool does. + Shows a card with what a toolbar tool does and what its keys do instead of its tip; it needs Show Tool Tips. Menampilkan kartu berisi fungsi alat di bilah alat dan tombolnya sebagai pengganti tipnya; memerlukan Tampilkan tips alat. + Selects whole objects and groups to move, resize or rotate them. Memilih objek dan grup utuh untuk dipindahkan, diubah ukurannya, atau diputar. + Selects anchor points and path segments to reshape a path. Memilih titik jangkar dan segmen jalur untuk mengubah bentuk jalur. + Draws paths point by point, with straight segments and smooth curves. Menggambar jalur titik demi titik, dengan segmen lurus dan lengkungan halus. + Draws smooth curves through the points you click. Menggambar lengkungan halus melalui titik yang Anda klik. + Adds text at a point, or in a frame you drag. Menambahkan teks di suatu titik atau di dalam bingkai yang Anda seret. + Draws rectangles and squares. Menggambar persegi panjang dan persegi. + Draws rectangles with rounded corners. Menggambar persegi panjang dengan sudut membulat. + Draws ellipses and circles. Menggambar elips dan lingkaran. + Draws polygons with sides of equal length. Menggambar poligon dengan sisi yang sama panjang. + Draws stars. Menggambar bintang. + Turns objects around a reference point. Memutar objek di sekitar titik referensi. + Flips objects across an axis through a reference point. Mencerminkan objek terhadap sumbu yang melalui titik referensi. + Resizes objects from a reference point. Mengubah ukuran objek dari titik referensi. + Slants objects from a reference point. Memiringkan objek dari titik referensi. + Moves the view of the document. Menggeser tampilan dokumen. + Magnifies or reduces the view. Memperbesar atau memperkecil tampilan. + Copies the color and other attributes of one object to the selection. Menyalin warna dan atribut lain dari satu objek ke pilihan. + Sets the direction and length of a gradient. Mengatur arah dan panjang gradien. + Creates, selects and resizes artboards. Membuat, memilih, dan mengubah ukuran artboard. + Changes the width of a stroke along its length. Mengubah lebar stroke di sepanjang panjangnya. + Bends art by dragging pins placed on it. Membengkokkan karya seni dengan menyeret pin yang dipasang padanya. + Pushes the outlines of paths in the direction you drag. Mendorong garis luar jalur ke arah yang Anda seret. + Twists the outlines of paths into swirls. Memelintir garis luar jalur menjadi pusaran. + Pulls the outlines of paths in toward the brush. Menarik garis luar jalur ke arah kuas. + Pushes the outlines of paths out from the brush. Mendorong garis luar jalur keluar dari kuas. + Adds curved details along the outlines of paths. Menambahkan detail melengkung di sepanjang garis luar jalur. + Adds spiky details along the outlines of paths. Menambahkan detail runcing di sepanjang garis luar jalur. + Adds wrinkles along the outlines of paths. Menambahkan kerutan di sepanjang garis luar jalur. + Moves, copies and resizes objects on the perspective grid. Memindahkan, menyalin, dan mengubah ukuran objek pada kisi perspektif. + Makes a series of steps between two or more objects. Membuat serangkaian langkah di antara dua objek atau lebih. + Places dimension lines that show measured lengths. Menempatkan garis dimensi yang menunjukkan panjang hasil pengukuran. Tap Tekan singkat Clear Hold Hapus Tahan Hold Shortcuts Pintasan tahan @@ -7717,3 +8548,288 @@ breakText Glyphs Glif Pulse Stroke Goresan Berdenyut Round Flow Aliran Bulat Chisel Flow Aliran Serong + +# Script files and their permissions, the script interpreter's errors, Liquify, SVG filters, image +# encoders, Revolve, swatch and color book readers, metadata templates, toolbars and other status +# and error messages. +@msg Script file access denied: {path} Akses file skrip ditolak: {path} +@msg Script file access to the app's own folders is not allowed Akses file skrip ke folder milik aplikasi tidak diizinkan +@msg Script file cannot encode the text File skrip tidak dapat mengodekan teks +@msg Script file could not be written File skrip tidak dapat ditulis +@msg Script file dialogs need a person to answer them Dialog file skrip memerlukan orang untuk menjawabnya +@msg Script file is not open for writing File skrip tidak dibuka untuk ditulis +@msg Script file name is already in use Nama file skrip sudah digunakan +@msg Script file name must be a name without a folder Nama file skrip harus berupa nama tanpa folder +@msg Script file permission can be kept only for a script run from a file Izin file skrip hanya dapat disimpan untuk skrip yang dijalankan dari file +@msg Script file permission could not be saved Izin file skrip tidak dapat disimpan +@msg Script folder is not empty Folder skrip tidak kosong +@msg Script files cannot make aliases File skrip tidak dapat membuat alias +@msg Script file hidden setting cannot be changed Pengaturan tersembunyi file skrip tidak dapat diubah +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: dialog file tidak dapat dibuka di dalam callback fungsi bawaan, getter, konversi, atau file yang dijalankan $.evalFile; panggil dari kode skrip itu sendiri +@msg the script wrote more file data than one run may write (32 MiB) skrip menulis data file lebih banyak daripada yang boleh ditulis dalam satu kali jalan (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` untuk dialog file skrip harus salah satu dari: once, always, deny, stop +@msg choose a file or folder first, or deny pilih file atau folder terlebih dahulu, atau tolak +@msg the script file permissions could not be saved: {e} izin file skrip tidak dapat disimpan: {e} +@msg this script's file access can be allowed only once akses file skrip ini hanya dapat diizinkan sekali +@msg Only the person at the keyboard can allow a script's file access Hanya orang yang berada di depan keyboard yang dapat mengizinkan akses file skrip +@msg A script is given at most 2,048 files: the files picked after them were left out Skrip diberi paling banyak 2.048 file: file yang dipilih sesudahnya dihilangkan +@msg assignment to a constant binding penetapan nilai ke binding konstanta +@msg invalid array length panjang array tidak valid +@msg array literal too long literal array terlalu panjang +@msg the value is not a function nilai tersebut bukan fungsi +@msg apply was called on a value that is not a function apply dipanggil pada nilai yang bukan fungsi +@msg the argument list is not an object daftar argumen bukan objek +@msg too many arguments terlalu banyak argumen +@msg the value is not a constructor nilai tersebut bukan konstruktor +@msg cannot convert the object to a primitive value objek tidak dapat dikonversi menjadi nilai primitif +@msg cannot convert undefined or null to an object undefined atau null tidak dapat dikonversi menjadi objek +@msg the right side of 'in' is not an object sisi kanan 'in' bukan objek +@msg the right side of 'instanceof' is not a function sisi kanan 'instanceof' bukan fungsi +@msg the function's prototype is not an object prototype fungsi bukan objek +@msg Error: {e} Error: {e} +@msg TypeError: {e} TypeError: {e} +@msg ReferenceError: {e} ReferenceError: {e} +@msg RangeError: {e} RangeError: {e} +@msg SyntaxError: {e} SyntaxError: {e} +@msg EvalError: {e} EvalError: {e} +@msg URIError: {e} URIError: {e} +@msg {ident} is not defined {ident} tidak didefinisikan +@msg cannot read property '{key}' of {base} properti '{key}' dari {base} tidak dapat dibaca +@msg cannot set property '{key}' of {base} properti '{key}' dari {base} tidak dapat diatur +@msg cannot read a property of {base} properti dari {base} tidak dapat dibaca +@msg cannot set a property of {base} properti dari {base} tidak dapat diatur +@msg cannot define property '{key}': {why} properti '{key}' tidak dapat didefinisikan: {why} +@msg cannot assign to property '{key}': {why} nilai tidak dapat ditetapkan ke properti '{key}': {why} +@msg cannot delete property '{key}' properti '{key}' tidak dapat dihapus +@msg cannot declare function {ident} fungsi {ident} tidak dapat dideklarasikan +@msg invalid assignment target target penetapan tidak valid +@msg the array's length is read-only panjang array bersifat baca-saja +@msg the property cannot be redefined properti tidak dapat didefinisikan ulang +@msg the object is not extensible objek tidak dapat diperluas +@msg the length cannot be redefined panjang tidak dapat didefinisikan ulang +@msg it is read-only properti itu baca-saja +@msg an element cannot be deleted elemen tidak dapat dihapus +@msg it has only a getter properti itu hanya memiliki getter +@msg the value is a primitive nilai tersebut primitif +@msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use `answers` memiliki {n} jawaban yang tidak digunakan skrip +@msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1} membiarkan {n} objek di bawah kuas seperti semula ({_2}): alat ini hanya membentuk ulang jalur +liquify-tool Warp Warp +liquify-tool Twirl Pilin +liquify-tool Pucker Pucker +liquify-tool Bloat Bloat +liquify-tool Scallop Scallop +liquify-tool Crystallize Kristalisasi +liquify-tool Wrinkle Kerut +liquify-kind graphs grafik +liquify-kind type teks +liquify-kind symbols simbol +liquify-kind images gambar +liquify-kind meshes mesh +liquify-kind envelopes amplop +liquify-kind repeats pengulangan +liquify-kind placed documents dokumen tertempat +liquify-kind blends blend +liquify-list-two {0}, {1} {0} dan {1} +liquify-list-middle {0}, {1} {0}, {1} +liquify-list-end {0}, {1} {0}, dan {1} +@msg give one element berikan satu elemen +@msg the element needs an id, the filter's name elemen memerlukan id, yaitu nama filter +@msg an SVG filter's id is at most {MAX_NAME} characters id filter SVG paling banyak {MAX_NAME} karakter +@msg <{_1}> isn't an element of an SVG filter <{_1}> bukan elemen filter SVG +@msg an SVG filter has no event attributes such as {_1} filter SVG tidak boleh memiliki atribut peristiwa seperti {_1} +@msg an SVG filter's images are PNG, JPEG, GIF or WebP data: URLs gambar filter SVG berupa URL data: PNG, JPEG, GIF, atau WebP +@msg the SVG filter isn't valid XML: {e} filter SVG bukan XML yang valid: {e} +@msg feTurbulence's numOctaves is at most {MAX_OCTAVES} numOctaves feTurbulence paling banyak {MAX_OCTAVES} +@msg {what} is at most {max} {what} paling banyak {max} +@msg feConvolveMatrix's order order feConvolveMatrix +@msg feMorphology's radius radius feMorphology +@msg a blur's stdDeviation stdDeviation efek kabur +@msg the SVG filter has no primitives filter SVG tidak memiliki primitif +@msg an SVG filter has at most {MAX_PRIMITIVES} primitives filter SVG memiliki paling banyak {MAX_PRIMITIVES} primitif +@msg the SVG filter is too large once its attributes are written out filter SVG terlalu besar setelah atributnya ditulis lengkap +@msg an SVG filter's images have at most {MAX_IMAGE_PIXELS} pixels in all gambar filter SVG memiliki total paling banyak {MAX_IMAGE_PIXELS} piksel +@msg the SVG filter can't be drawn: check its primitives and their inputs filter SVG tidak dapat digambar: periksa primitif dan masukannya +@msg an SVG filter's elements nest at most {MAX_DEPTH} deep elemen filter SVG bersarang paling dalam {MAX_DEPTH} tingkat +@msg an SVG filter is at most {_1} KB ukuran filter SVG paling besar {_1} KB +@msg `axes` must be [a, b, c, d], each from -1000 to 1000, with a·d - b·c at least 0.001 from 0 `axes` harus berupa [a, b, c, d], masing-masing dari -1000 sampai 1000, dengan a·d - b·c berjarak paling sedikit 0,001 dari 0 +@msg `angle` must be from -180 to 180 degrees `angle` harus dari -180 sampai 180 derajat +@msg `roundness` must be from 0 to 100% `roundness` harus dari 0 sampai 100% +@msg `fidelity` must be from 0.01 to 100 pt `fidelity` harus dari 0.01 sampai 100 pt +@msg style must be "pencil" or "brush" style harus "pencil" atau "brush" +@msg extend end must be "start" or "end" extend end harus "start" atau "end" +@msg connect end must be "start" or "end" connect end harus "start" atau "end" +@msg `roundness` must be from 1 to 100% `roundness` harus dari 1 sampai 100% +@msg 3D effects require finite coordinates within 100 million points Efek 3D memerlukan koordinat berhingga dalam batas 100 juta poin +@msg 3D effects require one to ten lights Efek 3D memerlukan satu sampai sepuluh cahaya +@msg BMP depth {_1}: 1, 4, 8, 16, 24 or 32 bits per pixel Kedalaman BMP {_1}: 1, 4, 8, 16, 24, atau 32 bit per piksel +@msg BMP encoding failed: {width} × {height} pixels doesn't fit the format or the pixel buffer Pengodean BMP gagal: {width} × {height} piksel tidak sesuai dengan format atau buffer piksel +@msg GIF encoding failed: the palette image is malformed Pengodean GIF gagal: gambar palet rusak +@msg GIF encoding failed: {e} Pengodean GIF gagal: {e} +@msg JPEG colour profile: {e} Profil warna JPEG: {e} +@msg JPEG encoding failed: pixel buffer doesn't match the image size Pengodean JPEG gagal: buffer piksel tidak sesuai dengan ukuran gambar +@msg JPEG encoding failed: {e} Pengodean JPEG gagal: {e} +@msg PNG encoding failed: pixel buffer doesn't match the image size Pengodean PNG gagal: buffer piksel tidak sesuai dengan ukuran gambar +@msg PNG encoding failed: the palette image is malformed Pengodean PNG gagal: gambar palet rusak +@msg PNG encoding failed: {e} Pengodean PNG gagal: {e} +@msg PNG encoding failed: {width} × {height} pixels is not a valid image size Pengodean PNG gagal: {width} × {height} piksel bukan ukuran gambar yang valid +@msg PSD colour profile: {e} Profil warna PSD: {e} +@msg PSD encoding failed: the pixel buffer doesn't match the image size Pengodean PSD gagal: buffer piksel tidak sesuai dengan ukuran gambar +@msg Revolve profile contains invalid coordinates Profil Revolusi berisi koordinat yang tidak valid +@msg Revolve profile is too complex Profil Revolusi terlalu rumit +@msg Revolve projection is not finite Proyeksi Revolusi tidak berhingga +@msg Revolve requires finite profile coordinates within 100 million points Revolusi memerlukan koordinat profil berhingga dalam batas 100 juta poin +@msg Revolve surface is too complex; reduce Segments or simplify the profile Permukaan Revolusi terlalu rumit; kurangi Segmen atau sederhanakan profil +@msg Revolve surface is too complex; simplify the profile Permukaan Revolusi terlalu rumit; sederhanakan profil +@msg Revolve visibility cannot split the projected boundary Visibilitas Revolusi tidak dapat membagi batas hasil proyeksi +@msg Revolve visibility creates too many fragments Visibilitas Revolusi menghasilkan terlalu banyak fragmen +@msg Revolve visibility creates too many vector anchors Visibilitas Revolusi menghasilkan terlalu banyak titik jangkar vektor +@msg Revolve visibility exceeds its geometry work limit Visibilitas Revolusi melampaui batas kerja geometrinya +@msg Revolve visibility exceeds its spatial index limit Visibilitas Revolusi melampaui batas indeks spasialnya +@msg Revolve visibility has too many boundary crossings Visibilitas Revolusi memiliki terlalu banyak perpotongan batas +@msg Revolve visibility has too many input anchors Visibilitas Revolusi memiliki terlalu banyak titik jangkar masukan +@msg Revolve visibility requires convex cap sectors Visibilitas Revolusi memerlukan sektor tutup yang cembung +@msg Revolve visibility requires finite projected faces Visibilitas Revolusi memerlukan sisi hasil proyeksi yang berhingga +@msg SVG options: {e} Opsi SVG: {e} +@msg Save for Web settings: {e} Pengaturan Simpan untuk web: {e} +@msg TIFF colour profile: {e} Profil warna TIFF: {e} +@msg TIFF encoding failed: the pixel buffer doesn't match the image size Pengodean TIFF gagal: buffer piksel tidak sesuai dengan ukuran gambar +@msg TIFF encoding failed: {e} Pengodean TIFF gagal: {e} +@msg Targa depth {_1}: 16, 24 or 32 bits per pixel Kedalaman Targa {_1}: 16, 24, atau 32 bit per piksel +@msg Targa encoding failed: the pixel buffer doesn't match the image size Pengodean Targa gagal: buffer piksel tidak sesuai dengan ukuran gambar +@msg The 3D projection is not finite Proyeksi 3D tidak berhingga +@msg The 3D shadow is too complex; turn Shadows off or simplify the art Bayangan 3D terlalu rumit; nonaktifkan Bayangan atau sederhanakan karya +@msg The shape contains invalid coordinates Bentuk berisi koordinat yang tidak valid +@msg Too many Revolve faces for visibility evaluation Terlalu banyak sisi Revolusi untuk evaluasi visibilitas +@msg VectorCraft reads at most {ASE_MAX_ENTRIES} colors and groups from a swatch exchange file, and this library has {entries} VectorCraft membaca paling banyak {ASE_MAX_ENTRIES} warna dan grup dari file swatch exchange, dan pustaka ini memiliki {entries} +@msg WebP encoding failed: {e} Pengodean WebP gagal: {e} +@msg WebP encoding failed: the image is too large for lossy WebP: lower the resolution or choose Lossless Pengodean WebP gagal: gambar terlalu besar untuk WebP lossy: turunkan resolusi atau pilih Tanpa kehilangan +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope` harus "document", {{artboards: [index, …]}}, atau {{layers: [id, …]}} +@msg `view` is smallThumb, mediumThumb, largeThumb, smallList or largeList `view` berupa smallThumb, mediumThumb, largeThumb, smallList, atau largeList +@msg `{file}` has no swatches of its own `{file}` tidak memiliki swatch sendiri +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` memiliki swatch pola, yang tidak dapat disimpan dalam file .vcswatches +@msg a line can't run from a point to itself garis tidak dapat ditarik dari suatu titik ke titik itu sendiri +@msg a line needs at least two points garis memerlukan paling sedikit dua titik +@msg a linked image file is outside the read roots file gambar tertaut berada di luar root baca +@msg a linked file's export folder is outside the read roots folder ekspor file tertaut berada di luar root baca +@msg a number cannot be read sebuah angka tidak dapat dibaca +@msg a swatch exchange block is too long blok swatch exchange terlalu panjang +@msg a swatch exchange name is too long nama swatch exchange terlalu panjang +@msg a {sw} × {sh} image can't be resized to {width} × {height} pixels gambar {sw} × {sh} tidak dapat diubah ukurannya menjadi {width} × {height} piksel +@msg a {width} × {height} image is too large gambar {width} × {height} terlalu besar +@msg a {width} × {height} image: {e} gambar {width} × {height}: {e} +@msg an image could not be written: {e} sebuah gambar tidak dapat ditulis: {e} +@msg an image that couldn't be read was left out gambar yang tidak dapat dibaca dihilangkan +@msg can't open “{name}”: {e} tidak dapat membuka “{name}”: {e} +@msg cannot align zip entries to {align} bytes entri zip tidak dapat diratakan ke {align} byte +@msg cannot open the automation {kind} root `{_1}`: {e} root {kind} otomatisasi `{_1}` tidak dapat dibuka: {e} +@msg cannot read profile: {0} profil tidak dapat dibaca: {0} +@msg color book version {version} isn't supported (only 1) versi buku warna {version} tidak didukung (hanya 1) +@msg color books in color space {other} aren't supported (only RGB, CMYK and Lab) buku warna dalam ruang warna {other} tidak didukung (hanya RGB, CMYK, dan Lab) +@msg file name too long to zip: {_1} nama file terlalu panjang untuk zip: {_1} +@msg file name too long to zip: {name} nama file terlalu panjang untuk zip: {name} +@msg freeform line {i}: {e} garis bentuk bebas {i}: {e} +@msg freeform point {i}: {e} titik bentuk bebas {i}: {e} +@msg give `{key}` or `{other}`, not both berikan `{key}` atau `{other}`, bukan keduanya +@msg grayscale profiles can't be working spaces yet profil skala abu-abu belum dapat menjadi ruang kerja +@msg input contains NaN or infinite coordinates masukan berisi koordinat NaN atau tak hingga +@msg input path could not be closed jalur masukan tidak dapat ditutup +@msg invalid ICC profile: {0} profil ICC tidak valid: {0} +@msg invalid scale {scale} skala {scale} tidak valid +@msg its localized names take more than {_1} KB nama yang dilokalkan memakan lebih dari {_1} KB +@msg its objects are nested too deep ({e}) objeknya bersarang terlalu dalam ({e}) +@msg its tag table lists the `{_1}` tag more than once tabel tag mencantumkan tag `{_1}` lebih dari sekali +@msg no similar objects found (reflected copies are not matched); change the Global Edit Options and try again tidak ditemukan objek serupa (salinan yang dicerminkan tidak dicocokkan); ubah Opsi edit global lalu coba lagi +@msg not a graphic style library: {e} bukan pustaka gaya grafis: {e} +@msg not a swatch library (.vcswatches or .gpl) bukan pustaka swatch (.vcswatches atau .gpl) +@msg not a swatch library (format `{_1}`) bukan pustaka swatch (format `{_1}`) +@msg not a swatch library: {e} bukan pustaka swatch: {e} +@msg not an action set file ({e}) bukan file set tindakan ({e}) +@msg numbers out of order in {{}} quantifier angka tidak berurutan dalam kuantifier {{}} +@msg profile colour space {other} is not RGB, CMYK or Gray ruang warna profil {other} bukan RGB, CMYK, atau Gray +@msg regular expression too large ekspresi reguler terlalu besar +@msg script file is not UTF-8 text: {value} file skrip bukan teks UTF-8: {value} +@msg step {step} of “{action}” runs the unknown command `{command}` langkah {step} dari “{action}” menjalankan perintah tidak dikenal `{command}` +@msg stop {i}: {e} perhentian {i}: {e} +@msg swatch exchange version {major}.{minor} isn't supported (only 1.x) versi swatch exchange {major}.{minor} tidak didukung (hanya 1.x) +@msg text.{key} `{v}`: use "{_1}" or "{_2}" text.{key} `{v}`: gunakan "{_1}" atau "{_2}" +@msg the SVG's style sheets take too long to match lembar gaya SVG terlalu lama untuk dicocokkan +@msg the SVG's styles expand to more than {0} MB gaya SVG berkembang menjadi lebih dari {0} MB +@msg the color book holds more than {ASE_MAX_ENTRIES} colors buku warna berisi lebih dari {ASE_MAX_ENTRIES} warna +@msg the color book is cut short buku warna terpotong +@msg the color book's names take more than {_1} MB nama dalam buku warna memakan lebih dari {_1} MB +@msg the image would be {w} × {h} pixels; raster exports are limited to {MAX_RASTER_SIDE} pixels per side and {_1} megapixels: lower the scale or resolution gambar akan berukuran {w} × {h} piksel; ekspor raster dibatasi {MAX_RASTER_SIDE} piksel per sisi dan {_1} megapiksel: turunkan skala atau resolusi +@msg the optimised image can't be read back: {e} gambar yang dioptimalkan tidak dapat dibaca kembali: {e} +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) cat bukan gradien bentuk bebas (terapkan dengan paint.editGradient {{kind: "freeform"}}) +@msg the pixel buffer doesn't match the image size buffer piksel tidak sesuai dengan ukuran gambar +@msg the preview: {e} pratinjau: {e} +@msg the request may not read the New Document profiles folder permintaan tidak boleh membaca folder profil Dokumen baru +@msg the shapes are too degenerate to combine bentuk terlalu degeneratif untuk digabungkan +@msg the shapes cross themselves and each other too often to combine bentuk terlalu sering memotong dirinya sendiri dan satu sama lain untuk digabungkan +@msg the swatch exchange file holds more than {ASE_MAX_ENTRIES} colors and groups file swatch exchange berisi lebih dari {ASE_MAX_ENTRIES} warna dan grup +@msg the swatch exchange file is cut short file swatch exchange terpotong +@msg the {_1} plate can't be read: {e} pelat {_1} tidak dapat dibaca: {e} +@msg this binary DXF file is damaged or cut short file DXF biner ini rusak atau terpotong +@msg this is a DWG drawing, which can't be read: save it from the CAD app as a DXF and open that ini gambar DWG, yang tidak dapat dibaca: simpan dari aplikasi CAD sebagai DXF lalu buka file itu +@msg too many classes terlalu banyak kelas +@msg too many groups terlalu banyak grup +@msg too many layers for PSD (at most 32767) terlalu banyak lapisan untuk PSD (paling banyak 32767) +@msg too many swatch exchange blocks terlalu banyak blok swatch exchange +@msg unknown colour profile: {0} profil warna tidak dikenal: {0} +@msg {_1} clashes with a built-in profile name {_1} bentrok dengan nama profil bawaan +@msg {_1} × {_2} pixels is too large for GIF (at most 65535 pixels a side): lower the resolution {_1} × {_2} piksel terlalu besar untuk GIF (paling banyak 65535 piksel per sisi): turunkan resolusi +@msg {_1}: no usable transform to/from sRGB {_1}: tidak ada transformasi yang dapat digunakan ke/dari sRGB +@msg {name} is not a CMYK profile {name} bukan profil CMYK +@msg {name} is not an RGB profile {name} bukan profil RGB +@msg {path}: could not be read {path}: tidak dapat dibaca +@msg {width} × {height} pixels is too large for JPEG (at most 65535 pixels a side): lower the resolution {width} × {height} piksel terlalu besar untuk JPEG (paling banyak 65535 piksel per sisi): turunkan resolusi +@msg {width} × {height} pixels is too large for Targa (at most 65535 pixels a side): lower the resolution {width} × {height} piksel terlalu besar untuk Targa (paling banyak 65535 piksel per sisi): turunkan resolusi +@msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} piksel terlalu besar untuk PSD (paling banyak {MAX_SIDE} piksel per sisi): turunkan resolusi +@msg the template name can't be empty nama templat tidak boleh kosong +@msg the template name isn't usable as a file name nama templat tidak dapat digunakan sebagai nama file +@msg no metadata templates folder here tidak ada folder templat metadata di sini +@msg give `name` or `path`, not both berikan `name` atau `path`, bukan keduanya +@msg give one of `path`, `name` and `data` berikan salah satu dari `path`, `name`, dan `data` +@msg mode must be replace, keep or append mode harus replace, keep, atau append +@msg the file is not an XMP metadata template file ini bukan templat metadata XMP +@msg no path painted with a brush is selected tidak ada jalur yang dicat dengan kuas yang terseleksi +@msg the selected paths are painted with brushes of different types jalur yang terseleksi dicat dengan kuas dari jenis yang berbeda +@msg give `params` or `reset`, not both berikan `params` atau `reset`, bukan keduanya +@msg a bristle brush has no options of its own on a path kuas bulu tidak memiliki opsi sendiri pada jalur +@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all beberapa efek raster tidak dijadikan gambar: efek tersebut akan memerlukan total lebih dari 1.024 gambar atau 256 megapiksel +@msg Shape Builder: select all paths you want to merge Pembangun bentuk: pilih semua jalur yang ingin digabungkan +@msg action step {_1} (`{id}`) failed: {reason} langkah tindakan {_1} (`{id}`) gagal: {reason} +@msg `points` must be three [x, y] pairs of numbers `points` harus berupa tiga pasangan angka [x, y] +@msg direct-select three anchor points, or give `points` pilih langsung tiga titik jangkar, atau berikan `points` +@msg no circle passes through these points: two are the same or all three lie on one line tidak ada lingkaran yang melewati titik-titik ini: dua titik sama atau ketiganya terletak pada satu garis +@msg `{panel}` has no display sizes to cycle `{panel}` tidak memiliki ukuran tampilan untuk diganti bergiliran +@msg the panels are not shown panel tidak ditampilkan +@msg a line or other open path that encloses no area does not change the result's shape; to include it, apply Object › Path › Outline Stroke to it first garis atau jalur terbuka lain yang tidak melingkupi area tidak mengubah bentuk hasil; untuk menyertakannya, terapkan Objek › Jalur › Garis luar stroke padanya terlebih dahulu +@msg {label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first {label} memberikan hasil kosong: garis atau jalur terbuka lain tidak melingkupi area; untuk menyertakannya, terapkan Objek › Jalur › Garis luar stroke padanya terlebih dahulu +@msg a line or other open path that encloses no area contributes no area to the compound shape; to include it, apply Object › Path › Outline Stroke to it first garis atau jalur terbuka lain yang tidak melingkupi area tidak menambahkan area ke bentuk majemuk; untuk menyertakannya, terapkan Objek › Jalur › Garis luar stroke padanya terlebih dahulu +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} Sematan {n} gambar dilepaskan ke {folder} +@msg every numbered name for {name} is taken in that folder setiap nama bernomor untuk {name} sudah dipakai di folder itu +@msg Import reads a data source file ending in .csv, .tsv, .txt or .xml Impor membaca file sumber data yang berakhiran .csv, .tsv, .txt, atau .xml +variable-kind Visibility Visibilitas +variable-kind Linked File File tertaut +variable-kind Graph Data Data grafik +variable-kind Unknown Tidak diketahui +variable-list-two {0}, {1} {0} dan {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0}, dan {1} +@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: Minimum tidak boleh melebihi Diinginkan, dan Diinginkan tidak boleh melebihi Maksimum +@msg side is left or right, not `{v}` side berupa left atau right, bukan `{v}` +@msg order is a whole number from 0 to {others}, not `{v}` order berupa bilangan bulat dari 0 sampai {others}, bukan `{v}` +@msg toolbar (a toolbar's name) must be a string toolbar (nama bilah alat) harus berupa string +@msg no toolbar named `{name}` tidak ada bilah alat bernama `{name}` +@msg toolbar name can't be empty nama bilah alat tidak boleh kosong +@msg a toolbar name has at most {MAX_NAME} characters nama bilah alat paling banyak {MAX_NAME} karakter +@msg there is already a toolbar named `{name}` sudah ada bilah alat bernama `{name}` +@msg there is already a toolbar named `{to}` sudah ada bilah alat bernama `{to}` +@msg a workspace keeps at most {MAX} toolbars ruang kerja menyimpan paling banyak {MAX} bilah alat +@msg name (a toolbar's name) must be a string name (nama bilah alat) harus berupa string +@msg name (a toolbar's name) is required name (nama bilah alat) wajib diisi +@msg to (the new name) is required to (nama baru) wajib diisi +@msg name must be a toolbar's name name harus berupa nama bilah alat +# #5804 native-picked raster editor (draft translations; native review welcome). + Edit Original with: Edit asli dengan: +file-filter Applications Aplikasi diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 8fe43c6bff..ebfb5764e5 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -500,6 +500,9 @@ font-technology Variable Variabili Choose… Scegli… Circle Cerchio Circle Tool Strumento Cerchio + Curvature Circle Tool Strumento Cerchio di curvatura + Cusp Cuspide + Straight segment Segmento diritto Circle too large Cerchio troppo grande Classic Defaults Valori predefiniti classici Clean Up… Pulisci… @@ -607,6 +610,9 @@ font-technology Variable Variabili Box Channel Canale del riquadro Color box Riquadro colore Color Wheel Options Opzioni ruota dei colori + Show Harmony Mostra armonia + Harmony Rule Regola di armonia + Harmony color Colore dell’armonia Color Type: Tipo di colore: Color: Colore: Colorize Colora @@ -1040,10 +1046,25 @@ font-technology Variable Variabili Duplicate Symbol Duplica simbolo Duplicate {kind} Style Duplica stile {kind} Dutch Olandese + PSD Import Options Opzioni di importazione PSD + Place PSD Inserisci PSD + Convert Layers to Objects Converti livelli in oggetti + Import Hidden Layers Importa livelli nascosti + Flatten Layers to a Single Image Appiattisci livelli in un’unica immagine + Import Slices Importa sezioni DXF Import Options Opzioni di importazione DXF DXF Info Informazioni DXF DXF Options Opzioni DXF DXF Options Dialog Finestra di dialogo Opzioni DXF + HP-GL Options Opzioni HP-GL + HP-GL Options Dialog Finestra di dialogo Opzioni HP-GL + Curve Tolerance: Tolleranza delle curve: + Origin: Origine: + Pens: Penne: + One Pen per Color Una penna per colore + Pen Table Tabella delle penne + Draw the Nearest Path Next Disegna poi il tracciato più vicino + Draw Inner Paths First Disegna prima i tracciati interni e.g. 1-3, 5 es. 1-3, 5 Each page prints as one image, at the document's raster effects resolution. Ogni pagina viene stampata come un'unica immagine, alla risoluzione degli effetti raster del documento. Earth Tones Toni della terra @@ -1282,6 +1303,15 @@ font-technology Variable Variabili Shading Color Colore ombreggiatura Black Overprint Nero in sovrastampa Draw Hidden Faces Disegna facce nascoste + Map Art… Mappa grafica… + Map Art Mappa grafica + First Surface Prima superficie + Previous Surface Superficie precedente + Next Surface Superficie successiva + Last Surface Ultima superficie + Scale to Fit Ridimensiona per adattare + Shade Artwork Ombreggia grafica + Invisible Geometry Geometria invisibile Eyedropper Contagocce Sample Color from Screen Campiona colore dallo schermo This system has no screen color sampler Questo sistema non ha un campionatore di colore dello schermo @@ -1411,6 +1441,17 @@ font-technology Variable Variabili Largest: Più grande: Direction: Direzione: Symbolism Tools Options Opzioni strumenti simboli + Tool: Strumento: + Symbol Set Density Densità del set di simboli + Symbol Sprayer Options Opzioni spruzzo simboli + Scrunch: Addensamento: + Spin: Rotazione: + Screen: Trasparenza: + Stain: Colorazione: + Symbol Sizer Options Opzioni ridimensionamento simboli + Proportional Resizing Ridimensionamento proporzionale + Resizing Affects Density Il ridimensionamento influisce sulla densità + Show Brush Size and Intensity Mostra dimensione e intensità del pennello Symbol Set Density: Densità del set di simboli: Flat Image Immagine appiattita Flat Logo Logo piatto @@ -1692,6 +1733,8 @@ file-filter Templates Modelli More Options Altre opzioni Show Properties Panel Mostra pannello Proprietà Hide Corner Widget Nascondi widget angolo + Hide Shape Widgets Nascondi widget forma + Show Shape Widgets Mostra widget forma Hide Corner Widget for angles greater than Nascondi widget angolo per angoli maggiori di Hide Edges Nascondi bordi Hide Gradient Annotator Nascondi annotatore sfumatura @@ -2264,6 +2307,15 @@ file-filter Templates Modelli YakumonoZenkaku YakumonoZenkaku Kinsoku Set Set kinsoku Kinsoku Shori Type Tipo di kinsoku shori + Kinsoku Shori Settings… Impostazioni kinsoku shori… + Kinsoku Shori Settings Impostazioni kinsoku shori + Kinsoku Sets Elenco set kinsoku + Kinsoku Set Base Base del set kinsoku + Based on: Basato su: + Cannot Start Line Non può iniziare la riga + Cannot End Line Non può terminare la riga + Hanging Punctuation Punteggiatura sospesa + Inseparable Characters Caratteri inseparabili Push In First Prima all'interno Push Out First Prima all'esterno Push Out Only Solo all'esterno @@ -2382,6 +2434,7 @@ file-filter Templates Modelli Pressure Pressione Tilt Inclinazione Bearing Orientamento + Stylus Wheel Rotella dello stilo Shape: Forma: Bristle Length: Lunghezza setole: Bristle Density: Densità setole: @@ -2412,6 +2465,9 @@ file-filter Templates Modelli embedding for preview and print incorporamento per anteprima e stampa embedding allowed incorporamento consentito {file}; {embedding} {file}; {embedding} + unknown type tipo sconosciuto + {type}; {uses} {type}; {uses} +@plural {n} use|{n} uses {n} utilizzo|{n} utilizzi substituted: shown in {family} {style} ({detail}) sostituito: mostrato con {family} {style} ({detail}) missing: shown in {family} {style} mancante: mostrato con {family} {style} missing mancante @@ -2684,6 +2740,8 @@ file-filter Templates Modelli Overprint and Transparency Flattener Options Opzioni sovrastampa e appiattimento trasparenza Custom… Personalizzato… Custom Transparency Flattener Options Opzioni di appiattimento trasparenza personalizzate + The PDF preset keeps the flattener preset but not the Custom… settings. Il preset PDF mantiene il preset di appiattimento, ma non le impostazioni di Personalizzato…. + PDF 1.3 files clip rasterized areas to their regions, and Overprint sets whether overprints are kept. I file PDF 1.3 ritagliano le aree rasterizzate alle loro regioni, e Sovrastampa stabilisce se le sovrastampe vengono mantenute. EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS non ha trasparenza alfa, e Sovrastampe stabilisce se le sovrastampe vengono mantenute. Overprint Black… Sovrastampa nero… Overprint Fill Sovrastampa riempimento @@ -3204,6 +3262,9 @@ digits Malayalam Malayalam Rotate View to Selection Ruota vista in base alla selezione Reset the rows to the artwork's colors Reimposta le righe sui colori della grafica Color Theme Picker Selettore tema colore + Undo Changes Annulla modifiche + Redo Changes Ripeti modifiche +@msg Recolor Artwork is not open Ricolora grafica non è aperto Click or drag across the art to pick its colors; Shift adds more Fai clic o trascina sulla grafica per prelevarne i colori; Maiusc ne aggiunge altri Prominent Colors Colori prominenti Save All Colors Salva tutti i colori @@ -3258,6 +3319,7 @@ digits Malayalam Malayalam A live rectangle's properties show one Corner Radius field for all four corners; off, each corner has its own field. Le proprietà di un rettangolo dinamico mostrano un solo campo Raggio angolo per tutti e quattro gli angoli; se disattivata, ogni angolo ha il proprio campo. What edits in the Transform panel transform: the object, its pattern tiles or both; Default follows Transform Pattern Tiles. Cosa trasformano le modifiche nel pannello Trasforma: l'oggetto, i suoi tasselli motivo o entrambi; Predefinito segue Trasforma tasselli motivo. With one symbol instance selected, the Transform panel uses the symbol's registration point as its reference point. Con un'istanza di simbolo selezionata, il pannello Trasforma usa il punto di registrazione del simbolo come punto di riferimento. + Drawing a rectangle, ellipse, polygon, star or line opens the Transform panel if it is closed. Disegnare un rettangolo, un'ellisse, un poligono, una stella o una linea apre il pannello Trasforma se è chiuso. Darkens the canvas outside the artboards while the Artboard tool is active. Scurisce l'area di lavoro fuori dalle tavole da disegno mentre lo strumento Tavola da disegno è attivo. With Fade Region Outside Artboard on, the area outside the artboards stays dark while you drag with the Artboard tool. Con Attenua area esterna alla tavola da disegno attivo, l'area fuori dalle tavole da disegno resta scura mentre trascini con lo strumento Tavola da disegno. How near, in pixels, the pointer must be to an object, anchor or handle for a click to select it. Quanto vicino, in pixel, deve trovarsi il puntatore a un oggetto, punto di ancoraggio o maniglia perché un clic lo selezioni. @@ -3438,6 +3500,7 @@ digits Malayalam Malayalam Save Document Preset Salva preset documento Preset {number} Preset {number} Save Preset… Salva preset… + Save Summary… Salva riepilogo… Save Print Preset Salva preset di stampa Save Recovery Data Salva dati di recupero Save Save for Web Preset Salva preset di Salva per il web @@ -3746,6 +3809,7 @@ digits Malayalam Malayalam Show Modified Mostra modificati Show Note Mostra nota Show Options Mostra opzioni + Show on Shape Creation Mostra alla creazione di forme Show Recent Colors Mostra colori recenti Toggle RGB Percent Alterna RGB in percentuale Show Original Path Mostra tracciato originale @@ -3773,6 +3837,7 @@ digits Malayalam Malayalam Show Thumbnails Mostra miniature Show Tile Edge Mostra bordo tassello Show Tints/Shades Mostra tinte/toni scuri + Show Tool Cards Mostra schede degli strumenti Show Tool Tips Mostra descrizioni comandi Show Transparency Grid Mostra griglia trasparenza Show Video Rulers Mostra righelli video @@ -3858,6 +3923,8 @@ digits Malayalam Malayalam Outlines Contorni Outlines with Source Image Contorni con immagine di origine Source Image Immagine di origine + Split View Vista divisa + Divider Divisore Press and hold to view the source image Tieni premuto per visualizzare l'immagine di origine Image Trace View Vista del ricalco immagine Snap Options Opzioni di aggancio @@ -4311,6 +4378,8 @@ digits Malayalam Malayalam Unembed… Rimuovi incorporamento… Ungroup Separa Ungroup Color Group Separa gruppo colori + Color Group Options Opzioni gruppo colori + Color Group Options… Opzioni gruppo colori… Unicode Unicode Unicode (UTF-16) Unicode (UTF-16) Unicode (UTF-8) Unicode (UTF-8) @@ -5102,6 +5171,7 @@ liquify-list-end {0}, {1} {0} e {1} @msg a freeform gradient keeps at least one point una sfumatura a forma libera mantiene almeno un punto @msg a gradient needs at least two stops una sfumatura richiede almeno due cursori colore @msg a graphic style named `{to}` already exists esiste già uno stile grafico denominato `{to}` +@msg a swatch or color group named `{name}` already exists esiste già un campione o un gruppo colori denominato `{name}` @msg a key object sits on that point su quel punto si trova un oggetto chiave @msg a page is missing manca una pagina @msg a page out of range una pagina fuori intervallo @@ -5243,6 +5313,11 @@ liquify-list-end {0}, {1} {0} e {1} @msg no anchor points selected nessun punto di ancoraggio selezionato @msg `points` must be two or three [x, y] pairs of numbers `points` deve essere composto da due o tre coppie di numeri [x, y] @msg direct-select two or three anchor points, or give `points` seleziona con Selezione diretta due o tre punti di ancoraggio oppure indica `points` +@msg the path is straight there, so no circle matches its curvature il tracciato è diritto in quel punto, quindi nessun cerchio corrisponde alla sua curvatura +@msg the path has a cusp there, so it has no single curvature il tracciato ha una cuspide in quel punto, quindi non ha un'unica curvatura +@msg the path has a corner there, so it has no single curvature il tracciato ha un angolo in quel punto, quindi non ha un'unica curvatura +@msg a guide has no curvature circle una guida non ha un cerchio di curvatura +@msg the circle that matches the path there would reach past the canvas il cerchio che corrisponde al tracciato in quel punto supererebbe l'area di lavoro @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 @@ -5499,6 +5574,7 @@ liquify-list-end {0}, {1} {0} e {1} @msg the PDF is password-protected: give its password il PDF è protetto da password: specifica la password @msg the PDF password is wrong la password del PDF è errata @msg the Save PDF dialog didn't open la finestra di dialogo Salva PDF non si è aperta +@msg the Save PDF dialog is not open la finestra di dialogo Salva PDF non è aperta @msg the WMF header is damaged l'intestazione WMF è danneggiata @msg the art could not be sampled impossibile campionare la grafica @msg the art has no bounds la grafica non ha limiti @@ -5722,6 +5798,7 @@ variable-list-end {0}, {1} {0} e {1} @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 +@msg give only one of `index`, `indices` and `t` indica solo uno tra `index`, `indices` e `t` @msg column must be true or a number from 1 column deve essere true o un numero da 1 @msg x and y must both be numbers x e y devono essere entrambi numeri @msg "{0}" is not a colour: write it as #rrggbb "{0}" non è un colore: scrivilo come #rrggbb @@ -5865,6 +5942,49 @@ variable-list-end {0}, {1} {0} e {1} @msg the PSD file's layer groups are nested too deeply i gruppi di livelli del file PSD sono annidati troppo in profondità @msg a layer of the PSD file is too large to read un livello del file PSD è troppo grande per essere letto @msg the PSD file's layers take more memory to read than allowed i livelli del file PSD richiedono più memoria del consentito per essere letti +@msg the file is no longer loaded il file non è più caricato +@msg the layers can't be read ({e}): the file was placed as its merged image i livelli non possono essere letti ({e}): il file è stato inserito come immagine unita +@msg 1 type layer came in as pixels: the text isn't editable 1 livello di testo è stato importato come pixel: il testo non è modificabile +@msg {n} type layers came in as pixels: the text isn't editable {n} livelli di testo sono stati importati come pixel: il testo non è modificabile +@msg 1 adjustment layer was not applied 1 livello di regolazione non è stato applicato +@msg {n} adjustment layers were not applied {n} livelli di regolazione non sono stati applicati +@msg 1 fill layer was not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels) 1 livello di riempimento non è stato disegnato (un riempimento con sfumatura o pattern, un colore che non può essere letto o una forma che non contiene pixel) +@msg {n} fill layers were not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels) {n} livelli di riempimento non sono stati disegnati (un riempimento con sfumatura o pattern, un colore che non può essere letto o una forma che non contiene pixel) +@msg the layer effects of 1 layer weren't drawn gli effetti di livello di 1 livello non sono stati disegnati +@msg the layer effects of {n} layers weren't drawn gli effetti di livello di {n} livelli non sono stati disegnati +@msg the vector masks of 1 layer weren't applied le maschere vettoriali di 1 livello non sono state applicate +@msg the vector masks of {n} layers weren't applied le maschere vettoriali di {n} livelli non sono state applicate +@msg the knockout of 1 layer wasn't applied la foratura di 1 livello non è stata applicata +@msg the knockout of {n} layers wasn't applied la foratura di {n} livelli non è stata applicata +@msg 1 layer was left out (hidden layers and the layers clipped to them) 1 livello è stato escluso (livelli nascosti e i livelli ritagliati su di essi) +@msg {n} layers were left out (hidden layers and the layers clipped to them) {n} livelli sono stati esclusi (livelli nascosti e i livelli ritagliati su di essi) +@msg 1 layer clipped to a fill layer that wasn't drawn was left out 1 livello ritagliato su un livello di riempimento non disegnato è stato escluso +@msg {n} layers clipped to fill layers that weren't drawn were left out {n} livelli ritagliati su livelli di riempimento non disegnati sono stati esclusi +@msg layers in blend modes VectorCraft doesn't have ({modes}) were merged with the layers below them i livelli in metodi di fusione che VectorCraft non ha ({modes}) sono stati uniti ai livelli sottostanti +@msg 1 layer in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed 1 livello in un metodo di fusione che VectorCraft non ha è stato importato come Normale: l’unione richiede più memoria di quella consentita +@msg {n} layers in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed {n} livelli in metodi di fusione che VectorCraft non ha sono stati importati come Normale: l’unione richiede più memoria di quella consentita +@msg 1 layer clipped to the layer below came in unclipped: the merge needs more memory than allowed 1 livello ritagliato sul livello sottostante è stato importato senza ritaglio: l’unione richiede più memoria di quella consentita +@msg {n} layers clipped to the layer below came in unclipped: the merge needs more memory than allowed {n} livelli ritagliati sul livello sottostante sono stati importati senza ritaglio: l’unione richiede più memoria di quella consentita +@msg hiddenLayers applies to a PSD file placed with layers: true hiddenLayers vale per un file PSD inserito con layers: true +@msg importSlices: a linked PSD file is placed as its flat image; give link: false to embed it with its slices importSlices: un file PSD collegato viene inserito come immagine appiattita; indica link: false per incorporarlo con le sue sezioni +@msg layers: a linked PSD file is placed as its flat image; leave link out or give link: false layers: un file PSD collegato viene inserito come immagine appiattita; ometti link o indica link: false +@msg the slices can't be read ({e}) and were left out le sezioni non possono essere lette ({e}) e sono state escluse +@msg 1 slice lies outside the canvas or has no size and was left out 1 sezione si trova fuori dall’area di lavoro o non ha dimensioni ed è stata esclusa +@msg {n} slices lie outside the canvas or have no size and were left out {n} sezioni si trovano fuori dall’area di lavoro o non hanno dimensioni e sono state escluse +@msg 1 slice would lie outside the canvas and was left out 1 sezione si troverebbe fuori dall’area di lavoro ed è stata esclusa +@msg {n} slices would lie outside the canvas and were left out {n} sezioni si troverebbero fuori dall’area di lavoro e sono state escluse +@msg the slices' descriptor holds too many values il descrittore delle sezioni contiene troppi valori +@msg the slices' descriptor has a version other than 16 il descrittore delle sezioni ha una versione diversa da 16 +@msg the slices are stored in version {v}, which isn't read le sezioni sono salvate nella versione {v}, che non viene letta +@msg the file has {count} slices, more than the {MAX_SLICES} read il file ha {count} sezioni, più delle {MAX_SLICES} lette +@msg the slices' descriptor has no list of slices il descrittore delle sezioni non ha un elenco di sezioni +@msg the slices' descriptor lists something other than a slice il descrittore delle sezioni elenca qualcosa che non è una sezione +@msg a slice in the slices' descriptor has no bounds una sezione nel descrittore delle sezioni non ha limiti +@msg a slice's bounds in the slices' descriptor aren't numbers i limiti di una sezione nel descrittore delle sezioni non sono numeri +@msg a text in the slices has more than the {MAX_TEXT} characters read un testo nelle sezioni ha più dei {MAX_TEXT} caratteri letti +@msg the slices' descriptor nests too deep il descrittore delle sezioni è annidato troppo in profondità +@msg the slices' descriptor has a reference of an unknown kind ({_1}) il descrittore delle sezioni ha un riferimento di un genere sconosciuto ({_1}) +@msg the slices' descriptor has a value of an unknown type ({_1}) il descrittore delle sezioni ha un valore di un tipo sconosciuto ({_1}) @msg the layers can't be read ({e}): the file opened as its merged image i livelli non possono essere letti ({e}): il file è stato aperto come immagine unita @msg {depth}-bit PSD files in this colour mode can't be read i file PSD a {depth} bit in questo metodo colore non possono essere letti @msg the PSD file is cut short il file PSD è troncato @@ -5892,6 +6012,25 @@ variable-list-end {0}, {1} {0} e {1} Preserve Embedded Profiles Mantieni profili incorporati Convert to Working Space Converti nello spazio di lavoro Preserve Numbers Mantieni valori numerici + Profile Mismatches: Mancata corrispondenza profili: + Ask When Opening Chiedi all'apertura + Ask When Pasting Chiedi quando si incolla + Missing Profiles: Profili mancanti: + Embedded Profile Mismatch Profilo incorporato non corrispondente + Missing Profile Profilo mancante + Paste Profile Mismatch Profilo non corrispondente nell'incollare + “{name}” is not tagged with a {model} profile. “{name}” non ha un profilo {model}. + “{name}” is tagged with the {model} profile “{profile}”, which is not the {model} working space “{working}”. “{name}” ha il profilo {model} “{profile}”, che non è lo spazio di lavoro {model} “{working}”. + Use the embedded profile Usa il profilo incorporato + Convert the colors to the working space Converti i colori nello spazio di lavoro + Discard the embedded profile Elimina il profilo incorporato + Leave as is Lascia invariato + Assign the working space Assegna lo spazio di lavoro + Assign profile: Assegna profilo: + Preserve the color numbers Mantieni i valori dei colori + Convert to keep the colors' appearance Converti per mantenere l'aspetto dei colori +@msg `{path}` goes with `{key}`: "assign" only `{path}` va solo con `{key}`: "assign" + The pasted colors come from a document whose {model} profile is “{from}”; this document's is “{to}”. I colori incollati provengono da un documento con profilo {model} “{from}”; quello di questo documento è “{to}”. Texture Texture Craquelure… Craquelé… Grain… Granulosità… @@ -7761,6 +7900,8 @@ breakText Glyphs Glifi # Path Precision Tools add-on: Tangent Circle. Tangent Circle… Cerchio tangente… Tangent Circle Cerchio tangente + Tangent Circle Tool Strumento Cerchio tangente + No tangent circle here Nessun cerchio tangente qui Circle: Cerchio: @msg `ids` names an object twice `ids` indica due volte lo stesso oggetto @msg select two or three paths or compound paths seleziona due o tre tracciati o tracciati composti @@ -7776,6 +7917,16 @@ breakText Glyphs Glifi @msg `circle` is past the last circle found ({found}) `circle` va oltre l’ultimo cerchio trovato ({found}) @msg object {value} is not a path or compound path l’oggetto {value} non è un tracciato né un tracciato composto @msg these shapes are too small to measure queste forme sono troppo piccole per essere misurate +# Path Precision Tools add-on: Add Bounding Rectangle and Add Bounding Circle. + Add Bounding Rectangle Aggiungi rettangolo di delimitazione + Add Bounding Circle Aggiungi cerchio di delimitazione + Add Bounding Rectangle… Aggiungi rettangolo di delimitazione… + Add Bounding Circle… Aggiungi cerchio di delimitazione… + One per Object Uno per oggetto +@msg nothing to enclose niente da racchiudere +@msg `offset` must be 0 or more `offset` deve essere 0 o maggiore +@msg the shape would have no size la forma non avrebbe dimensioni +@msg the shape would reach past the edge of the canvas la forma supererebbe il bordo dell'area di disegno # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Strumenti documento Save a Timestamped Copy Salva una copia con data e ora @@ -10054,6 +10205,39 @@ breakText Glyphs Glifi No objects are selected. Nessun oggetto selezionato. Open a document to mark its fold lines. Apri un documento per segnarne le linee di piega. Remove Fold Line Role Rimuovi tipo di linea +# Tool cards (General › Show Tool Cards): one sentence on what each tool does. + Shows a card with what a toolbar tool does and what its keys do instead of its tip; it needs Show Tool Tips. Mostra una scheda con ciò che fanno uno strumento della barra e i suoi tasti al posto della descrizione; richiede Mostra descrizioni comandi. + Selects whole objects and groups to move, resize or rotate them. Seleziona oggetti e gruppi interi per spostarli, ridimensionarli o ruotarli. + Selects anchor points and path segments to reshape a path. Seleziona punti di ancoraggio e segmenti di tracciato per modificare la forma di un tracciato. + Draws paths point by point, with straight segments and smooth curves. Disegna tracciati punto per punto, con segmenti diritti e curve morbide. + Draws smooth curves through the points you click. Disegna curve morbide che passano per i punti su cui fai clic. + Adds text at a point, or in a frame you drag. Aggiunge testo in un punto o in una cornice che trascini. + Draws rectangles and squares. Disegna rettangoli e quadrati. + Draws rectangles with rounded corners. Disegna rettangoli con angoli arrotondati. + Draws ellipses and circles. Disegna ellissi e cerchi. + Draws polygons with sides of equal length. Disegna poligoni con lati di uguale lunghezza. + Draws stars. Disegna stelle. + Turns objects around a reference point. Ruota gli oggetti attorno a un punto di riferimento. + Flips objects across an axis through a reference point. Riflette gli oggetti rispetto a un asse che passa per un punto di riferimento. + Resizes objects from a reference point. Ridimensiona gli oggetti a partire da un punto di riferimento. + Slants objects from a reference point. Inclina gli oggetti a partire da un punto di riferimento. + Moves the view of the document. Sposta la vista del documento. + Magnifies or reduces the view. Ingrandisce o riduce la vista. + Copies the color and other attributes of one object to the selection. Copia il colore e altri attributi di un oggetto nella selezione. + Sets the direction and length of a gradient. Imposta la direzione e la lunghezza di una sfumatura. + Creates, selects and resizes artboards. Crea, seleziona e ridimensiona le tavole da disegno. + Changes the width of a stroke along its length. Cambia lo spessore di una traccia lungo la sua lunghezza. + Bends art by dragging pins placed on it. Piega la grafica trascinando i perni posizionati su di essa. + Pushes the outlines of paths in the direction you drag. Spinge i contorni dei tracciati nella direzione in cui trascini. + Twists the outlines of paths into swirls. Torce i contorni dei tracciati in vortici. + Pulls the outlines of paths in toward the brush. Attira i contorni dei tracciati verso il pennello. + Pushes the outlines of paths out from the brush. Spinge i contorni dei tracciati verso l’esterno dal pennello. + Adds curved details along the outlines of paths. Aggiunge dettagli curvi lungo i contorni dei tracciati. + Adds spiky details along the outlines of paths. Aggiunge dettagli appuntiti lungo i contorni dei tracciati. + Adds wrinkles along the outlines of paths. Aggiunge grinze lungo i contorni dei tracciati. + Moves, copies and resizes objects on the perspective grid. Sposta, copia e ridimensiona gli oggetti sulla griglia prospettica. + Makes a series of steps between two or more objects. Crea una serie di passaggi tra due o più oggetti. + Places dimension lines that show measured lengths. Inserisce linee di quota che mostrano le lunghezze misurate. Tap Pressione breve Clear Hold Cancella pressione prolungata Hold Shortcuts Scorciatoie a pressione prolungata @@ -10084,7 +10268,18 @@ breakText Glyphs Glifi @msg A panel is not joined to the rest by a crease. Un pannello non è unito al resto da alcuna linea di cordonatura. @msg A fold line is on a non-printing layer. Una linea di piega si trova su un livello non stampabile. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Pannelli: {panels}, cerniere: {hinges}, errori: {errors}, avvisi: {warnings} + Paper Cutouts Ritagli di carta + Coral Layers Livelli corallo + Mint Layers Livelli menta + Midnight Layers Livelli di mezzanotte + Sunflower Sheet Foglio girasole + Rose Layers Livelli rosa + Monochrome Stack Pila monocromatica Dashed Arrow Freccia tratteggiata + Fine Stipple Puntinatura fine + Dense Stipple Puntinatura fitta + Soft Stipple Puntinatura morbida + Bold Stipple Puntinatura marcata Pressure Sensitive Sensibile alla pressione Flex Ribbon Nastro flessibile Pulse Stroke Tratto pulsante @@ -10100,3 +10295,7 @@ breakText Glyphs Glifi @msg Other blanks not shown: {count} Altri fustellati non mostrati: {count} @msg A joint does not close by {gap} pt. Una giunzione non si chiude di {gap} pt. @msg Two panels pass through each other. Due pannelli si attraversano. + +# #5804 native-picked raster editor (draft translations; native review welcome). + Edit Original with: Modifica originale con: +file-filter Applications Applicazioni diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 3e0ae1b765..734ee90afc 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -95,6 +95,15 @@ digits Malayalam マラヤーラム数字 YakumonoZenkaku 約物全角 Kinsoku Set 禁則処理 Kinsoku Shori Type 禁則調整方式 + Kinsoku Shori Settings… 禁則処理設定… + Kinsoku Shori Settings 禁則処理設定 + Kinsoku Sets 禁則処理セット + Kinsoku Set Base 禁則処理セットの基準 + Based on: 基準: + Cannot Start Line 行頭禁則文字 + Cannot End Line 行末禁則文字 + Hanging Punctuation ぶら下がり文字 + Inseparable Characters 分離禁止文字 Push In First 追い込み優先 Push Out First 追い出し優先 Push Out Only 追い出しのみ @@ -618,6 +627,15 @@ digits Malayalam マラヤーラム数字 Shading Color 陰影のカラー Black Overprint ブラックオーバープリント Draw Hidden Faces 隠れた面を描画 + Map Art… アートをマップ… + Map Art アートをマップ + First Surface 最初の面 + Previous Surface 前の面 + Next Surface 次の面 + Last Surface 最後の面 + Scale to Fit サイズに合わせる + Shade Artwork アートワークに陰影をつける + Invisible Geometry 不可視のジオメトリ Revolve… 回転体… Inflate… 膨張… Materials… マテリアル… @@ -726,6 +744,8 @@ digits Malayalam マラヤーラム数字 Hide Text Threads テキストのスレッドを隠す Hide Gradient Annotator グラデーションガイドを隠す Hide Corner Widget コーナーウィジェットを隠す + Hide Shape Widgets シェイプウィジェットを隠す + Show Shape Widgets シェイプウィジェットを表示 Guides ガイド Hide Guides ガイドを隠す Lock Guides ガイドをロック @@ -835,6 +855,9 @@ digits Malayalam マラヤーラム数字 Box Channel ボックスのチャンネル Color box カラーボックス Color Wheel Options カラーホイールオプション + Show Harmony ハーモニーを表示 + Harmony Rule ハーモニールール + Harmony color ハーモニーカラー CSS Properties CSS プロパティ Document Info ドキュメント情報 Flattener Preview 分割・統合プレビュー @@ -1366,6 +1389,9 @@ antiAlias Sharp シャープ Choose… 選択… Circle 円 Circle Tool 円ツール + Curvature Circle Tool 曲率円ツール + Cusp 尖点 + Straight segment 直線セグメント Circle too large 円が大きすぎます Clear All Tabs すべてのタブを消去 Above Text テキストの上 @@ -1529,10 +1555,25 @@ antiAlias Sharp シャープ Cut Path at Selected Anchor Points 選択したアンカーポイントでパスをカット Dim Images to: 画像の濃さ: Duplicate Selection 選択項目を複製 + PSD Import Options PSD 読み込みオプション + Place PSD PSD を配置 + Convert Layers to Objects レイヤーをオブジェクトに変換 + Import Hidden Layers 非表示レイヤーを読み込む + Flatten Layers to a Single Image レイヤーを 1 つの画像に統合 + Import Slices スライスを読み込む DXF Import Options DXF 読み込みオプション DXF Info DXF 情報 DXF Options DXF オプション DXF Options Dialog DXF オプションダイアログ + HP-GL Options HP-GL オプション + HP-GL Options Dialog HP-GL オプションダイアログ + Curve Tolerance: カーブの許容値: + Origin: 原点: + Pens: ペン: + One Pen per Color カラーごとに 1 本のペン + Pen Table ペンテーブル + Draw the Nearest Path Next 最も近いパスを次に描画 + Draw Inner Paths First 内側のパスを先に描画 Darken 比較 (暗) Darkness 濃さ Dashed 破線 @@ -2581,6 +2622,7 @@ antiAlias Sharp シャープ Pressure 筆圧 Tilt 傾き Bearing 方位 + Stylus Wheel スタイラスホイール Shape: 形状: Bristle Length: 毛の長さ: Bristle Density: 毛の密度: @@ -2611,6 +2653,9 @@ antiAlias Sharp シャープ embedding for preview and print プレビューと印刷用に埋め込み可 embedding allowed 埋め込み可 {file}; {embedding} {file}、{embedding} + unknown type 不明な種類 + {type}; {uses} {type}、{uses} +@plural {n} use|{n} uses 使用 {n} 回 substituted: shown in {family} {style} ({detail}) 代替: {family} {style} で表示 ({detail}) missing: shown in {family} {style} 見つかりません: {family} {style} で表示 missing 見つかりません @@ -2814,6 +2859,8 @@ antiAlias Sharp シャープ Overprint and Transparency Flattener Options オーバープリントと透明の分割・統合オプション Custom… カスタム… Custom Transparency Flattener Options カスタムの透明の分割・統合オプション + The PDF preset keeps the flattener preset but not the Custom… settings. PDF プリセットには分割・統合プリセットが保存されますが、「カスタム…」の設定は保存されません。 + PDF 1.3 files clip rasterized areas to their regions, and Overprint sets whether overprints are kept. PDF 1.3 のファイルではラスタライズされた領域がその範囲でクリップされ、オーバープリントを保持するかどうかは「オーバープリント」で決まります。 EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS にはアルファ透明がなく、オーバープリントを保持するかどうかは「オーバープリント」で決まります。 Overprint: オーバープリント: Overprints: オーバープリント: @@ -3192,6 +3239,9 @@ mark-style Japanese 日本式 Reload Arrowheads 矢印を再読み込み Reset the rows to the artwork's colors 行をアートワークのカラーにリセット Color Theme Picker カラーテーマピッカー + Undo Changes 変更を取り消し + Redo Changes 変更をやり直し +@msg Recolor Artwork is not open 「アートワークを再配色」が開いていません Click or drag across the art to pick its colors; Shift adds more アートワークをクリックまたはドラッグしてカラーを取得します。Shift キーで追加します Prominent Colors 主要カラー Save All Colors すべてのカラーを保存 @@ -3242,6 +3292,7 @@ mark-style Japanese 日本式 A live rectangle's properties show one Corner Radius field for all four corners; off, each corner has its own field. ライブ長方形のプロパティで、4 つの角に共通の角丸の半径フィールドを 1 つ表示します。オフのときは角ごとにフィールドを表示します。 What edits in the Transform panel transform: the object, its pattern tiles or both; Default follows Transform Pattern Tiles. 変形パネルでの編集が変形する対象で、オブジェクト、パターンタイル、またはその両方です。デフォルトはパターンタイルを変形に従います。 With one symbol instance selected, the Transform panel uses the symbol's registration point as its reference point. シンボルインスタンスを 1 つ選択したとき、変形パネルはシンボルの基準点を基準点として使います。 + Drawing a rectangle, ellipse, polygon, star or line opens the Transform panel if it is closed. 長方形、楕円形、多角形、スター、直線を描画すると、閉じている変形パネルが開きます。 Darkens the canvas outside the artboards while the Artboard tool is active. アートボードツールを使っている間、アートボードの外側のカンバスを暗く表示します。 With Fade Region Outside Artboard on, the area outside the artboards stays dark while you drag with the Artboard tool. アートボードの外側を暗く表示がオンのとき、アートボードツールでドラッグしている間もアートボードの外側を暗いままにします。 How near, in pixels, the pointer must be to an object, anchor or handle for a click to select it. クリックでオブジェクト、アンカーポイント、ハンドルを選択できる、ポインターからの距離(ピクセル)です。 @@ -3383,6 +3434,7 @@ mark-style Japanese 日本式 Save Document Preset ドキュメントプリセットを保存 Preset {number} プリセット {number} Save Preset… 保存… + Save Summary… サマリーを保存… Save Print Preset プリントプリセットを保存 Save Recovery Data 復帰用データを保存 Save Save for Web Preset Web 用に保存プリセットを保存 @@ -3547,6 +3599,7 @@ mark-style Japanese 日本式 Show List View リスト表示 Show Note メモを表示 Show Options オプションを表示 + Show on Shape Creation シェイプ作成時に表示 Show Recent Colors 最近使用したカラーを表示 Toggle RGB Percent RGB のパーセント表示を切り替え Show Original Path 元のパスを表示 @@ -3568,6 +3621,7 @@ mark-style Japanese 日本式 Show Thumbnails サムネールを表示 Show Tile Edge タイルの境界線を表示 Show Tints/Shades ティント/シェードを表示 + Show Tool Cards ツールカードを表示 Show Tool Tips ツールヒントを表示 Show Vivid/Muted ビビッド/ソフトを表示 Show Warm/Cool 暖色/寒色を表示 @@ -3617,6 +3671,8 @@ mark-style Japanese 日本式 Outlines アウトライン Outlines with Source Image アウトライン(元画像付き) Source Image 元画像 + Split View 分割表示 + Divider 境界線 Press and hold to view the source image 押している間、元画像を表示 Image Trace View 画像トレースの表示 Snap Options スナップオプション @@ -3870,6 +3926,8 @@ mark-style Japanese 日本式 Unembed 埋め込みを解除 Unembed… 埋め込みを解除… Ungroup Color Group カラーグループを解除 + Color Group Options カラーグループオプション + Color Group Options… カラーグループオプション… Uniform 縦横比を固定 Unite 合体 Units 単位 @@ -4144,6 +4202,17 @@ gradient-kind Radial 円形 Largest: 最大: Direction: 方向: Symbolism Tools Options シンボルツールオプション + Tool: ツール: + Symbol Set Density シンボルセットの密度 + Symbol Sprayer Options シンボルスプレーのオプション + Scrunch: スクランチ: + Spin: スピン: + Screen: スクリーン: + Stain: ステイン: + Symbol Sizer Options シンボルリサイザーのオプション + Proportional Resizing 縦横比を保持してサイズ変更 + Resizing Affects Density サイズ変更で密度を変更 + Show Brush Size and Intensity ブラシサイズと強度を表示 Symbol Set Density: シンボルセットの密度: Flattener presets 分割・統合プリセット file-filter All readable files 読み込めるすべてのファイル @@ -5006,6 +5075,11 @@ variable-list-end {0}, {1} {0}、{1} @msg no anchor points selected アンカーポイントが選択されていません @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 the path is straight there, so no circle matches its curvature パスはその位置で直線のため、曲率に合う円はありません +@msg the path has a cusp there, so it has no single curvature パスはその位置に尖点があるため、曲率が 1 つに定まりません +@msg the path has a corner there, so it has no single curvature パスはその位置にコーナーがあるため、曲率が 1 つに定まりません +@msg a guide has no curvature circle ガイドには曲率円がありません +@msg the circle that matches the path there would reach past the canvas その位置でパスに合う円はキャンバスからはみ出します @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 先に分離モードを終了してください @@ -5120,6 +5194,7 @@ variable-list-end {0}, {1} {0}、{1} @msg select a stroke with a variable width 可変幅の線を選択してください @msg the selected stroke's profile is already listed as {_1} 選択した線のプロファイルは、すでに {_1} として登録されています @msg a graphic style named `{to}` already exists `{to}` という名前のグラフィックスタイルはすでに存在します +@msg a swatch or color group named `{name}` already exists `{name}` という名前のスウォッチまたはカラーグループはすでに存在します @msg a key object sits on that point そのポイントにはキーオブジェクトがあります @msg no graphic style `{name}` グラフィックスタイル `{name}` が見つかりません @msg node {_1} is not text ノード {_1} はテキストではありません @@ -5443,6 +5518,7 @@ variable-list-end {0}, {1} {0}、{1} @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 つだけを指定してください +@msg give only one of `index`, `indices` and `t` `index`、`indices`、`t` のうち 1 つだけを指定してください @msg column must be true or a number from 1 column には true または 1 以上の数値を指定してください @msg unknown panel `{raw}` `{raw}` は不明なパネルです @msg `{panel}` has no display sizes to cycle `{panel}` には切り替える表示サイズがありません @@ -5459,6 +5535,7 @@ variable-list-end {0}, {1} {0}、{1} @msg no file manager here この環境にはファイルマネージャーがありません @msg no revert command 「保存済みの状態に戻す」コマンドがありません @msg the Save PDF dialog didn't open PDF 保存ダイアログが開きませんでした +@msg the Save PDF dialog is not open PDF 保存ダイアログが開いていません @msg the document has never been saved ドキュメントはまだ一度も保存されていません @msg the export returned unreadable data 書き出し処理から読み取れないデータが返されました @msg {status} ({e}) {status} ({e}) @@ -5913,6 +5990,49 @@ liquify-list-end {0}, {1} {0}、{1} @msg the PSD file's layer groups are nested too deeply PSD ファイルのレイヤーグループの入れ子が深すぎます @msg a layer of the PSD file is too large to read PSD ファイルのレイヤーが大きすぎて読み込めません @msg the PSD file's layers take more memory to read than allowed PSD ファイルのレイヤーの読み込みに許容量を超えるメモリーが必要です +@msg the file is no longer loaded ファイルはもう読み込まれていません +@msg the layers can't be read ({e}): the file was placed as its merged image レイヤーを読み込めません({e}):ファイルは統合画像として配置されました +@msg 1 type layer came in as pixels: the text isn't editable テキストレイヤー 1 個がピクセルとして読み込まれました:テキストは編集できません +@msg {n} type layers came in as pixels: the text isn't editable テキストレイヤー {n} 個がピクセルとして読み込まれました:テキストは編集できません +@msg 1 adjustment layer was not applied 調整レイヤー 1 個は適用されませんでした +@msg {n} adjustment layers were not applied 調整レイヤー {n} 個は適用されませんでした +@msg 1 fill layer was not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels) 塗りつぶしレイヤー 1 個は描画されませんでした(グラデーションまたはパターンの塗り、読み込めないカラー、またはピクセルを持たないシェイプ) +@msg {n} fill layers were not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels) 塗りつぶしレイヤー {n} 個は描画されませんでした(グラデーションまたはパターンの塗り、読み込めないカラー、またはピクセルを持たないシェイプ) +@msg the layer effects of 1 layer weren't drawn レイヤー 1 個のレイヤー効果は描画されませんでした +@msg the layer effects of {n} layers weren't drawn レイヤー {n} 個のレイヤー効果は描画されませんでした +@msg the vector masks of 1 layer weren't applied レイヤー 1 個のベクトルマスクは適用されませんでした +@msg the vector masks of {n} layers weren't applied レイヤー {n} 個のベクトルマスクは適用されませんでした +@msg the knockout of 1 layer wasn't applied レイヤー 1 個のノックアウトは適用されませんでした +@msg the knockout of {n} layers wasn't applied レイヤー {n} 個のノックアウトは適用されませんでした +@msg 1 layer was left out (hidden layers and the layers clipped to them) レイヤー 1 個を除外しました(非表示のレイヤーと、それにクリップされたレイヤー) +@msg {n} layers were left out (hidden layers and the layers clipped to them) レイヤー {n} 個を除外しました(非表示のレイヤーと、それにクリップされたレイヤー) +@msg 1 layer clipped to a fill layer that wasn't drawn was left out 描画されなかった塗りつぶしレイヤーにクリップされたレイヤー 1 個を除外しました +@msg {n} layers clipped to fill layers that weren't drawn were left out 描画されなかった塗りつぶしレイヤーにクリップされたレイヤー {n} 個を除外しました +@msg layers in blend modes VectorCraft doesn't have ({modes}) were merged with the layers below them VectorCraft にない描画モード({modes})のレイヤーは下のレイヤーと統合されました +@msg 1 layer in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed VectorCraft にない描画モードのレイヤー 1 個は通常として読み込まれました:統合には許容量を超えるメモリが必要です +@msg {n} layers in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed VectorCraft にない描画モードのレイヤー {n} 個は通常として読み込まれました:統合には許容量を超えるメモリが必要です +@msg 1 layer clipped to the layer below came in unclipped: the merge needs more memory than allowed 下のレイヤーにクリップされたレイヤー 1 個はクリップなしで読み込まれました:統合には許容量を超えるメモリが必要です +@msg {n} layers clipped to the layer below came in unclipped: the merge needs more memory than allowed 下のレイヤーにクリップされたレイヤー {n} 個はクリップなしで読み込まれました:統合には許容量を超えるメモリが必要です +@msg hiddenLayers applies to a PSD file placed with layers: true hiddenLayers は layers: true で配置する PSD ファイルに適用されます +@msg importSlices: a linked PSD file is placed as its flat image; give link: false to embed it with its slices importSlices:リンクした PSD ファイルはフラットな画像として配置されます。スライスと一緒に埋め込むには link: false を指定してください +@msg layers: a linked PSD file is placed as its flat image; leave link out or give link: false layers:リンクした PSD ファイルはフラットな画像として配置されます。link を省略するか link: false を指定してください +@msg the slices can't be read ({e}) and were left out スライスを読み込めないため({e})、除外しました +@msg 1 slice lies outside the canvas or has no size and was left out スライス 1 個がカンバスの外にあるかサイズがないため、除外しました +@msg {n} slices lie outside the canvas or have no size and were left out スライス {n} 個がカンバスの外にあるかサイズがないため、除外しました +@msg 1 slice would lie outside the canvas and was left out スライス 1 個がカンバスの外に出るため、除外しました +@msg {n} slices would lie outside the canvas and were left out スライス {n} 個がカンバスの外に出るため、除外しました +@msg the slices' descriptor holds too many values スライスの記述子に含まれる値が多すぎます +@msg the slices' descriptor has a version other than 16 スライスの記述子のバージョンが 16 ではありません +@msg the slices are stored in version {v}, which isn't read スライスは読み込まないバージョン {v} で保存されています +@msg the file has {count} slices, more than the {MAX_SLICES} read ファイルのスライスは {count} 個で、読み込む {MAX_SLICES} 個を超えています +@msg the slices' descriptor has no list of slices スライスの記述子にスライスのリストがありません +@msg the slices' descriptor lists something other than a slice スライスの記述子にスライス以外のものがあります +@msg a slice in the slices' descriptor has no bounds スライスの記述子のスライスに境界がありません +@msg a slice's bounds in the slices' descriptor aren't numbers スライスの記述子のスライスの境界が数値ではありません +@msg a text in the slices has more than the {MAX_TEXT} characters read スライスのテキストが読み込む {MAX_TEXT} 文字を超えています +@msg the slices' descriptor nests too deep スライスの記述子の入れ子が深すぎます +@msg the slices' descriptor has a reference of an unknown kind ({_1}) スライスの記述子に不明な種類の参照があります({_1}) +@msg the slices' descriptor has a value of an unknown type ({_1}) スライスの記述子に不明な型の値があります({_1}) @msg the layers can't be read ({e}): the file opened as its merged image レイヤーを読み込めません({e}):ファイルは統合画像として開かれました @msg {depth}-bit PSD files in this colour mode can't be read このカラーモードの {depth} bit PSD ファイルは読み込めません @msg the PSD file is cut short PSD ファイルが途中で切れています @@ -5940,6 +6060,25 @@ liquify-list-end {0}, {1} {0}、{1} Preserve Embedded Profiles 埋め込まれたプロファイルを保持 Convert to Working Space 作業用スペースに変換 Preserve Numbers カラー値を保持 + Profile Mismatches: プロファイルの不一致: + Ask When Opening 開くときに確認 + Ask When Pasting ペーストするときに確認 + Missing Profiles: プロファイルの欠落: + Embedded Profile Mismatch 埋め込まれたプロファイルの不一致 + Missing Profile プロファイルの欠落 + Paste Profile Mismatch ペースト時のプロファイルの不一致 + “{name}” is not tagged with a {model} profile. 「{name}」には {model} プロファイルがありません。 + “{name}” is tagged with the {model} profile “{profile}”, which is not the {model} working space “{working}”. 「{name}」の {model} プロファイルは「{profile}」で、{model} 作業用スペース「{working}」ではありません。 + Use the embedded profile 埋め込まれたプロファイルを使用 + Convert the colors to the working space カラーを作業用スペースに変換 + Discard the embedded profile 埋め込まれたプロファイルを破棄 + Leave as is そのままにする + Assign the working space 作業用スペースを割り当て + Assign profile: プロファイルを割り当て: + Preserve the color numbers カラーの数値を保持 + Convert to keep the colors' appearance カラーの見た目を保つように変換 +@msg `{path}` goes with `{key}`: "assign" only `{path}` は `{key}`: "assign" のときだけ指定してください + The pasted colors come from a document whose {model} profile is “{from}”; this document's is “{to}”. ペーストしたカラーは {model} プロファイルが「{from}」のドキュメントのものです。このドキュメントのプロファイルは「{to}」です。 Texture テクスチャ Craquelure… クラッキング… Grain… 粒状… @@ -9651,6 +9790,8 @@ breakText Glyphs 字形 # Path Precision Tools add-on: Tangent Circle. Tangent Circle… 接円… Tangent Circle 接円 + Tangent Circle Tool 接円ツール + No tangent circle here ここに接円はありません Circle: 円: @msg `ids` names an object twice `ids` に同じオブジェクトが 2 回指定されています @msg select two or three paths or compound paths パスまたは複合パスを 2 つか 3 つ選択してください @@ -9666,6 +9807,16 @@ breakText Glyphs 字形 @msg `circle` is past the last circle found ({found}) `circle` が見つかった最後の円を超えています({found}) @msg object {value} is not a path or compound path オブジェクト {value} はパスでも複合パスでもありません @msg these shapes are too small to measure これらのシェイプは小さすぎて測定できません +# Path Precision Tools add-on: Add Bounding Rectangle and Add Bounding Circle. + Add Bounding Rectangle 外接長方形を追加 + Add Bounding Circle 外接円を追加 + Add Bounding Rectangle… 外接長方形を追加… + Add Bounding Circle… 外接円を追加… + One per Object オブジェクトごとに 1 つ +@msg nothing to enclose 囲むものがありません +@msg `offset` must be 0 or more `offset` には 0 以上を指定してください +@msg the shape would have no size 図形にサイズがありません +@msg the shape would reach past the edge of the canvas 図形がカンバスの端を超えます # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools ドキュメントツール Save a Timestamped Copy 日時付きのコピーを保存 @@ -10118,6 +10269,39 @@ breakText Glyphs 字形 No objects are selected. オブジェクトが選択されていません。 Open a document to mark its fold lines. ドキュメントを開くと折り線を設定できます。 Remove Fold Line Role 線種を解除 +# Tool cards (General › Show Tool Cards): one sentence on what each tool does. + Shows a card with what a toolbar tool does and what its keys do instead of its tip; it needs Show Tool Tips. ツールバーのツールとそのキーの働きを、ヒントの代わりにカードで表示。ツールヒントを表示がオンのときに使用 + Selects whole objects and groups to move, resize or rotate them. オブジェクトやグループ全体を選択して、移動、サイズ変更、回転を行います。 + Selects anchor points and path segments to reshape a path. アンカーポイントとパスのセグメントを選択して、パスの形を変えます。 + Draws paths point by point, with straight segments and smooth curves. 直線のセグメントと滑らかな曲線で、パスを 1 点ずつ描きます。 + Draws smooth curves through the points you click. クリックした点を通る滑らかな曲線を描きます。 + Adds text at a point, or in a frame you drag. クリックした位置、またはドラッグした枠の中にテキストを追加します。 + Draws rectangles and squares. 長方形と正方形を描きます。 + Draws rectangles with rounded corners. 角の丸い長方形を描きます。 + Draws ellipses and circles. 楕円と円を描きます。 + Draws polygons with sides of equal length. 辺の長さが等しい多角形を描きます。 + Draws stars. スターを描きます。 + Turns objects around a reference point. 基準点を中心にオブジェクトを回転します。 + Flips objects across an axis through a reference point. 基準点を通る軸でオブジェクトを反転します。 + Resizes objects from a reference point. 基準点からオブジェクトのサイズを変更します。 + Slants objects from a reference point. 基準点からオブジェクトを傾けます。 + Moves the view of the document. ドキュメントの表示を移動します。 + Magnifies or reduces the view. 表示を拡大または縮小します。 + Copies the color and other attributes of one object to the selection. あるオブジェクトのカラーなどの属性を選択範囲にコピーします。 + Sets the direction and length of a gradient. グラデーションの方向と長さを設定します。 + Creates, selects and resizes artboards. アートボードを作成、選択、サイズ変更します。 + Changes the width of a stroke along its length. 線の幅を長さに沿って変えます。 + Bends art by dragging pins placed on it. アートに置いたピンをドラッグして曲げます。 + Pushes the outlines of paths in the direction you drag. パスの輪郭をドラッグした方向に押し出します。 + Twists the outlines of paths into swirls. パスの輪郭を渦巻き状にねじります。 + Pulls the outlines of paths in toward the brush. パスの輪郭をブラシの方へ引き寄せます。 + Pushes the outlines of paths out from the brush. パスの輪郭をブラシから外側へ押し出します。 + Adds curved details along the outlines of paths. パスの輪郭に沿って弧状の細部を加えます。 + Adds spiky details along the outlines of paths. パスの輪郭に沿ってとがった細部を加えます。 + Adds wrinkles along the outlines of paths. パスの輪郭に沿ってしわを加えます。 + Moves, copies and resizes objects on the perspective grid. 遠近グリッド上でオブジェクトを移動、コピー、サイズ変更します。 + Makes a series of steps between two or more objects. 2 つ以上のオブジェクトの間に一連のステップを作ります。 + Places dimension lines that show measured lengths. 測った長さを示す寸法線を配置します。 Tap 短押し Clear Hold 長押しを消去 Hold Shortcuts 長押しショートカット @@ -10148,7 +10332,18 @@ breakText Glyphs 字形 @msg A panel is not joined to the rest by a crease. パネルがどの筋入れ線でも他とつながっていません。 @msg A fold line is on a non-printing layer. 折り線が印刷しないレイヤーにあります。 @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} パネル: {panels}、ヒンジ: {hinges}、エラー: {errors}、警告: {warnings} + Paper Cutouts 切り絵 + Coral Layers コーラルのレイヤー + Mint Layers ミントのレイヤー + Midnight Layers 真夜中のレイヤー + Sunflower Sheet ひまわりのシート + Rose Layers ローズのレイヤー + Monochrome Stack モノクロの重なり Dashed Arrow 破線矢印 + Fine Stipple 細かい点描 + Dense Stipple 密な点描 + Soft Stipple 柔らかい点描 + Bold Stipple 太い点描 Pressure Sensitive 筆圧対応 Flex Ribbon しなやかなリボン Pulse Stroke 脈打つ線 @@ -10164,3 +10359,7 @@ breakText Glyphs 字形 @msg Other blanks not shown: {count} 表示されていない他の展開図: {count} @msg A joint does not close by {gap} pt. 継ぎ目が {gap} pt 閉じていません。 @msg Two panels pass through each other. 2 つのパネルが互いを貫通しています。 + +# #5804 native-picked raster editor (draft translations; native review welcome). + Edit Original with: 元のファイルを編集するアプリ: +file-filter Applications アプリケーション diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index ed6ccfb103..60b4151e58 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -2692,6 +2692,15 @@ Shading Color დაჩრდილვის ფერი Black Overprint ზედდაბეჭდილი შავი Draw Hidden Faces დამალული წახნაგების დახატვა + Map Art… ნახატის მიბმა… + Map Art ნახატის მიბმა + First Surface პირველი ზედაპირი + Previous Surface წინა ზედაპირი + Next Surface შემდეგი ზედაპირი + Last Surface ბოლო ზედაპირი + Scale to Fit მასშტაბირება მორგებით + Shade Artwork ნახატის დაჩრდილვა + Invisible Geometry უხილავი გეომეტრია Revolve… ბრუნვა… Inflate… გაბერვა… Materials… მასალები… @@ -2807,6 +2816,8 @@ Hide Gradient Annotator გრადიენტის მაჩვენებლის დამალვა Show Gradient Annotator გრადიენტის მაჩვენებლის ჩვენება Hide Corner Widget კუთხის ვიჯეტის დამალვა + Hide Shape Widgets ფიგურის ვიჯეტების დამალვა + Show Shape Widgets ფიგურის ვიჯეტების ჩვენება Show Corner Widget კუთხის ვიჯეტის ჩვენება Guides დამხმარე ხაზები Hide Guides დამხმარე ხაზების დამალვა @@ -2916,6 +2927,9 @@ Box Channel კვადრატის არხი Color box ფერის კვადრატი Color Wheel Options ფერთა წრის პარამეტრები + Show Harmony ჰარმონიის ჩვენება + Harmony Rule ჰარმონიის წესი + Harmony color ჰარმონიის ფერი CSS Properties CSS თვისებები Document Info დოკუმენტის ინფორმაცია Flattener Preview გაბრტყელების წინასწარი ნახვა @@ -3147,6 +3161,25 @@ Preserve Embedded Profiles ჩაშენებული პროფილების შენარჩუნება Convert to Working Space სამუშაო სივრცეში გადაყვანა Preserve Numbers რიცხვების შენარჩუნება + Profile Mismatches: პროფილების შეუსაბამობა: + Ask When Opening გახსნისას კითხვა + Ask When Pasting ჩასმისას კითხვა + Missing Profiles: დაკარგული პროფილები: + Embedded Profile Mismatch ჩაშენებული პროფილის შეუსაბამობა + Missing Profile პროფილი არ არის + Paste Profile Mismatch პროფილის შეუსაბამობა ჩასმისას + “{name}” is not tagged with a {model} profile. „{name}“-ს არ აქვს {model} პროფილი. + “{name}” is tagged with the {model} profile “{profile}”, which is not the {model} working space “{working}”. „{name}“-ს აქვს {model} პროფილი „{profile}“, რომელიც არ არის {model} სამუშაო სივრცე „{working}“. + Use the embedded profile ჩაშენებული პროფილის გამოყენება + Convert the colors to the working space ფერების სამუშაო სივრცეში გადაყვანა + Discard the embedded profile ჩაშენებული პროფილის უგულებელყოფა + Leave as is უცვლელად დატოვება + Assign the working space სამუშაო სივრცის მინიჭება + Assign profile: პროფილის მინიჭება: + Preserve the color numbers ფერების რიცხვების შენარჩუნება + Convert to keep the colors' appearance გადაყვანა ფერების იერსახის შესანარჩუნებლად +@msg `{path}` goes with `{key}`: "assign" only `{path}` გამოიყენება მხოლოდ `{key}`: "assign"-თან + The pasted colors come from a document whose {model} profile is “{from}”; this document's is “{to}”. ჩასმული ფერები მოდის დოკუმენტიდან, რომლის {model} პროფილია „{from}“; ამ დოკუმენტის პროფილია „{to}“. CMYK CMYK Texture ტექსტურა Craquelure… კრაკელიური… @@ -3228,6 +3261,15 @@ lighting Light სინათლე Document Raster Effects Settings Dialog დოკუმენტის რასტრული ეფექტების პარამეტრების დიალოგი Drop Shadow ჩრდილი DXF Options Dialog DXF პარამეტრების დიალოგი + HP-GL Options HP-GL-ის პარამეტრები + HP-GL Options Dialog HP-GL პარამეტრების დიალოგი + Curve Tolerance: მრუდების დაშვება: + Origin: სათავე: + Pens: კალმები: + One Pen per Color თითო კალამი თითო ფერზე + Pen Table კალმების ცხრილი + Draw the Nearest Path Next შემდეგ უახლოესი ტრაექტორიის დახატვა + Draw Inner Paths First ჯერ შიდა ტრაექტორიების დახატვა Edit Toolbar ხელსაწყოთა ზოლის რედაქტირება Edit Views ხედების რედაქტირება Effect… ეფექტი… @@ -3762,6 +3804,7 @@ digits Malayalam მალაიალამური Roman Baseline რომაული საბაზისო ხაზი Select a text object to edit its character attributes. სიმბოლოების ატრიბუტების რედაქტირებისთვის მონიშნეთ ტექსტური ობიექტი. Show Options პარამეტრების ჩვენება + Show on Shape Creation ჩვენება ფიგურის შექმნისას Show Recent Colors ბოლოდროინდელი ფერების ჩვენება Toggle RGB Percent RGB-ის პროცენტებში ჩვენების გადართვა Small Caps პატარა მთავრული @@ -4028,6 +4071,8 @@ digits Malayalam მალაიალამური Snap Curves To Lines მრუდების ხაზებზე მიბმა Tracing Result with Outlines ვექტორიზაციის შედეგი კონტურებით Source Image საწყისი გამოსახულება + Split View გაყოფილი ხედი + Divider გამყოფი Threshold ზღვარი Trace ვექტორიზაცია Trace the image with the Default preset გამოსახულების ვექტორიზაცია ნაგულისხმევი პრესეტით @@ -4143,6 +4188,15 @@ digits Malayalam მალაიალამური YakumonoZenkaku YakumonoZenkaku Kinsoku Set Kinsoku-ის ნაკრები Kinsoku Shori Type Kinsoku Shori-ის ტიპი + Kinsoku Shori Settings… Kinsoku Shori-ის პარამეტრები… + Kinsoku Shori Settings Kinsoku Shori-ის პარამეტრები + Kinsoku Sets Kinsoku-ის ნაკრებები + Kinsoku Set Base Kinsoku-ის ნაკრების საფუძველი + Based on: საფუძველი: + Cannot Start Line ვერ დაიწყებს ხაზს + Cannot End Line ვერ დაასრულებს ხაზს + Hanging Punctuation დაკიდებული პუნქტუაცია + Inseparable Characters განუყოფელი სიმბოლოები Push In First ჯერ შეტანა Push Out First ჯერ გატანა Push Out Only მხოლოდ გატანა @@ -4690,6 +4744,7 @@ digits Malayalam მალაიალამური Save As Preset… შენახვა წინასწარ პარამეტრად… Save Changes ცვლილებების შენახვა Save Preset… პრესეტის შენახვა… + Save Summary… შეჯამების შენახვა… Vectors ვექტორები A saved copy of the selected preset მონიშნული პრესეტის შენახული ასლი Built-in presets don't change: New makes a copy you can edit. ჩაშენებული პრესეტები არ იცვლება: „ახალი“ ქმნის რედაქტირებად ასლს. @@ -4919,6 +4974,8 @@ digits Malayalam მალაიალამური Overprint and Transparency Flattener Options ზედდაბეჭდვისა და გამჭვირვალობის გაბრტყელების პარამეტრები Custom… მორგებული… Custom Transparency Flattener Options გამჭვირვალობის გაბრტყელების მორგებული პარამეტრები + The PDF preset keeps the flattener preset but not the Custom… settings. PDF პრესეტი ინახავს გაბრტყელების პრესეტს, მაგრამ არა მორგებული… პარამეტრებს. + PDF 1.3 files clip rasterized areas to their regions, and Overprint sets whether overprints are kept. PDF 1.3 ფაილები რასტრირებულ უბნებს მათ არეებზე ჭრის, ხოლო ზედდაბეჭდვა განსაზღვრავს, შენარჩუნდება თუ არა ზედდაბეჭდვები. EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS-ს არ აქვს ალფა-გამჭვირვალობა, ხოლო ზედდაბეჭდვები განსაზღვრავს, შენარჩუნდება თუ არა ზედდაბეჭდვები. Place the pages with the placement again გვერდების ხელახლა განთავსება განთავსების მიხედვით Placement: განთავსება: @@ -5008,6 +5065,9 @@ digits Malayalam მალაიალამური Recolor this row ამ სტრიქონის ხელახლა შეფერადება Reset the rows to the artwork's colors სტრიქონებისთვის ნახატის ფერების დაბრუნება Color Theme Picker ფერთა თემის ამრჩევი + Undo Changes ცვლილებების გაუქმება + Redo Changes ცვლილებების ხელახლა შესრულება +@msg Recolor Artwork is not open „ნახატის ხელახლა შეფერადება“ გახსნილი არ არის Click or drag across the art to pick its colors; Shift adds more დაწკაპეთ ან გადაატარეთ ნახატზე მისი ფერების ასაღებად; Shift ამატებს კიდევ Prominent Colors გამოკვეთილი ფერები Save All Colors ყველა ფერის შენახვა @@ -5220,6 +5280,17 @@ antiAlias Sharp მკვეთრი Swatch Name: ფერის ნიმუშის სახელი: Diameter: დიამეტრი: Symbolism Tools Options სიმბოლოების ხელსაწყოების პარამეტრები + Tool: ხელსაწყო: + Symbol Set Density სიმბოლოების ნაკრების სიმჭიდროვე + Symbol Sprayer Options სიმბოლოების სპრეის პარამეტრები + Scrunch: შეკუმშვა: + Spin: შემობრუნება: + Screen: გამჭვირვალობა: + Stain: შეფერადება: + Symbol Sizer Options სიმბოლოების ზომის შეცვლის პარამეტრები + Proportional Resizing პროპორციული ზომის შეცვლა + Resizing Affects Density ზომის შეცვლა სიმჭიდროვეზე მოქმედებს + Show Brush Size and Intensity ფუნჯის ზომისა და ინტენსივობის ჩვენება Symbol Set Density: სიმბოლოების ნაკრების სიმჭიდროვე: Intensity: ინტენსივობა: Place PDF PDF-ის განთავსება @@ -5276,6 +5347,7 @@ antiAlias Sharp მკვეთრი Width Point Edit სიგანის წერტილის რედაქტირება Art ნახატი Bearing აზიმუტი + Stylus Wheel სტილუსის ბორბალი Bristle ჯაგრისი Calligraphic კალიგრაფიული Dots წერტილები @@ -5415,6 +5487,9 @@ theme Appearance იერსახე embedding for preview and print ჩაშენება გადახედვისა და ბეჭდვისთვის embedding allowed ჩაშენება დაშვებულია {file}; {embedding} {file}; {embedding} + unknown type უცნობი ტიპი + {type}; {uses} {type}; {uses} +@plural {n} use|{n} uses {n} გამოყენება substituted: shown in {family} {style} ({detail}) ჩანაცვლებულია: ნაჩვენებია შრიფტით {family} {style} ({detail}) missing: shown in {family} {style} აკლია: ნაჩვენებია შრიფტით {family} {style} missing აკლია @@ -5988,6 +6063,7 @@ theme Appearance იერსახე Show Pixel Grid (Above 600% Zoom) პიქსელური ბადის ჩვენება (600%-ზე მეტ მასშტაბზე) Show Slice Numbers ნაჭრების ნომრების ჩვენება Show The Home Screen When No Documents Are Open საწყისი ეკრანის ჩვენება, როცა დოკუმენტი არ არის გახსნილი + Show Tool Cards ხელსაწყოების ბარათების ჩვენება Show Tool Tips მინიშნებების ჩვენება Size/Leading ზომა/სტრიქონთა დაშორება Snapping Tolerance მიბმის დაშვება @@ -6107,6 +6183,8 @@ theme Appearance იერსახე Spot Colors სპოტ-ფერები Swatch Options ფერის ნიმუშის პარამეტრები Ungroup Color Group ფერების ჯგუფის დაშლა + Color Group Options ფერების ჯგუფის პარამეტრები + Color Group Options… ფერების ჯგუფის პარამეტრები… Copy to User Defined მომხმარებლის განსაზღვრულში კოპირება Swatch Library ფერის ნიმუშების ბიბლიოთეკა Clear All Tabs ყველა ტაბულაციის გასუფთავება @@ -6386,6 +6464,7 @@ font-technology Variable ცვლადი A live rectangle's properties show one Corner Radius field for all four corners; off, each corner has its own field. ცოცხალი მართკუთხედის თვისებები ოთხივე კუთხისთვის კუთხის რადიუსის ერთ ველს აჩვენებს; გამორთვისას თითოეულ კუთხეს თავისი ველი აქვს. What edits in the Transform panel transform: the object, its pattern tiles or both; Default follows Transform Pattern Tiles. რას გარდაქმნის ცვლილებები გარდაქმნის პანელში: ობიექტს, მისი პატერნის ფილებს ან ორივეს; ნაგულისხმევი მისდევს პატერნის ფილების გარდაქმნას. With one symbol instance selected, the Transform panel uses the symbol's registration point as its reference point. როცა სიმბოლოს ერთი ეგზემპლარია მონიშნული, გარდაქმნის პანელი სიმბოლოს რეგისტრაციის წერტილს საბაზისო წერტილად იყენებს. + Drawing a rectangle, ellipse, polygon, star or line opens the Transform panel if it is closed. მართკუთხედის, ელიფსის, მრავალკუთხედის, ვარსკვლავის ან ხაზის დახატვა ხსნის გარდაქმნის პანელს, თუ ის დახურულია. Darkens the canvas outside the artboards while the Artboard tool is active. სანამ სამუშაო დაფის ხელსაწყო აქტიურია, სამუშაო დაფების გარეთ ტილოს აბნელებს. With Fade Region Outside Artboard on, the area outside the artboards stays dark while you drag with the Artboard tool. როცა სამუშაო დაფის გარეთ არის დაბნელება ჩართულია, სამუშაო დაფის ხელსაწყოთი გადათრევისას სამუშაო დაფების გარეთ არე ბნელი რჩება. How near, in pixels, the pointer must be to an object, anchor or handle for a click to select it. რამდენად ახლოს, პიქსელებში, უნდა იყოს მაჩვენებელი ობიექტთან, საყრდენ წერტილთან ან სახელურთან, რომ დაწკაპუნებამ ის მონიშნოს. @@ -6480,6 +6559,9 @@ font-technology Variable ცვლადი Channel არხი Circle წრე Circle Tool წრის ხელსაწყო + Curvature Circle Tool სიმრუდის წრის ხელსაწყო + Cusp წვეტი + Straight segment სწორი სეგმენტი Circle too large წრე ზედმეტად დიდია Clip to Art ნახატზე მოჭრა Colorize გაფერადება @@ -6851,6 +6933,7 @@ font-technology Variable ცვლადი @msg a freeform gradient keeps at least one point თავისუფალი ფორმის გრადიენტი ინარჩუნებს მინიმუმ ერთ წერტილს @msg a gradient needs at least two stops გრადიენტს სჭირდება მინიმუმ ორი გადასვლის წერტილი @msg a graphic style named `{to}` already exists გრაფიკული სტილი სახელით `{to}` უკვე არსებობს +@msg a swatch or color group named `{name}` already exists ფერის ნიმუში ან ფერების ჯგუფი სახელით `{name}` უკვე არსებობს @msg a page is missing გვერდი აკლია @msg a page out of range გვერდი დიაპაზონს გარეთაა @msg a page tree kid isn't a reference გვერდების ხის შვილობილი მიმართვა არ არის @@ -6970,6 +7053,11 @@ font-technology Variable ცვლადი @msg no anchor points selected საყრდენი წერტილები მონიშნული არ არის @msg `points` must be two or three [x, y] pairs of numbers `points` უნდა იყოს რიცხვების ორი ან სამი [x, y] წყვილი @msg direct-select two or three anchor points, or give `points` პირდაპირი მონიშვნით მონიშნეთ ორი ან სამი საყრდენი წერტილი ან მიუთითეთ `points` +@msg the path is straight there, so no circle matches its curvature ტრაექტორია იქ სწორია, ამიტომ არცერთი წრეწირი არ შეესაბამება მის სიმრუდეს +@msg the path has a cusp there, so it has no single curvature ტრაექტორიას იქ წვეტი აქვს, ამიტომ მას ერთი სიმრუდე არ აქვს +@msg the path has a corner there, so it has no single curvature ტრაექტორიას იქ კუთხე აქვს, ამიტომ მას ერთი სიმრუდე არ აქვს +@msg a guide has no curvature circle დამხმარე ხაზს სიმრუდის წრე არ აქვს +@msg the circle that matches the path there would reach past the canvas წრეწირი, რომელიც იქ ტრაექტორიას შეესაბამება, ტილოს გასცდებოდა @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 სამუშაო დაფა არ არის @@ -7203,6 +7291,7 @@ font-technology Variable ცვლადი @msg the PDF is password-protected: give its password PDF პაროლით არის დაცული: მიუთითეთ პაროლი @msg the PDF password is wrong PDF-ის პაროლი არასწორია @msg the Save PDF dialog didn't open PDF-ის შენახვის დიალოგი არ გაიხსნა +@msg the Save PDF dialog is not open PDF-ის შენახვის დიალოგი გახსნილი არ არის @msg the WMF header is damaged WMF-ის სათაური დაზიანებულია @msg the art could not be sampled ნახატიდან ნიმუშის აღება ვერ მოხერხდა @msg the art has no bounds ნახატს საზღვრები არ აქვს @@ -7405,6 +7494,7 @@ font-technology Variable ცვლადი @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 +@msg give only one of `index`, `indices` and `t` მიუთითეთ მხოლოდ ერთი: `index`, `indices` ან `t` @msg column must be true or a number from 1 column უნდა იყოს true ან რიცხვი 1-დან @msg x and y must both be numbers x და y ორივე რიცხვი უნდა იყოს @msg "{0}" is not a colour: write it as #rrggbb "{0}" ფერი არ არის: ჩაწერეთ #rrggbb სახით @@ -7509,6 +7599,33 @@ font-technology Variable ცვლადი @msg the PSD file's layer groups are nested too deeply PSD ფაილის შრეების ჯგუფები ზედმეტად ღრმადაა ჩადგმული @msg a layer of the PSD file is too large to read PSD ფაილის შრე ზედმეტად დიდია წასაკითხად @msg the PSD file's layers take more memory to read than allowed PSD ფაილის შრეების წასაკითხად დაშვებულზე მეტი მეხსიერებაა საჭირო +@msg the layers can't be read ({e}): the file was placed as its merged image შრეების წაკითხვა ვერ ხერხდება ({e}): ფაილი განთავსდა როგორც მისი გაერთიანებული გამოსახულება +@msg 1 type layer came in as pixels: the text isn't editable 1 ტექსტის შრე შემოვიდა პიქსელებად: ტექსტი არ რედაქტირდება +@msg {n} type layers came in as pixels: the text isn't editable {n} ტექსტის შრე შემოვიდა პიქსელებად: ტექსტი არ რედაქტირდება +@msg 1 adjustment layer was not applied 1 კორექციის შრე არ იქნა გამოყენებული +@msg {n} adjustment layers were not applied {n} კორექციის შრე არ იქნა გამოყენებული +@msg 1 fill layer was not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels) 1 შევსების შრე არ დაიხატა (გრადიენტული ან ნიმუშის შევსება, ფერი, რომლის წაკითხვაც ვერ ხერხდება, ან ფიგურა, რომელიც პიქსელებს არ ინახავს) +@msg {n} fill layers were not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels) {n} შევსების შრე არ დაიხატა (გრადიენტული ან ნიმუშის შევსება, ფერი, რომლის წაკითხვაც ვერ ხერხდება, ან ფიგურა, რომელიც პიქსელებს არ ინახავს) +@msg the layer effects of 1 layer weren't drawn 1 შრის შრის ეფექტები არ დაიხატა +@msg the layer effects of {n} layers weren't drawn {n} შრის შრის ეფექტები არ დაიხატა +@msg the vector masks of 1 layer weren't applied 1 შრის ვექტორული ნიღბები არ იქნა გამოყენებული +@msg the vector masks of {n} layers weren't applied {n} შრის ვექტორული ნიღბები არ იქნა გამოყენებული +@msg the knockout of 1 layer wasn't applied 1 შრის ამოჭრა არ იქნა გამოყენებული +@msg the knockout of {n} layers wasn't applied {n} შრის ამოჭრა არ იქნა გამოყენებული +@msg 1 layer was left out (hidden layers and the layers clipped to them) 1 შრე გამოტოვებულია (დამალული შრეები და მათზე მოჭრილი შრეები) +@msg {n} layers were left out (hidden layers and the layers clipped to them) {n} შრე გამოტოვებულია (დამალული შრეები და მათზე მოჭრილი შრეები) +@msg 1 layer clipped to a fill layer that wasn't drawn was left out დაუხატავ შევსების შრეზე მოჭრილი 1 შრე გამოტოვებულია +@msg {n} layers clipped to fill layers that weren't drawn were left out დაუხატავ შევსების შრეებზე მოჭრილი {n} შრე გამოტოვებულია +@msg layers in blend modes VectorCraft doesn't have ({modes}) were merged with the layers below them შრეები შერევის რეჟიმებში, რომლებიც VectorCraft-ს არ აქვს ({modes}), გაერთიანდა მათ ქვემოთ მყოფ შრეებთან +@msg 1 layer in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed 1 შრე შერევის რეჟიმში, რომელიც VectorCraft-ს არ აქვს, შემოვიდა როგორც ჩვეულებრივი: გაერთიანებას დასაშვებზე მეტი მეხსიერება სჭირდება +@msg {n} layers in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed {n} შრე შერევის რეჟიმებში, რომლებიც VectorCraft-ს არ აქვს, შემოვიდა როგორც ჩვეულებრივი: გაერთიანებას დასაშვებზე მეტი მეხსიერება სჭირდება +@msg 1 layer clipped to the layer below came in unclipped: the merge needs more memory than allowed ქვედა შრეზე მოჭრილი 1 შრე შემოვიდა მოუჭრელად: გაერთიანებას დასაშვებზე მეტი მეხსიერება სჭირდება +@msg {n} layers clipped to the layer below came in unclipped: the merge needs more memory than allowed ქვედა შრეზე მოჭრილი {n} შრე შემოვიდა მოუჭრელად: გაერთიანებას დასაშვებზე მეტი მეხსიერება სჭირდება +@msg the slices can't be read ({e}) and were left out ნაჭრების წაკითხვა ვერ ხერხდება ({e}) და ისინი გამოტოვებულია +@msg 1 slice lies outside the canvas or has no size and was left out 1 ნაჭერი ტილოს გარეთაა ან ზომა არ აქვს და გამოტოვებულია +@msg {n} slices lie outside the canvas or have no size and were left out {n} ნაჭერი ტილოს გარეთაა ან ზომა არ აქვს და გამოტოვებულია +@msg 1 slice would lie outside the canvas and was left out 1 ნაჭერი ტილოს გარეთ აღმოჩნდებოდა და გამოტოვებულია +@msg {n} slices would lie outside the canvas and were left out {n} ნაჭერი ტილოს გარეთ აღმოჩნდებოდა და გამოტოვებულია @msg the layers can't be read ({e}): the file opened as its merged image შრეების წაკითხვა ვერ ხერხდება ({e}): ფაილი გაიხსნა როგორც მისი გაერთიანებული გამოსახულება @msg {depth}-bit PSD files in this colour mode can't be read ამ ფერის რეჟიმში {depth}-ბიტიანი PSD ფაილების წაკითხვა ვერ ხერხდება @msg the PSD file is cut short PSD ფაილი შეკვეცილია @@ -10324,6 +10441,8 @@ breakText Glyphs გლიფები # Path Precision Tools add-on: Tangent Circle. Tangent Circle… მხები წრე… Tangent Circle მხები წრე + Tangent Circle Tool მხები წრის ხელსაწყო + No tangent circle here აქ მხები წრე არ არის Circle: წრე: @msg `ids` names an object twice `ids` ერთსა და იმავე ობიექტს ორჯერ მიუთითებს @msg select two or three paths or compound paths მონიშნეთ ორი ან სამი ტრაექტორია ან შედგენილი ტრაექტორია @@ -10339,6 +10458,16 @@ breakText Glyphs გლიფები @msg `circle` is past the last circle found ({found}) `circle` ბოლო ნაპოვნი წრის შემდეგაა ({found}) @msg object {value} is not a path or compound path ობიექტი {value} არ არის ტრაექტორია ან შედგენილი ტრაექტორია @msg these shapes are too small to measure ეს ფიგურები ზედმეტად პატარაა გასაზომად +# Path Precision Tools add-on: Add Bounding Rectangle and Add Bounding Circle. + Add Bounding Rectangle შემომსაზღვრელი მართკუთხედის დამატება + Add Bounding Circle შემომსაზღვრელი წრეწირის დამატება + Add Bounding Rectangle… შემომსაზღვრელი მართკუთხედის დამატება… + Add Bounding Circle… შემომსაზღვრელი წრეწირის დამატება… + One per Object თითო თითოეულ ობიექტზე +@msg nothing to enclose შემოსაზღვრელი არაფერია +@msg `offset` must be 0 or more `offset` უნდა იყოს 0 ან მეტი +@msg the shape would have no size ფიგურას ზომა არ ექნებოდა +@msg the shape would reach past the edge of the canvas ფიგურა ტილოს კიდეს გასცდებოდა # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools დოკუმენტის ხელსაწყოები Save a Timestamped Copy ასლის შენახვა თარიღითა და დროით @@ -10779,6 +10908,50 @@ font-script Japanese იაპონური @msg A joint does not close by {gap} pt. შეერთება არ იხურება {gap} pt-ით. @msg Two panels pass through each other. ორი პანელი ერთმანეთში გადის. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer უნდა იყოს "singleLine", "everyLine", "standardSingleLine" ან "standardEveryLine" + Fine Stipple წვრილი წერტილოვანი ტექსტურა + Dense Stipple მკვრივი წერტილოვანი ტექსტურა + Soft Stipple რბილი წერტილოვანი ტექსტურა + Bold Stipple მსხვილი წერტილოვანი ტექსტურა + Paper Cutouts ქაღალდის ამონაჭრები + Coral Layers მარჯნის ფენები + Mint Layers პიტნის ფენები + Midnight Layers შუაღამის ფენები + Sunflower Sheet მზესუმზირის ფურცელი + Rose Layers ვარდისფერი ფენები + Monochrome Stack მონოქრომული დასტა +# Tool cards (General › Show Tool Cards): one sentence on what each tool does. + Shows a card with what a toolbar tool does and what its keys do instead of its tip; it needs Show Tool Tips. ინსტრუმენტების ზოლის ინსტრუმენტისა და მისი კლავიშების მოქმედებას მინიშნების ნაცვლად ბარათზე აჩვენებს; საჭიროა მინიშნებების ჩვენება. + Selects whole objects and groups to move, resize or rotate them. მთლიანად მონიშნავს ობიექტებსა და ჯგუფებს მათი გადასაადგილებლად, ზომის შესაცვლელად ან მოსაბრუნებლად. + Selects anchor points and path segments to reshape a path. მონიშნავს საყრდენ წერტილებსა და ტრაექტორიის სეგმენტებს ტრაექტორიის ფორმის შესაცვლელად. + Draws paths point by point, with straight segments and smooth curves. ხატავს ტრაექტორიებს წერტილ-წერტილ, სწორი სეგმენტებითა და გლუვი მრუდებით. + Draws smooth curves through the points you click. ხატავს გლუვ მრუდებს იმ წერტილებზე გავლით, რომლებზეც დააწკაპუნებთ. + Adds text at a point, or in a frame you drag. ამატებს ტექსტს წერტილში ან ჩარჩოში, რომელსაც გაჭიმავთ. + Draws rectangles and squares. ხატავს მართკუთხედებსა და კვადრატებს. + Draws rectangles with rounded corners. ხატავს მომრგვალებულკუთხიან მართკუთხედებს. + Draws ellipses and circles. ხატავს ელიფსებსა და წრეებს. + Draws polygons with sides of equal length. ხატავს ტოლგვერდა მრავალკუთხედებს. + Draws stars. ხატავს ვარსკვლავებს. + Turns objects around a reference point. აბრუნებს ობიექტებს საორიენტაციო წერტილის გარშემო. + Flips objects across an axis through a reference point. სარკისებურად ასახავს ობიექტებს საორიენტაციო წერტილზე გამავალი ღერძის მიმართ. + Resizes objects from a reference point. ცვლის ობიექტების ზომას საორიენტაციო წერტილიდან. + Slants objects from a reference point. ახრის ობიექტებს საორიენტაციო წერტილიდან. + Moves the view of the document. გადააადგილებს დოკუმენტის ხედს. + Magnifies or reduces the view. ადიდებს ან ამცირებს ხედს. + Copies the color and other attributes of one object to the selection. აკოპირებს ერთი ობიექტის ფერსა და სხვა ატრიბუტებს მონიშნულზე. + Sets the direction and length of a gradient. აყენებს გრადიენტის მიმართულებასა და სიგრძეს. + Creates, selects and resizes artboards. ქმნის, მონიშნავს და ცვლის სამუშაო დაფების ზომას. + Changes the width of a stroke along its length. ცვლის კონტურის სისქეს მისი სიგრძის გასწვრივ. + Bends art by dragging pins placed on it. ღუნავს ნახატს მასზე დასმული ქინძისთავების გადათრევით. + Pushes the outlines of paths in the direction you drag. უბიძგებს ტრაექტორიების მოხაზულობას გადათრევის მიმართულებით. + Twists the outlines of paths into swirls. ხვევს ტრაექტორიების მოხაზულობას გრიგალებად. + Pulls the outlines of paths in toward the brush. იზიდავს ტრაექტორიების მოხაზულობას ფუნჯისკენ. + Pushes the outlines of paths out from the brush. უბიძგებს ტრაექტორიების მოხაზულობას ფუნჯიდან გარეთ. + Adds curved details along the outlines of paths. ამატებს მრუდ დეტალებს ტრაექტორიების მოხაზულობის გასწვრივ. + Adds spiky details along the outlines of paths. ამატებს წვეტიან დეტალებს ტრაექტორიების მოხაზულობის გასწვრივ. + Adds wrinkles along the outlines of paths. ამატებს ნაოჭებს ტრაექტორიების მოხაზულობის გასწვრივ. + Moves, copies and resizes objects on the perspective grid. გადააადგილებს, აკოპირებს და ცვლის ობიექტების ზომას პერსპექტივის ბადეზე. + Makes a series of steps between two or more objects. ქმნის საფეხურების რიგს ორ ან მეტ ობიექტს შორის. + Places dimension lines that show measured lengths. სვამს ზომის ხაზებს, რომლებიც გაზომილ სიგრძეებს აჩვენებს. Tap მოკლე დაჭერა Clear Hold ხანგრძლივი დაჭერის გასუფთავება Hold Shortcuts ხანგრძლივი დაჭერის მალსახმობები @@ -10795,3 +10968,7 @@ font-script Japanese იაპონური Pulse Stroke პულსირებადი მონასმი Round Flow მრგვალი ნაკადი Chisel Flow დახრილი ნაკადი + +# #5804 native-picked raster editor (draft translations; native review welcome). + Edit Original with: ორიგინალის რედაქტირება პროგრამით: +file-filter Applications აპლიკაციები diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index fd3e3e3dfb..ddeca628cf 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -88,6 +88,15 @@ digits Malayalam 말라얄람어 YakumonoZenkaku YakumonoZenkaku Kinsoku Set 긴소쿠 세트 Kinsoku Shori Type 긴소쿠 처리 유형 + Kinsoku Shori Settings… 긴소쿠 처리 설정… + Kinsoku Shori Settings 긴소쿠 처리 설정 + Kinsoku Sets 긴소쿠 세트 목록 + Kinsoku Set Base 긴소쿠 세트 기준 + Based on: 기준: + Cannot Start Line 행 시작 금지 문자 + Cannot End Line 행 끝 금지 문자 + Hanging Punctuation 매달림 문장 부호 + Inseparable Characters 분리 금지 문자 Push In First 밀어 넣기 우선 Push Out First 밀어내기 우선 Push Out Only 밀어내기만 @@ -611,6 +620,15 @@ digits Malayalam 말라얄람어 Shading Color 셰이딩 색상 Black Overprint 검정 겹쳐찍기 Draw Hidden Faces 숨겨진 면 그리기 + Map Art… 아트 매핑… + Map Art 아트 매핑 + First Surface 첫 번째 표면 + Previous Surface 이전 표면 + Next Surface 다음 표면 + Last Surface 마지막 표면 + Scale to Fit 크기에 맞게 조절 + Shade Artwork 아트워크 음영 처리 + Invisible Geometry 보이지 않는 형상 Revolve… 회전체… Inflate… 부풀리기… Materials… 재질… @@ -721,6 +739,8 @@ digits Malayalam 말라얄람어 Hide Text Threads 문자 연결선 숨기기 Hide Gradient Annotator 그레이디언트 주석 숨기기 Hide Corner Widget 모퉁이 위젯 숨기기 + Hide Shape Widgets 모양 위젯 숨기기 + Show Shape Widgets 모양 위젯 표시 Guides 안내선 Hide Guides 안내선 숨기기 Lock Guides 안내선 잠그기 @@ -828,6 +848,9 @@ digits Malayalam 말라얄람어 Box Channel 상자 채널 Color box 색상 상자 Color Wheel Options 색상환 옵션 + Show Harmony 하모니 표시 + Harmony Rule 하모니 규칙 + Harmony color 하모니 색상 CSS Properties CSS 속성 Document Info 문서 정보 Flattener Preview 병합 미리 보기 @@ -1356,6 +1379,9 @@ antiAlias Sharp 날카롭게 Choose… 선택… Circle 원 Circle Tool 점 기준 원 도구 + Curvature Circle Tool 곡률원 도구 + Cusp 뾰족점 + Straight segment 직선 세그먼트 Circle too large 원이 너무 큽니다 Clear All Tabs 모든 탭 지우기 Above Text 문자 위 @@ -1519,10 +1545,25 @@ antiAlias Sharp 날카롭게 Cut Path at Selected Anchor Points 선택한 앵커 포인트에서 패스 자르기 Dim Images to: 이미지 흐리게: Duplicate Selection 선택 항목 복제 + PSD Import Options PSD 가져오기 옵션 + Place PSD PSD 가져오기 + Convert Layers to Objects 레이어를 오브젝트로 변환 + Import Hidden Layers 숨겨진 레이어 가져오기 + Flatten Layers to a Single Image 레이어를 단일 이미지로 병합 + Import Slices 분할 영역 가져오기 DXF Import Options DXF 가져오기 옵션 DXF Info DXF 정보 DXF Options DXF 옵션 DXF Options Dialog DXF 옵션 대화상자 + HP-GL Options HP-GL 옵션 + HP-GL Options Dialog HP-GL 옵션 대화상자 + Curve Tolerance: 곡선 허용치: + Origin: 원점: + Pens: 펜: + One Pen per Color 색상마다 펜 하나 + Pen Table 펜 테이블 + Draw the Nearest Path Next 가장 가까운 패스를 다음에 그리기 + Draw Inner Paths First 안쪽 패스를 먼저 그리기 Darken 어둡게 Darkness 어둡기 Dashed 점선 @@ -2571,6 +2612,7 @@ antiAlias Sharp 날카롭게 Pressure 필압 Tilt 기울기 Bearing 방위 + Stylus Wheel 스타일러스 휠 Shape: 모양: Bristle Length: 강모 길이: Bristle Density: 강모 밀도: @@ -2601,6 +2643,9 @@ antiAlias Sharp 날카롭게 embedding for preview and print 미리 보기 및 인쇄용 포함 embedding allowed 포함 허용 {file}; {embedding} {file}; {embedding} + unknown type 알 수 없는 유형 + {type}; {uses} {type}; {uses} +@plural {n} use|{n} uses {n}회 사용 substituted: shown in {family} {style} ({detail}) 대체됨: {family} {style}(으)로 표시({detail}) missing: shown in {family} {style} 없음: {family} {style}(으)로 표시 missing 없음 @@ -2804,6 +2849,8 @@ antiAlias Sharp 날카롭게 Overprint and Transparency Flattener Options 오버프린트 및 투명도 병합 옵션 Custom… 사용자 지정… Custom Transparency Flattener Options 사용자 지정 투명도 병합 옵션 + The PDF preset keeps the flattener preset but not the Custom… settings. PDF 사전 설정에는 병합 사전 설정이 저장되지만 사용자 지정… 설정은 저장되지 않습니다. + PDF 1.3 files clip rasterized areas to their regions, and Overprint sets whether overprints are kept. PDF 1.3 파일은 래스터화된 영역을 해당 영역의 모양으로 클립하며, 오버프린트 설정에 따라 오버프린트 유지 여부가 결정됩니다. EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS에는 알파 투명도가 없으며, 오버프린트 설정에 따라 오버프린트 유지 여부가 결정됩니다. Overprint: 오버프린트: Overprints: 오버프린트: @@ -3181,6 +3228,9 @@ mark-style Japanese 일본식 Reload Arrowheads 화살촉 다시 불러오기 Reset the rows to the artwork's colors 행을 아트웍 색상으로 재설정 Color Theme Picker 색상 테마 피커 + Undo Changes 변경 내용 실행 취소 + Redo Changes 변경 내용 다시 실행 +@msg Recolor Artwork is not open 아트웍 색상 재지정이 열려 있지 않습니다 Click or drag across the art to pick its colors; Shift adds more 아트웍을 클릭하거나 드래그하여 색상을 가져옵니다. Shift 키로 더 추가합니다 Prominent Colors 주요 색상 Save All Colors 모든 색상 저장 @@ -3231,6 +3281,7 @@ mark-style Japanese 일본식 A live rectangle's properties show one Corner Radius field for all four corners; off, each corner has its own field. 라이브 사각형의 속성에 네 모퉁이 모두에 쓰는 모퉁이 반지름 필드 하나를 표시합니다. 끄면 모퉁이마다 필드가 따로 있습니다. What edits in the Transform panel transform: the object, its pattern tiles or both; Default follows Transform Pattern Tiles. 변형 패널에서 편집할 때 변형되는 대상으로, 개체, 패턴 타일 또는 둘 다입니다. 기본값은 패턴 타일 변형을 따릅니다. With one symbol instance selected, the Transform panel uses the symbol's registration point as its reference point. 심볼 인스턴스 하나를 선택하면 변형 패널은 심볼의 등록 지점을 참조점으로 사용합니다. + Drawing a rectangle, ellipse, polygon, star or line opens the Transform panel if it is closed. 사각형, 타원, 다각형, 별 또는 선을 그리면 변형 패널이 닫혀 있을 때 열립니다. Darkens the canvas outside the artboards while the Artboard tool is active. 아트보드 도구를 사용하는 동안 아트보드 바깥의 캔버스를 어둡게 표시합니다. With Fade Region Outside Artboard on, the area outside the artboards stays dark while you drag with the Artboard tool. 아트보드 외부 영역 어둡게 표시가 켜져 있으면 아트보드 도구로 드래그하는 동안에도 아트보드 바깥 영역이 어둡게 유지됩니다. How near, in pixels, the pointer must be to an object, anchor or handle for a click to select it. 클릭으로 개체, 고정점 또는 핸들을 선택하려면 포인터가 얼마나 가까이(픽셀) 있어야 하는지입니다. @@ -3372,6 +3423,7 @@ mark-style Japanese 일본식 Save Document Preset 문서 사전 설정 저장 Preset {number} 사전 설정 {number} Save Preset… 사전 설정 저장… + Save Summary… 요약 저장… Save Print Preset 인쇄 사전 설정 저장 Save Recovery Data 복구 데이터 저장 Save Save for Web Preset 웹용 저장 사전 설정 저장 @@ -3538,6 +3590,7 @@ mark-style Japanese 일본식 Show List View 목록 보기 표시 Show Note 메모 표시 Show Options 옵션 표시 + Show on Shape Creation 모양 생성 시 표시 Show Recent Colors 최근 색상 표시 Toggle RGB Percent RGB 백분율 표시 전환 Show Original Path 원래 패스 표시 @@ -3559,6 +3612,7 @@ mark-style Japanese 일본식 Show Thumbnails 축소판 표시 Show Tile Edge 타일 가장자리 표시 Show Tints/Shades 밝은/어두운 색조 표시 + Show Tool Cards 도구 카드 표시 Show Tool Tips 도구 설명 표시 Show Vivid/Muted 선명/탁한 색상 표시 Show Warm/Cool 따뜻한/차가운 색상 표시 @@ -3608,6 +3662,8 @@ mark-style Japanese 일본식 Outlines 윤곽선 Outlines with Source Image 원본 이미지 포함 윤곽선 Source Image 원본 이미지 + Split View 분할 보기 + Divider 구분선 Press and hold to view the source image 누르고 있는 동안 원본 이미지 보기 Image Trace View 이미지 추적 보기 Snap Options 스냅 옵션 @@ -3861,6 +3917,8 @@ mark-style Japanese 일본식 Unembed 포함 해제 Unembed… 포함 해제… Ungroup Color Group 색상 그룹 해제 + Color Group Options 색상 그룹 옵션 + Color Group Options… 색상 그룹 옵션… Uniform 균일 Unite 합치기 Units 단위 @@ -4134,6 +4192,17 @@ gradient-kind Radial 방사형 Largest: 최대: Direction: 방향: Symbolism Tools Options 심볼 도구 옵션 + Tool: 도구: + Symbol Set Density 심볼 세트 밀도 + Symbol Sprayer Options 심볼 분무기 옵션 + Scrunch: 스크런치: + Spin: 회전: + Screen: 스크린: + Stain: 염색: + Symbol Sizer Options 심볼 크기 조절기 옵션 + Proportional Resizing 비율에 맞게 크기 조정 + Resizing Affects Density 크기 조정이 밀도에 영향 + Show Brush Size and Intensity 브러시 크기 및 강도 표시 Symbol Set Density: 심볼 세트 밀도: Flattener presets 병합 프리셋 file-filter All readable files 읽을 수 있는 모든 파일 @@ -4935,6 +5004,11 @@ variable-list-end {0}, {1} {0} 및 {1} @msg no anchor points selected 선택한 앵커 포인트가 없습니다 @msg `points` must be two or three [x, y] pairs of numbers `points`는 숫자 쌍 [x, y] 두 개 또는 세 개여야 합니다 @msg direct-select two or three anchor points, or give `points` 앵커 포인트 두 개 또는 세 개를 직접 선택하거나 `points`를 지정하세요 +@msg the path is straight there, so no circle matches its curvature 패스가 그 위치에서 직선이므로 곡률에 맞는 원이 없습니다 +@msg the path has a cusp there, so it has no single curvature 패스가 그 위치에서 뾰족하므로 곡률이 하나로 정해지지 않습니다 +@msg the path has a corner there, so it has no single curvature 패스가 그 위치에서 모서리를 이루므로 곡률이 하나로 정해지지 않습니다 +@msg a guide has no curvature circle 안내선에는 곡률원이 없습니다 +@msg the circle that matches the path there would reach past the canvas 그 위치에서 패스에 맞는 원이 캔버스를 벗어납니다 @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 먼저 격리 모드를 종료하세요 @@ -5049,6 +5123,7 @@ variable-list-end {0}, {1} {0} 및 {1} @msg select a stroke with a variable width 가변 너비 선을 선택하세요 @msg the selected stroke's profile is already listed as {_1} 선택한 선의 프로파일이 이미 {_1}(으)로 등록되어 있습니다 @msg a graphic style named `{to}` already exists `{to}` 그래픽 스타일이 이미 있습니다 +@msg a swatch or color group named `{name}` already exists `{name}` 견본 또는 색상 그룹이 이미 있습니다 @msg a key object sits on that point 그 포인트에 키 개체가 있습니다 @msg no graphic style `{name}` `{name}` 그래픽 스타일이 없습니다 @msg node {_1} is not text 노드 {_1}은(는) 텍스트가 아닙니다 @@ -5372,6 +5447,7 @@ variable-list-end {0}, {1} {0} 및 {1} @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 중 하나만 지정하세요 +@msg give only one of `index`, `indices` and `t` `index`, `indices`, `t` 중 하나만 지정하세요 @msg column must be true or a number from 1 column은 true이거나 1 이상의 숫자여야 합니다 @msg unknown panel `{raw}` 알 수 없는 패널 `{raw}` @msg `{panel}` has no display sizes to cycle `{panel}`에는 전환할 표시 크기가 없습니다 @@ -5388,6 +5464,7 @@ variable-list-end {0}, {1} {0} 및 {1} @msg no file manager here 여기에는 파일 관리자가 없습니다 @msg no revert command 되돌리기 명령이 없습니다 @msg the Save PDF dialog didn't open PDF 저장 대화상자가 열리지 않았습니다 +@msg the Save PDF dialog is not open PDF 저장 대화상자가 열려 있지 않습니다 @msg the document has never been saved 문서가 저장된 적이 없습니다 @msg the export returned unreadable data 내보내기가 읽을 수 없는 데이터를 반환했습니다 @msg {status} ({e}) {status}({e}) @@ -5842,6 +5919,49 @@ liquify-list-end {0}, {1} {0} 및 {1} @msg the PSD file's layer groups are nested too deeply PSD 파일의 레이어 그룹이 너무 깊이 중첩되어 있습니다 @msg a layer of the PSD file is too large to read PSD 파일의 레이어가 너무 커서 읽을 수 없습니다 @msg the PSD file's layers take more memory to read than allowed PSD 파일의 레이어를 읽는 데 허용된 것보다 많은 메모리가 필요합니다 +@msg the file is no longer loaded 파일이 더 이상 로드되어 있지 않습니다 +@msg the layers can't be read ({e}): the file was placed as its merged image 레이어를 읽을 수 없습니다({e}): 파일이 병합된 이미지로 가져와졌습니다 +@msg 1 type layer came in as pixels: the text isn't editable 문자 레이어 1개가 픽셀로 들어왔습니다: 텍스트를 편집할 수 없습니다 +@msg {n} type layers came in as pixels: the text isn't editable 문자 레이어 {n}개가 픽셀로 들어왔습니다: 텍스트를 편집할 수 없습니다 +@msg 1 adjustment layer was not applied 조정 레이어 1개가 적용되지 않았습니다 +@msg {n} adjustment layers were not applied 조정 레이어 {n}개가 적용되지 않았습니다 +@msg 1 fill layer was not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels) 칠 레이어 1개가 그려지지 않았습니다(그레이디언트 또는 패턴 칠, 읽을 수 없는 색상, 또는 픽셀을 저장하지 않는 모양) +@msg {n} fill layers were not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels) 칠 레이어 {n}개가 그려지지 않았습니다(그레이디언트 또는 패턴 칠, 읽을 수 없는 색상, 또는 픽셀을 저장하지 않는 모양) +@msg the layer effects of 1 layer weren't drawn 레이어 1개의 레이어 효과가 그려지지 않았습니다 +@msg the layer effects of {n} layers weren't drawn 레이어 {n}개의 레이어 효과가 그려지지 않았습니다 +@msg the vector masks of 1 layer weren't applied 레이어 1개의 벡터 마스크가 적용되지 않았습니다 +@msg the vector masks of {n} layers weren't applied 레이어 {n}개의 벡터 마스크가 적용되지 않았습니다 +@msg the knockout of 1 layer wasn't applied 레이어 1개의 녹아웃이 적용되지 않았습니다 +@msg the knockout of {n} layers wasn't applied 레이어 {n}개의 녹아웃이 적용되지 않았습니다 +@msg 1 layer was left out (hidden layers and the layers clipped to them) 레이어 1개를 제외했습니다(숨겨진 레이어와 그에 클리핑된 레이어) +@msg {n} layers were left out (hidden layers and the layers clipped to them) 레이어 {n}개를 제외했습니다(숨겨진 레이어와 그에 클리핑된 레이어) +@msg 1 layer clipped to a fill layer that wasn't drawn was left out 그려지지 않은 칠 레이어에 클리핑된 레이어 1개를 제외했습니다 +@msg {n} layers clipped to fill layers that weren't drawn were left out 그려지지 않은 칠 레이어에 클리핑된 레이어 {n}개를 제외했습니다 +@msg layers in blend modes VectorCraft doesn't have ({modes}) were merged with the layers below them VectorCraft에 없는 혼합 모드({modes})의 레이어를 아래 레이어와 병합했습니다 +@msg 1 layer in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed VectorCraft에 없는 혼합 모드의 레이어 1개가 표준으로 들어왔습니다: 병합에 허용된 것보다 많은 메모리가 필요합니다 +@msg {n} layers in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed VectorCraft에 없는 혼합 모드의 레이어 {n}개가 표준으로 들어왔습니다: 병합에 허용된 것보다 많은 메모리가 필요합니다 +@msg 1 layer clipped to the layer below came in unclipped: the merge needs more memory than allowed 아래 레이어에 클리핑된 레이어 1개가 클리핑 없이 들어왔습니다: 병합에 허용된 것보다 많은 메모리가 필요합니다 +@msg {n} layers clipped to the layer below came in unclipped: the merge needs more memory than allowed 아래 레이어에 클리핑된 레이어 {n}개가 클리핑 없이 들어왔습니다: 병합에 허용된 것보다 많은 메모리가 필요합니다 +@msg hiddenLayers applies to a PSD file placed with layers: true hiddenLayers는 layers: true로 가져오는 PSD 파일에 적용됩니다 +@msg importSlices: a linked PSD file is placed as its flat image; give link: false to embed it with its slices importSlices: 연결된 PSD 파일은 평면 이미지로 가져옵니다. 분할 영역과 함께 포함하려면 link: false를 지정하세요 +@msg layers: a linked PSD file is placed as its flat image; leave link out or give link: false layers: 연결된 PSD 파일은 평면 이미지로 가져옵니다. link를 생략하거나 link: false를 지정하세요 +@msg the slices can't be read ({e}) and were left out 분할 영역을 읽을 수 없어({e}) 제외했습니다 +@msg 1 slice lies outside the canvas or has no size and was left out 분할 영역 1개가 캔버스 밖에 있거나 크기가 없어 제외했습니다 +@msg {n} slices lie outside the canvas or have no size and were left out 분할 영역 {n}개가 캔버스 밖에 있거나 크기가 없어 제외했습니다 +@msg 1 slice would lie outside the canvas and was left out 분할 영역 1개가 캔버스 밖에 놓이게 되어 제외했습니다 +@msg {n} slices would lie outside the canvas and were left out 분할 영역 {n}개가 캔버스 밖에 놓이게 되어 제외했습니다 +@msg the slices' descriptor holds too many values 분할 영역 설명자에 값이 너무 많습니다 +@msg the slices' descriptor has a version other than 16 분할 영역 설명자의 버전이 16이 아닙니다 +@msg the slices are stored in version {v}, which isn't read 분할 영역이 읽지 않는 버전 {v}(으)로 저장되어 있습니다 +@msg the file has {count} slices, more than the {MAX_SLICES} read 파일의 분할 영역이 {count}개로, 읽는 {MAX_SLICES}개보다 많습니다 +@msg the slices' descriptor has no list of slices 분할 영역 설명자에 분할 영역 목록이 없습니다 +@msg the slices' descriptor lists something other than a slice 분할 영역 설명자에 분할 영역이 아닌 항목이 있습니다 +@msg a slice in the slices' descriptor has no bounds 분할 영역 설명자의 분할 영역에 경계가 없습니다 +@msg a slice's bounds in the slices' descriptor aren't numbers 분할 영역 설명자의 분할 영역 경계가 숫자가 아닙니다 +@msg a text in the slices has more than the {MAX_TEXT} characters read 분할 영역의 텍스트가 읽는 {MAX_TEXT}자를 넘습니다 +@msg the slices' descriptor nests too deep 분할 영역 설명자가 너무 깊게 중첩되어 있습니다 +@msg the slices' descriptor has a reference of an unknown kind ({_1}) 분할 영역 설명자에 알 수 없는 종류의 참조가 있습니다({_1}) +@msg the slices' descriptor has a value of an unknown type ({_1}) 분할 영역 설명자에 알 수 없는 유형의 값이 있습니다({_1}) @msg the layers can't be read ({e}): the file opened as its merged image 레이어를 읽을 수 없습니다({e}): 파일이 병합된 이미지로 열렸습니다 @msg {depth}-bit PSD files in this colour mode can't be read 이 색상 모드의 {depth}비트 PSD 파일은 읽을 수 없습니다 @msg the PSD file is cut short PSD 파일이 잘려 있습니다 @@ -5869,6 +5989,25 @@ liquify-list-end {0}, {1} {0} 및 {1} Preserve Embedded Profiles 포함된 프로필 유지 Convert to Working Space 작업 공간으로 변환 Preserve Numbers 숫자 유지 + Profile Mismatches: 프로필 불일치: + Ask When Opening 열 때 묻기 + Ask When Pasting 붙여넣을 때 묻기 + Missing Profiles: 누락된 프로필: + Embedded Profile Mismatch 포함된 프로필 불일치 + Missing Profile 프로필 없음 + Paste Profile Mismatch 붙여넣기 프로필 불일치 + “{name}” is not tagged with a {model} profile. “{name}”에 {model} 프로필이 없습니다. + “{name}” is tagged with the {model} profile “{profile}”, which is not the {model} working space “{working}”. “{name}”의 {model} 프로필은 “{profile}”이며, {model} 작업 공간 “{working}”이(가) 아닙니다. + Use the embedded profile 포함된 프로필 사용 + Convert the colors to the working space 색상을 작업 공간으로 변환 + Discard the embedded profile 포함된 프로필 버리기 + Leave as is 그대로 두기 + Assign the working space 작업 공간 지정 + Assign profile: 프로필 지정: + Preserve the color numbers 색상 값 유지 + Convert to keep the colors' appearance 색상의 모양을 유지하도록 변환 +@msg `{path}` goes with `{key}`: "assign" only `{path}`은(는) `{key}`: "assign"일 때만 씁니다 + The pasted colors come from a document whose {model} profile is “{from}”; this document's is “{to}”. 붙여넣은 색상은 {model} 프로필이 “{from}”인 문서에서 왔습니다. 이 문서의 프로필은 “{to}”입니다. Texture 텍스처 Craquelure… 크랙… Grain… 그레인… @@ -7733,6 +7872,8 @@ breakText Glyphs 글리프 # Path Precision Tools add-on: Tangent Circle. Tangent Circle… 접원… Tangent Circle 접원 + Tangent Circle Tool 접원 도구 + No tangent circle here 여기에는 접원이 없음 Circle: 원: @msg `ids` names an object twice `ids`에 같은 오브젝트가 두 번 있습니다 @msg select two or three paths or compound paths 패스나 컴파운드 패스를 두 개 또는 세 개 선택하세요 @@ -7748,6 +7889,16 @@ breakText Glyphs 글리프 @msg `circle` is past the last circle found ({found}) `circle`이(가) 찾은 마지막 원을 넘었습니다({found}) @msg object {value} is not a path or compound path 오브젝트 {value}은(는) 패스나 컴파운드 패스가 아닙니다 @msg these shapes are too small to measure 이 모양들은 너무 작아서 측정할 수 없습니다 +# Path Precision Tools add-on: Add Bounding Rectangle and Add Bounding Circle. + Add Bounding Rectangle 경계 사각형 추가 + Add Bounding Circle 경계 원 추가 + Add Bounding Rectangle… 경계 사각형 추가… + Add Bounding Circle… 경계 원 추가… + One per Object 개체마다 하나 +@msg nothing to enclose 둘러쌀 항목이 없습니다 +@msg `offset` must be 0 or more `offset`은(는) 0 이상이어야 합니다 +@msg the shape would have no size 도형의 크기가 없습니다 +@msg the shape would reach past the edge of the canvas 도형이 캔버스 가장자리를 벗어납니다 # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools 문서 도구 Save a Timestamped Copy 날짜와 시간이 붙은 사본 저장 @@ -10017,6 +10168,39 @@ breakText Glyphs 글리프 No objects are selected. 선택한 개체가 없습니다. Open a document to mark its fold lines. 접는 선을 지정하려면 문서를 여세요. Remove Fold Line Role 선 종류 제거 +# Tool cards (General › Show Tool Cards): one sentence on what each tool does. + Shows a card with what a toolbar tool does and what its keys do instead of its tip; it needs Show Tool Tips. 도구 막대의 도구와 그 키가 하는 일을 도움말 대신 카드로 표시합니다. 도구 설명 표시가 켜져 있어야 합니다. + Selects whole objects and groups to move, resize or rotate them. 개체와 그룹 전체를 선택하여 이동하거나 크기를 조정하거나 회전합니다. + Selects anchor points and path segments to reshape a path. 기준점과 패스 세그먼트를 선택하여 패스의 모양을 바꿉니다. + Draws paths point by point, with straight segments and smooth curves. 직선 세그먼트와 부드러운 곡선으로 패스를 한 점씩 그립니다. + Draws smooth curves through the points you click. 클릭한 점을 지나는 부드러운 곡선을 그립니다. + Adds text at a point, or in a frame you drag. 한 점에 또는 드래그한 프레임 안에 텍스트를 추가합니다. + Draws rectangles and squares. 직사각형과 정사각형을 그립니다. + Draws rectangles with rounded corners. 모서리가 둥근 직사각형을 그립니다. + Draws ellipses and circles. 타원과 원을 그립니다. + Draws polygons with sides of equal length. 변의 길이가 같은 다각형을 그립니다. + Draws stars. 별을 그립니다. + Turns objects around a reference point. 기준점을 중심으로 개체를 회전합니다. + Flips objects across an axis through a reference point. 기준점을 지나는 축을 기준으로 개체를 반사합니다. + Resizes objects from a reference point. 기준점에서 개체의 크기를 조정합니다. + Slants objects from a reference point. 기준점에서 개체를 기울입니다. + Moves the view of the document. 문서 보기를 이동합니다. + Magnifies or reduces the view. 보기를 확대하거나 축소합니다. + Copies the color and other attributes of one object to the selection. 한 개체의 색상과 기타 속성을 선택 항목에 복사합니다. + Sets the direction and length of a gradient. 그레이디언트의 방향과 길이를 설정합니다. + Creates, selects and resizes artboards. 아트보드를 만들고 선택하고 크기를 조정합니다. + Changes the width of a stroke along its length. 선의 폭을 길이를 따라 바꿉니다. + Bends art by dragging pins placed on it. 아트에 놓은 핀을 드래그하여 구부립니다. + Pushes the outlines of paths in the direction you drag. 패스의 윤곽을 드래그하는 방향으로 밀어냅니다. + Twists the outlines of paths into swirls. 패스의 윤곽을 소용돌이 모양으로 비틉니다. + Pulls the outlines of paths in toward the brush. 패스의 윤곽을 브러시 쪽으로 끌어당깁니다. + Pushes the outlines of paths out from the brush. 패스의 윤곽을 브러시에서 바깥쪽으로 밀어냅니다. + Adds curved details along the outlines of paths. 패스의 윤곽을 따라 곡선 모양의 세부를 추가합니다. + Adds spiky details along the outlines of paths. 패스의 윤곽을 따라 뾰족한 세부를 추가합니다. + Adds wrinkles along the outlines of paths. 패스의 윤곽을 따라 주름을 추가합니다. + Moves, copies and resizes objects on the perspective grid. 원근 격자에서 개체를 이동, 복사하고 크기를 조정합니다. + Makes a series of steps between two or more objects. 두 개 이상의 개체 사이에 일련의 단계를 만듭니다. + Places dimension lines that show measured lengths. 측정한 길이를 보여 주는 치수선을 배치합니다. Tap 짧게 누르기 Clear Hold 길게 누르기 지우기 Hold Shortcuts 길게 누르기 단축키 @@ -10047,7 +10231,18 @@ breakText Glyphs 글리프 @msg A panel is not joined to the rest by a crease. 패널이 어떤 오시선으로도 나머지와 연결되어 있지 않습니다. @msg A fold line is on a non-printing layer. 접는 선이 인쇄되지 않는 레이어에 있습니다. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} 패널: {panels}, 힌지: {hinges}, 오류: {errors}, 경고: {warnings} + Paper Cutouts 종이 오려내기 + Coral Layers 산호색 레이어 + Mint Layers 민트색 레이어 + Midnight Layers 한밤중 레이어 + Sunflower Sheet 해바라기 시트 + Rose Layers 장미색 레이어 + Monochrome Stack 단색 쌓기 Dashed Arrow 점선 화살표 + Fine Stipple 가는 점묘 + Dense Stipple 촘촘한 점묘 + Soft Stipple 부드러운 점묘 + Bold Stipple 굵은 점묘 Pressure Sensitive 압력 감지 Flex Ribbon 유연한 리본 Pulse Stroke 맥동 획 @@ -10063,3 +10258,7 @@ breakText Glyphs 글리프 @msg Other blanks not shown: {count} 표시되지 않은 다른 전개도: {count} @msg A joint does not close by {gap} pt. 이음매가 {gap} pt만큼 닫히지 않습니다. @msg Two panels pass through each other. 두 패널이 서로 관통합니다. + +# #5804 native-picked raster editor (draft translations; native review welcome). + Edit Original with: 원본 편집 앱: +file-filter Applications 응용 프로그램 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 58c5dce61b..2008376434 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1121,6 +1121,17 @@ liquify-list-end {0}, {1} {0} en {1} Shading Color Arceringskleur Black Overprint Zwart overprinten Draw Hidden Faces Verborgen vlakken tekenen + Map Art… Artwork toewijzen… + Map Art Artwork toewijzen + First Surface Eerste oppervlak + Previous Surface Vorig oppervlak + Next Surface Volgend oppervlak + Last Surface Laatste oppervlak + Horizontal Scale Horizontale schaal + Vertical Scale Verticale schaal + Scale to Fit Schalen om te passen + Shade Artwork Artwork arceren + Invisible Geometry Onzichtbare geometrie Revolve… Draaien… Inflate… Opblazen… Materials… Materialen… @@ -1232,6 +1243,8 @@ liquify-list-end {0}, {1} {0} en {1} Hide Gradient Annotator Verloopaanduiding verbergen Show Gradient Annotator Verloopaanduiding tonen Hide Corner Widget Hoekwidget verbergen + Hide Shape Widgets Vormwidgets verbergen + Show Shape Widgets Vormwidgets tonen Show Corner Widget Hoekwidget tonen Guides Hulplijnen Hide Guides Hulplijnen verbergen @@ -1351,6 +1364,9 @@ liquify-list-end {0}, {1} {0} en {1} Box Channel Kanaal van het vak Color box Kleurvak Color Wheel Options Opties voor kleurenwiel + Show Harmony Harmonie tonen + Harmony Rule Harmonieregel + Harmony color Harmoniekleur CSS Properties CSS-eigenschappen Document Info Documentinfo Flattener Preview Afvlakvoorbeeld @@ -1582,6 +1598,25 @@ liquify-list-end {0}, {1} {0} en {1} Preserve Embedded Profiles Ingesloten profielen behouden Convert to Working Space Omzetten naar werkruimte Preserve Numbers Waarden behouden + Profile Mismatches: Profielverschillen: + Ask When Opening Vragen bij openen + Ask When Pasting Vragen bij plakken + Missing Profiles: Ontbrekende profielen: + Embedded Profile Mismatch Ingesloten profiel komt niet overeen + Missing Profile Ontbrekend profiel + Paste Profile Mismatch Profielverschil bij plakken + “{name}” is not tagged with a {model} profile. „{name}” heeft geen {model}-profiel. + “{name}” is tagged with the {model} profile “{profile}”, which is not the {model} working space “{working}”. „{name}” heeft het {model}-profiel „{profile}”, dat niet de {model}-werkruimte „{working}” is. + Use the embedded profile Ingesloten profiel gebruiken + Convert the colors to the working space Kleuren omzetten naar de werkruimte + Discard the embedded profile Ingesloten profiel negeren + Leave as is Laten zoals het is + Assign the working space Werkruimte toewijzen + Assign profile: Profiel toewijzen: + Preserve the color numbers Kleurwaarden behouden + Convert to keep the colors' appearance Omzetten zodat de kleuren er hetzelfde uitzien +@msg `{path}` goes with `{key}`: "assign" only `{path}` hoort alleen bij `{key}`: "assign" + The pasted colors come from a document whose {model} profile is “{from}”; this document's is “{to}”. De geplakte kleuren komen uit een document met het {model}-profiel „{from}”; dat van dit document is „{to}”. CMYK CMYK Texture Textuur Craquelure… Craquelure… @@ -1663,6 +1698,15 @@ lighting Light Licht Document Raster Effects Settings Dialog Dialoogvenster rastereffectinstellingen van document Drop Shadow Slagschaduw DXF Options Dialog Dialoogvenster DXF-opties + HP-GL Options HP-GL-opties + HP-GL Options Dialog Dialoogvenster HP-GL-opties + Curve Tolerance: Curvetolerantie: + Origin: Oorsprong: + Pens: Pennen: + One Pen per Color Eén pen per kleur + Pen Table Pennentabel + Draw the Nearest Path Next Het dichtstbijzijnde pad als volgende tekenen + Draw Inner Paths First Binnenste paden eerst tekenen Edit Toolbar Werkbalk bewerken Edit Views Weergaven bewerken Effect… Effect… @@ -2225,6 +2269,7 @@ digits Malayalam Malayalam Roman Baseline Romeinse basislijn Select a text object to edit its character attributes. Selecteer een tekstobject om de tekenkenmerken ervan te bewerken. Show Options Opties tonen + Show on Shape Creation Tonen bij maken van vorm Show Recent Colors Recente kleuren tonen Toggle RGB Percent RGB in procenten wisselen Small Caps Kleine kapitalen @@ -2493,6 +2538,8 @@ digits Malayalam Malayalam Snap Curves To Lines Curves vastzetten op lijnen Tracing Result with Outlines Traceringsresultaat met omlijningen Source Image Bronafbeelding + Split View Gesplitste weergave + Divider Scheidingslijn Threshold Drempel Trace Traceren Trace the image with the Default preset De afbeelding traceren met de standaardvoorinstelling @@ -2617,6 +2664,15 @@ digits Malayalam Malayalam YakumonoZenkaku YakumonoZenkaku Kinsoku Set Kinsoku-set Kinsoku Shori Type Kinsoku Shori-type + Kinsoku Shori Settings… Kinsoku Shori-instellingen… + Kinsoku Shori Settings Kinsoku Shori-instellingen + Kinsoku Sets Kinsoku-sets + Kinsoku Set Base Basis van Kinsoku-set + Based on: Gebaseerd op: + Cannot Start Line Kan regel niet beginnen + Cannot End Line Kan regel niet beëindigen + Hanging Punctuation Hangende interpunctie + Inseparable Characters Onscheidbare tekens Push In First Eerst inschuiven Push Out First Eerst uitschuiven Push Out Only Alleen uitschuiven @@ -3016,6 +3072,12 @@ digits Malayalam Malayalam Units: Eenheden: Use Typographer's Quotes Typografische aanhalingstekens gebruiken Center Artwork Artwork centreren + PSD Import Options PSD-importopties + Place PSD PSD plaatsen + Convert Layers to Objects Lagen omzetten in objecten + Import Hidden Layers Verborgen lagen importeren + Flatten Layers to a Single Image Lagen afvlakken tot één afbeelding + Import Slices Slices importeren DXF Import Options DXF-importopties Layout: Indeling: Merge Layers Lagen samenvoegen @@ -3167,6 +3229,7 @@ digits Malayalam Malayalam Save As Preset… Opslaan als voorinstelling… Save Changes Wijzigingen opslaan Save Preset… Voorinstelling opslaan… + Save Summary… Samenvatting opslaan… Vectors Vectoren A saved copy of the selected preset Een opgeslagen kopie van de geselecteerde voorinstelling Built-in presets don't change: New makes a copy you can edit. Ingebouwde voorinstellingen veranderen niet: Nieuw maakt een kopie die je kunt bewerken. @@ -3400,6 +3463,8 @@ digits Malayalam Malayalam Overprint and Transparency Flattener Options Opties voor overprint en transparantiepletter Custom… Aangepast… Custom Transparency Flattener Options Aangepaste opties voor transparantieafvlakking + The PDF preset keeps the flattener preset but not the Custom… settings. De PDF-voorinstelling bewaart de afvlakvoorinstelling, maar niet de instellingen van Aangepast…. + PDF 1.3 files clip rasterized areas to their regions, and Overprint sets whether overprints are kept. PDF 1.3-bestanden snijden gerasterde gebieden bij tot hun regio's, en Overprint bepaalt of overdrukken behouden blijven. EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS heeft geen alfatransparantie, en Overdrukken bepaalt of overdrukken behouden blijven. Place the pages with the placement again Plaats de pagina's opnieuw met de plaatsing Placement: Plaatsing: @@ -3495,6 +3560,9 @@ digits Malayalam Malayalam Recolor this row Deze rij opnieuw kleuren Reset the rows to the artwork's colors De rijen herstellen naar de kleuren van de artwork Color Theme Picker Kleurthemakiezer + Undo Changes Wijzigingen ongedaan maken + Redo Changes Wijzigingen opnieuw uitvoeren +@msg Recolor Artwork is not open Artwork herkleuren is niet geopend Click or drag across the art to pick its colors; Shift adds more Klik of sleep over het artwork om de kleuren ervan op te nemen; Shift voegt er meer toe Prominent Colors Prominente kleuren Save All Colors Alle kleuren opslaan @@ -3782,6 +3850,17 @@ antiAlias Sharp Scherp Swatch Name: Staalnaam: Diameter: Diameter: Symbolism Tools Options Opties symbolisatiegereedschappen + Tool: Gereedschap: + Symbol Set Density Symboolsetdichtheid + Symbol Sprayer Options Opties voor symboolspuit + Scrunch: Verdichten: + Spin: Roteren: + Screen: Transparantie: + Stain: Kleuren: + Symbol Sizer Options Opties voor symboolgrootte + Proportional Resizing Proportioneel schalen + Resizing Affects Density Schalen beïnvloedt dichtheid + Show Brush Size and Intensity Penseelgrootte en intensiteit tonen Symbol Set Density: Symboolsetdichtheid: Intensity: Intensiteit: Place PDF PDF plaatsen @@ -3842,6 +3921,7 @@ antiAlias Sharp Scherp Width Point Edit Breedtepunt bewerken Art Illustratie Bearing Richting + Stylus Wheel Pennenwiel Bristle Borstel Calligraphic Kalligrafisch Dots Stippen @@ -3976,6 +4056,9 @@ theme Appearance Vormgeving embedding for preview and print insluiten voor voorvertoning en afdrukken embedding allowed insluiten toegestaan {file}; {embedding} {file}; {embedding} + unknown type onbekend type + {type}; {uses} {type}; {uses} +@plural {n} use|{n} uses {n} keer gebruikt|{n} keer gebruikt substituted: shown in {family} {style} ({detail}) vervangen: weergegeven in {family} {style} ({detail}) missing: shown in {family} {style} ontbreekt: weergegeven in {family} {style} missing ontbreekt @@ -4548,6 +4631,7 @@ theme Appearance Vormgeving Show Pixel Grid (Above 600% Zoom) Pixelraster weergeven (boven 600% zoom) Show Slice Numbers Slicenummers weergeven Show The Home Screen When No Documents Are Open Startscherm tonen als er geen documenten geopend zijn + Show Tool Cards Gereedschapskaarten tonen Show Tool Tips Tooltips tonen Size/Leading Tekengrootte/Regelafstand Snapping Tolerance Snapping-tolerantie @@ -4673,6 +4757,8 @@ theme Appearance Vormgeving Spot Colors (0) Spotkleuren (0) Swatch Options Kleurstaalopties Ungroup Color Group Kleurgroep opheffen + Color Group Options Opties voor kleurgroep + Color Group Options… Opties voor kleurgroep… Copy to User Defined Kopiëren naar Gebruikergedefinieerd Swatch Library Bibliotheek met kleurstalen Clear All Tabs Alle tabs wissen @@ -4971,6 +5057,7 @@ font-technology Variable Variabel A live rectangle's properties show one Corner Radius field for all four corners; off, each corner has its own field. De eigenschappen van een dynamische rechthoek tonen één veld Hoekradius voor alle vier hoeken; uitgeschakeld heeft elke hoek een eigen veld. What edits in the Transform panel transform: the object, its pattern tiles or both; Default follows Transform Pattern Tiles. Wat bewerkingen in het deelvenster Transformeren transformeren: het object, de patroontegels ervan of beide; Standaard volgt Patroontegels transformeren. With one symbol instance selected, the Transform panel uses the symbol's registration point as its reference point. Met één symboolinstantie geselecteerd gebruikt het deelvenster Transformeren het registratiepunt van het symbool als referentiepunt. + Drawing a rectangle, ellipse, polygon, star or line opens the Transform panel if it is closed. Als u een rechthoek, ellips, veelhoek, ster of lijn tekent, wordt het deelvenster Transformeren geopend als het gesloten is. Darkens the canvas outside the artboards while the Artboard tool is active. Maakt het canvas buiten de tekenborden donkerder zolang het gereedschap Tekenbord actief is. With Fade Region Outside Artboard on, the area outside the artboards stays dark while you drag with the Artboard tool. Met Gebied buiten tekenbord dimmen aan blijft het gebied buiten de tekenborden donker terwijl u sleept met het gereedschap Tekenbord. How near, in pixels, the pointer must be to an object, anchor or handle for a click to select it. Hoe dicht, in pixels, de aanwijzer bij een object, ankerpunt of greep moet zijn om het met een klik te selecteren. @@ -5065,6 +5152,9 @@ font-technology Variable Variabel Channel Kanaal Circle Cirkel Circle Tool Cirkelgereedschap + Curvature Circle Tool Krommingscirkelgereedschap + Cusp Keerpunt + Straight segment Recht segment Circle too large Cirkel te groot Clip to Art Clippen op artwork Colorize Inkleuren @@ -5448,6 +5538,7 @@ imageTrace Outline Contour @msg a freeform gradient keeps at least one point een verloop met vrije vorm behoudt minstens één punt @msg a gradient needs at least two stops een verloop heeft minstens twee stops nodig @msg a graphic style named `{to}` already exists er bestaat al een grafische stijl met de naam `{to}` +@msg a swatch or color group named `{name}` already exists er bestaat al een kleurstaal of kleurgroep met de naam `{name}` @msg a page is missing er ontbreekt een pagina @msg a page out of range een pagina buiten het bereik @msg a page tree kid isn't a reference een kind van de paginaboom is geen verwijzing @@ -5560,6 +5651,11 @@ imageTrace Outline Contour @msg no anchor points selected geen ankerpunten geselecteerd @msg `points` must be two or three [x, y] pairs of numbers `points` moet uit twee of drie getallenparen [x, y] bestaan @msg direct-select two or three anchor points, or give `points` selecteer met directe selectie twee of drie ankerpunten of geef `points` op +@msg the path is straight there, so no circle matches its curvature het pad is daar recht, dus geen cirkel komt overeen met de kromming ervan +@msg the path has a cusp there, so it has no single curvature het pad heeft daar een keerpunt en dus geen eenduidige kromming +@msg the path has a corner there, so it has no single curvature het pad heeft daar een hoek en dus geen eenduidige kromming +@msg a guide has no curvature circle een hulplijn heeft geen krommingscirkel +@msg the circle that matches the path there would reach past the canvas de cirkel die daar bij het pad past, zou voorbij het canvas reiken @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 @@ -5771,6 +5867,7 @@ imageTrace Outline Contour @msg the PDF is password-protected: give its password de PDF is met een wachtwoord beveiligd: geef het wachtwoord op @msg the PDF password is wrong het PDF-wachtwoord is onjuist @msg the Save PDF dialog didn't open het dialoogvenster PDF opslaan is niet geopend +@msg the Save PDF dialog is not open het dialoogvenster PDF opslaan is niet open @msg the WMF header is damaged de WMF-header is beschadigd @msg the art could not be sampled de illustratie kon niet worden bemonsterd @msg the art has no bounds de illustratie heeft geen begrenzing @@ -5970,6 +6067,7 @@ imageTrace Outline Contour @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 +@msg give only one of `index`, `indices` and `t` geef slechts één van `index`, `indices` en `t` @msg column must be true or a number from 1 column moet true zijn of een getal vanaf 1 @msg x and y must both be numbers x en y moeten allebei getallen zijn @msg "{0}" is not a colour: write it as #rrggbb "{0}" is geen kleur: schrijf het als #rrggbb @@ -6066,6 +6164,49 @@ imageTrace Outline Contour @msg the PSD file's layer groups are nested too deeply de laaggroepen van het PSD-bestand zijn te diep genest @msg a layer of the PSD file is too large to read een laag van het PSD-bestand is te groot om te lezen @msg the PSD file's layers take more memory to read than allowed de lagen van het PSD-bestand hebben meer geheugen nodig om te lezen dan toegestaan +@msg the file is no longer loaded het bestand is niet meer geladen +@msg the layers can't be read ({e}): the file was placed as its merged image de lagen kunnen niet worden gelezen ({e}): het bestand is geplaatst als zijn samengevoegde afbeelding +@msg 1 type layer came in as pixels: the text isn't editable 1 tekstlaag is als pixels binnengekomen: de tekst is niet bewerkbaar +@msg {n} type layers came in as pixels: the text isn't editable {n} tekstlagen zijn als pixels binnengekomen: de tekst is niet bewerkbaar +@msg 1 adjustment layer was not applied 1 aanpassingslaag is niet toegepast +@msg {n} adjustment layers were not applied {n} aanpassingslagen zijn niet toegepast +@msg 1 fill layer was not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels) 1 vullaag is niet getekend (een verloop- of patroonvulling, een kleur die niet kan worden gelezen, of een vorm die geen pixels opslaat) +@msg {n} fill layers were not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels) {n} vullagen zijn niet getekend (een verloop- of patroonvulling, een kleur die niet kan worden gelezen, of een vorm die geen pixels opslaat) +@msg the layer effects of 1 layer weren't drawn de laageffecten van 1 laag zijn niet getekend +@msg the layer effects of {n} layers weren't drawn de laageffecten van {n} lagen zijn niet getekend +@msg the vector masks of 1 layer weren't applied de vectormaskers van 1 laag zijn niet toegepast +@msg the vector masks of {n} layers weren't applied de vectormaskers van {n} lagen zijn niet toegepast +@msg the knockout of 1 layer wasn't applied de uitsparing van 1 laag is niet toegepast +@msg the knockout of {n} layers wasn't applied de uitsparing van {n} lagen is niet toegepast +@msg 1 layer was left out (hidden layers and the layers clipped to them) 1 laag is weggelaten (verborgen lagen en de lagen die erop zijn uitgeknipt) +@msg {n} layers were left out (hidden layers and the layers clipped to them) {n} lagen zijn weggelaten (verborgen lagen en de lagen die erop zijn uitgeknipt) +@msg 1 layer clipped to a fill layer that wasn't drawn was left out 1 laag die is uitgeknipt op een vullaag die niet is getekend, is weggelaten +@msg {n} layers clipped to fill layers that weren't drawn were left out {n} lagen die zijn uitgeknipt op vullagen die niet zijn getekend, zijn weggelaten +@msg layers in blend modes VectorCraft doesn't have ({modes}) were merged with the layers below them lagen in overvloeimodi die VectorCraft niet heeft ({modes}) zijn samengevoegd met de lagen eronder +@msg 1 layer in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed 1 laag in een overvloeimodus die VectorCraft niet heeft, is als Normaal binnengekomen: het samenvoegen vraagt meer geheugen dan toegestaan +@msg {n} layers in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed {n} lagen in overvloeimodi die VectorCraft niet heeft, zijn als Normaal binnengekomen: het samenvoegen vraagt meer geheugen dan toegestaan +@msg 1 layer clipped to the layer below came in unclipped: the merge needs more memory than allowed 1 laag die is uitgeknipt op de laag eronder, is niet uitgeknipt binnengekomen: het samenvoegen vraagt meer geheugen dan toegestaan +@msg {n} layers clipped to the layer below came in unclipped: the merge needs more memory than allowed {n} lagen die zijn uitgeknipt op de laag eronder, zijn niet uitgeknipt binnengekomen: het samenvoegen vraagt meer geheugen dan toegestaan +@msg hiddenLayers applies to a PSD file placed with layers: true hiddenLayers geldt voor een PSD-bestand dat met layers: true wordt geplaatst +@msg importSlices: a linked PSD file is placed as its flat image; give link: false to embed it with its slices importSlices: een gekoppeld PSD-bestand wordt als zijn platte afbeelding geplaatst; geef link: false om het met zijn slices in te sluiten +@msg layers: a linked PSD file is placed as its flat image; leave link out or give link: false layers: een gekoppeld PSD-bestand wordt als zijn platte afbeelding geplaatst; laat link weg of geef link: false +@msg the slices can't be read ({e}) and were left out de slices kunnen niet worden gelezen ({e}) en zijn weggelaten +@msg 1 slice lies outside the canvas or has no size and was left out 1 slice ligt buiten het canvas of heeft geen grootte en is weggelaten +@msg {n} slices lie outside the canvas or have no size and were left out {n} slices liggen buiten het canvas of hebben geen grootte en zijn weggelaten +@msg 1 slice would lie outside the canvas and was left out 1 slice zou buiten het canvas liggen en is weggelaten +@msg {n} slices would lie outside the canvas and were left out {n} slices zouden buiten het canvas liggen en zijn weggelaten +@msg the slices' descriptor holds too many values de descriptor van de slices bevat te veel waarden +@msg the slices' descriptor has a version other than 16 de descriptor van de slices heeft een andere versie dan 16 +@msg the slices are stored in version {v}, which isn't read de slices zijn opgeslagen in versie {v}, die niet wordt gelezen +@msg the file has {count} slices, more than the {MAX_SLICES} read het bestand heeft {count} slices, meer dan de {MAX_SLICES} die worden gelezen +@msg the slices' descriptor has no list of slices de descriptor van de slices heeft geen lijst met slices +@msg the slices' descriptor lists something other than a slice de descriptor van de slices vermeldt iets anders dan een slice +@msg a slice in the slices' descriptor has no bounds een slice in de descriptor van de slices heeft geen grenzen +@msg a slice's bounds in the slices' descriptor aren't numbers de grenzen van een slice in de descriptor van de slices zijn geen getallen +@msg a text in the slices has more than the {MAX_TEXT} characters read een tekst in de slices heeft meer dan de {MAX_TEXT} tekens die worden gelezen +@msg the slices' descriptor nests too deep de descriptor van de slices is te diep genest +@msg the slices' descriptor has a reference of an unknown kind ({_1}) de descriptor van de slices heeft een verwijzing van een onbekende soort ({_1}) +@msg the slices' descriptor has a value of an unknown type ({_1}) de descriptor van de slices heeft een waarde van een onbekend type ({_1}) @msg the layers can't be read ({e}): the file opened as its merged image de lagen kunnen niet worden gelezen ({e}): het bestand is geopend als zijn samengevoegde afbeelding @msg {depth}-bit PSD files in this colour mode can't be read {depth}-bits PSD-bestanden in deze kleurmodus kunnen niet worden gelezen @msg the PSD file is cut short het PSD-bestand is afgekapt @@ -10020,6 +10161,8 @@ breakText Glyphs Glyphs # Path Precision Tools add-on: Tangent Circle. Tangent Circle… Raakcirkel… Tangent Circle Raakcirkel + Tangent Circle Tool Raakcirkel-gereedschap + No tangent circle here Hier geen raakcirkel Circle: Cirkel: @msg `ids` names an object twice `ids` noemt een object twee keer @msg select two or three paths or compound paths selecteer twee of drie paden of samengestelde paden @@ -10035,6 +10178,16 @@ breakText Glyphs Glyphs @msg `circle` is past the last circle found ({found}) `circle` ligt voorbij de laatst gevonden cirkel ({found}) @msg object {value} is not a path or compound path object {value} is geen pad of samengesteld pad @msg these shapes are too small to measure deze vormen zijn te klein om te meten +# Path Precision Tools add-on: Add Bounding Rectangle and Add Bounding Circle. + Add Bounding Rectangle Begrenzingsrechthoek toevoegen + Add Bounding Circle Begrenzingscirkel toevoegen + Add Bounding Rectangle… Begrenzingsrechthoek toevoegen… + Add Bounding Circle… Begrenzingscirkel toevoegen… + One per Object Eén per object +@msg nothing to enclose niets om te omsluiten +@msg `offset` must be 0 or more `offset` moet 0 of meer zijn +@msg the shape would have no size de vorm zou geen grootte hebben +@msg the shape would reach past the edge of the canvas de vorm zou voorbij de rand van het canvas reiken # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Documentgereedschappen Save a Timestamped Copy Een kopie met tijdstempel opslaan @@ -10445,6 +10598,39 @@ breakText Glyphs Glyphs No objects are selected. Er zijn geen objecten geselecteerd. Open a document to mark its fold lines. Open een document om de vouwlijnen te markeren. Remove Fold Line Role Lijnsoort verwijderen +# Tool cards (General › Show Tool Cards): one sentence on what each tool does. + Shows a card with what a toolbar tool does and what its keys do instead of its tip; it needs Show Tool Tips. Toont in plaats van de tooltip een kaart met wat een gereedschap in de werkbalk en zijn toetsen doen; vereist Tooltips tonen. + Selects whole objects and groups to move, resize or rotate them. Selecteert hele objecten en groepen om ze te verplaatsen, te schalen of te draaien. + Selects anchor points and path segments to reshape a path. Selecteert ankerpunten en padsegmenten om de vorm van een pad te wijzigen. + Draws paths point by point, with straight segments and smooth curves. Tekent paden punt voor punt, met rechte segmenten en vloeiende curven. + Draws smooth curves through the points you click. Tekent vloeiende curven door de punten waarop u klikt. + Adds text at a point, or in a frame you drag. Voegt tekst toe op een punt of in een kader dat u sleept. + Draws rectangles and squares. Tekent rechthoeken en vierkanten. + Draws rectangles with rounded corners. Tekent rechthoeken met afgeronde hoeken. + Draws ellipses and circles. Tekent ellipsen en cirkels. + Draws polygons with sides of equal length. Tekent veelhoeken met zijden van gelijke lengte. + Draws stars. Tekent sterren. + Turns objects around a reference point. Draait objecten rond een referentiepunt. + Flips objects across an axis through a reference point. Spiegelt objecten over een as door een referentiepunt. + Resizes objects from a reference point. Schaalt objecten vanaf een referentiepunt. + Slants objects from a reference point. Schuint objecten af vanaf een referentiepunt. + Moves the view of the document. Verschuift de weergave van het document. + Magnifies or reduces the view. Vergroot of verkleint de weergave. + Copies the color and other attributes of one object to the selection. Kopieert de kleur en andere kenmerken van een object naar de selectie. + Sets the direction and length of a gradient. Stelt de richting en lengte van een verloop in. + Creates, selects and resizes artboards. Maakt, selecteert en schaalt tekengebieden. + Changes the width of a stroke along its length. Wijzigt de breedte van een contour over de lengte ervan. + Bends art by dragging pins placed on it. Buigt illustraties door er geplaatste spelden te slepen. + Pushes the outlines of paths in the direction you drag. Duwt de omtrekken van paden in de richting waarin u sleept. + Twists the outlines of paths into swirls. Draait de omtrekken van paden tot wervelingen. + Pulls the outlines of paths in toward the brush. Trekt de omtrekken van paden naar het penseel toe. + Pushes the outlines of paths out from the brush. Duwt de omtrekken van paden van het penseel af naar buiten. + Adds curved details along the outlines of paths. Voegt gebogen details toe langs de omtrekken van paden. + Adds spiky details along the outlines of paths. Voegt puntige details toe langs de omtrekken van paden. + Adds wrinkles along the outlines of paths. Voegt rimpels toe langs de omtrekken van paden. + Moves, copies and resizes objects on the perspective grid. Verplaatst, kopieert en schaalt objecten op het perspectiefraster. + Makes a series of steps between two or more objects. Maakt een reeks stappen tussen twee of meer objecten. + Places dimension lines that show measured lengths. Plaatst maatlijnen die gemeten lengten tonen. Tap Kort drukken Clear Hold Vasthouden wissen Hold Shortcuts Vasthoudsneltoetsen @@ -10475,7 +10661,18 @@ breakText Glyphs Glyphs @msg A panel is not joined to the rest by a crease. Een paneel is door geen rillijn met de rest verbonden. @msg A fold line is on a non-printing layer. Een vouwlijn staat op een laag die niet wordt afgedrukt. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panelen: {panels}, scharnieren: {hinges}, fouten: {errors}, waarschuwingen: {warnings} + Paper Cutouts Papieruitsneden + Coral Layers Koraallagen + Mint Layers Muntlagen + Midnight Layers Middernachtlagen + Sunflower Sheet Zonnebloemvel + Rose Layers Rozenlagen + Monochrome Stack Monochrome stapel Dashed Arrow Gestreepte pijl + Fine Stipple Fijn stippelen + Dense Stipple Dicht stippelen + Soft Stipple Zacht stippelen + Bold Stipple Grof stippelen Pressure Sensitive Drukgevoelig Flex Ribbon Flexibel lint Pulse Stroke Pulserende streek @@ -10491,3 +10688,7 @@ breakText Glyphs Glyphs @msg Other blanks not shown: {count} Andere uitslagen niet getoond: {count} @msg A joint does not close by {gap} pt. Een naad sluit {gap} pt niet. @msg Two panels pass through each other. Twee panelen gaan door elkaar heen. + +# #5804 native-picked raster editor (draft translations; native review welcome). + Edit Original with: Origineel bewerken met: +file-filter Applications Programma’s diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 649bcf3c90..2af48efa05 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -522,6 +522,15 @@ Shading Color Kolor cieniowania Black Overprint Czarny nadruk Draw Hidden Faces Rysuj ukryte ściany + Map Art… Mapuj kompozycję… + Map Art Mapuj kompozycję + First Surface Pierwsza powierzchnia + Previous Surface Poprzednia powierzchnia + Next Surface Następna powierzchnia + Last Surface Ostatnia powierzchnia + Scale to Fit Skaluj, aby dopasować + Shade Artwork Cieniuj kompozycję + Invisible Geometry Niewidoczna geometria Revolve… Obrót… Inflate… Nadmuchanie… Materials… Materiały… @@ -644,6 +653,8 @@ Hide Gradient Annotator Ukryj wskaźnik gradientu Show Gradient Annotator Pokaż wskaźnik gradientu Hide Corner Widget Ukryj widżet narożników + Hide Shape Widgets Ukryj widżety kształtów + Show Shape Widgets Pokaż widżety kształtów Show Corner Widget Pokaż widżet narożników Guides Linie pomocnicze Hide Guides Ukryj linie pomocnicze @@ -756,6 +767,9 @@ Box Channel Kanał kwadratu Color box Kwadrat koloru Color Wheel Options Opcje koła kolorów + Show Harmony Pokaż harmonię + Harmony Rule Reguła harmonii + Harmony color Kolor harmonii CSS Properties Właściwości CSS Document Info Informacje o dokumencie Flattener Preview Podgląd spłaszczania @@ -1001,6 +1015,25 @@ Preserve Embedded Profiles Zachowaj osadzone profile Convert to Working Space Konwertuj do przestrzeni roboczej Preserve Numbers Zachowaj wartości liczbowe + Profile Mismatches: Niezgodność profili: + Ask When Opening Pytaj przy otwieraniu + Ask When Pasting Pytaj przy wklejaniu + Missing Profiles: Brakujące profile: + Embedded Profile Mismatch Niezgodność osadzonego profilu + Missing Profile Brak profilu + Paste Profile Mismatch Niezgodność profilu przy wklejaniu + “{name}” is not tagged with a {model} profile. „{name}” nie ma profilu {model}. + “{name}” is tagged with the {model} profile “{profile}”, which is not the {model} working space “{working}”. „{name}” ma profil {model} „{profile}”, który nie jest przestrzenią roboczą {model} „{working}”. + Use the embedded profile Użyj osadzonego profilu + Convert the colors to the working space Konwertuj kolory do przestrzeni roboczej + Discard the embedded profile Odrzuć osadzony profil + Leave as is Pozostaw bez zmian + Assign the working space Przypisz przestrzeń roboczą + Assign profile: Przypisz profil: + Preserve the color numbers Zachowaj wartości kolorów + Convert to keep the colors' appearance Konwertuj, aby zachować wygląd kolorów +@msg `{path}` goes with `{key}`: "assign" only `{path}` łączy się tylko z `{key}`: "assign" + The pasted colors come from a document whose {model} profile is “{from}”; this document's is “{to}”. Wklejone kolory pochodzą z dokumentu z profilem {model} „{from}”; profil tego dokumentu to „{to}”. CMYK CMYK Texture Tekstura Craquelure… Spękania… @@ -1083,6 +1116,15 @@ lighting Light Światło Document Raster Effects Settings Dialog Okno ustawień efektów rastrowych dokumentu Drop Shadow Cień DXF Options Dialog Okno opcji DXF + HP-GL Options Opcje HP-GL + HP-GL Options Dialog Okno opcji HP-GL + Curve Tolerance: Tolerancja krzywych: + Origin: Początek układu: + Pens: Pisaki: + One Pen per Color Jeden pisak na kolor + Pen Table Tabela pisaków + Draw the Nearest Path Next Rysuj następnie najbliższą ścieżkę + Draw Inner Paths First Najpierw rysuj ścieżki wewnętrzne Edit Toolbar Edytuj pasek narzędzi Edit Views Edytuj widoki Effect… Efekt… @@ -1639,6 +1681,7 @@ digits Malayalam Malajalam Roman Baseline Linia bazowa łacińska Select a text object to edit its character attributes. Zaznacz obiekt tekstowy, aby edytować atrybuty znaków. Show Options Pokaż opcje + Show on Shape Creation Pokaż przy tworzeniu kształtu Show Recent Colors Pokaż ostatnie kolory Toggle RGB Percent Przełącz RGB w procentach Color Panel Options Opcje panelu Kolor @@ -1995,6 +2038,8 @@ digits Malayalam Malajalam Snap Curves To Lines Przyciągaj krzywe do linii Tracing Result with Outlines Wynik obrysu z konturami Source Image Obraz źródłowy + Split View Widok podzielony + Divider Linia podziału Threshold Próg Trace Obrysuj Trace the image with the Default preset Obrysuj obraz ustawieniem Domyślne @@ -2142,6 +2187,15 @@ digits Malayalam Malajalam YakumonoZenkaku YakumonoZenkaku Kinsoku Set Zestaw kinsoku Kinsoku Shori Type Typ kinsoku shori + Kinsoku Shori Settings… Ustawienia kinsoku shori… + Kinsoku Shori Settings Ustawienia kinsoku shori + Kinsoku Sets Zestawy kinsoku + Kinsoku Set Base Podstawa zestawu kinsoku + Based on: Na podstawie: + Cannot Start Line Nie może zaczynać wiersza + Cannot End Line Nie może kończyć wiersza + Hanging Punctuation Wisząca interpunkcja + Inseparable Characters Znaki nierozdzielne Push In First Najpierw wciągaj Push Out First Najpierw wypychaj Push Out Only Tylko wypychaj @@ -2543,6 +2597,12 @@ digits Malayalam Malajalam Units: Jednostki: Use Typographer's Quotes Używaj cudzysłowów drukarskich Center Artwork Wyśrodkuj kompozycję + PSD Import Options Opcje importu PSD + Place PSD Umieść PSD + Convert Layers to Objects Konwertuj warstwy na obiekty + Import Hidden Layers Importuj ukryte warstwy + Flatten Layers to a Single Image Spłaszcz warstwy do jednego obrazu + Import Slices Importuj plasterki DXF Import Options Opcje importu DXF Layout: Układ: Merge Layers Scal warstwy @@ -2698,6 +2758,7 @@ digits Malayalam Malajalam Save As Preset… Zapisz jako ustawienie predefiniowane… Save Changes Zapisz zmiany Save Preset… Zapisz ustawienie… + Save Summary… Zapisz podsumowanie… Vectors Wektory A saved copy of the selected preset Zapisana kopia zaznaczonego ustawienia Built-in presets don't change: New makes a copy you can edit. Wbudowanych ustawień nie można zmieniać: Nowe tworzy edytowalną kopię. @@ -2940,6 +3001,8 @@ digits Malayalam Malajalam Overprint and Transparency Flattener Options Opcje nadruku i spłaszczania przezroczystości Custom… Niestandardowe… Custom Transparency Flattener Options Niestandardowe opcje spłaszczania przezroczystości + The PDF preset keeps the flattener preset but not the Custom… settings. Ustawienie PDF zachowuje ustawienie spłaszczania, ale nie ustawienia z Niestandardowe…. + PDF 1.3 files clip rasterized areas to their regions, and Overprint sets whether overprints are kept. Pliki PDF 1.3 przycinają rasteryzowane obszary do ich regionów, a Nadruk określa, czy nadruki są zachowywane. EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS nie ma przezroczystości alfa, a Nadruki określają, czy nadruki są zachowywane. Place the pages with the placement again Ponownie rozmieść strony według położenia Placement: Położenie: @@ -3031,6 +3094,9 @@ digits Malayalam Malajalam Recolor this row Zmień kolory tego wiersza Reset the rows to the artwork's colors Przywróć w wierszach kolory kompozycji Color Theme Picker Próbnik motywu kolorów + Undo Changes Cofnij zmiany + Redo Changes Ponów zmiany +@msg Recolor Artwork is not open Okno Zmień kolory kompozycji nie jest otwarte Click or drag across the art to pick its colors; Shift adds more Kliknij lub przeciągnij po kompozycji, aby pobrać jej kolory; Shift dodaje kolejne Prominent Colors Dominujące kolory Save All Colors Zapisz wszystkie kolory @@ -3293,6 +3359,17 @@ antiAlias Sharp Ostre Swatch Name: Nazwa próbki: Diameter: Średnica: Symbolism Tools Options Opcje narzędzi symboli + Tool: Narzędzie: + Symbol Set Density Gęstość zestawu symboli + Symbol Sprayer Options Opcje rozpylania symboli + Scrunch: Zagęszczanie: + Spin: Obracanie: + Screen: Przesłanianie: + Stain: Barwienie: + Symbol Sizer Options Opcje skalowania symboli + Proportional Resizing Skalowanie proporcjonalne + Resizing Affects Density Skalowanie wpływa na gęstość + Show Brush Size and Intensity Pokaż rozmiar i natężenie pędzla Symbol Set Density: Gęstość zestawu symboli: Intensity: Natężenie: Place PDF Umieść PDF @@ -3386,6 +3463,7 @@ antiAlias Sharp Ostre Width Point Edit Edycja punktu szerokości Art Artystyczny Bearing Kierunek + Stylus Wheel Kółko pióra Bristle Włosiankowy Calligraphic Kaligraficzny Dots Kropki @@ -3531,6 +3609,9 @@ theme Appearance Wygląd embedding for preview and print osadzanie do podglądu i drukowania embedding allowed osadzanie dozwolone {file}; {embedding} {file}; {embedding} + unknown type nieznany typ + {type}; {uses} {type}; {uses} +@plural {n} use|{n} uses {n} użycie|{n} użycia|{n} użyć substituted: shown in {family} {style} ({detail}) zastąpiony: wyświetlany krojem {family} {style} ({detail}) missing: shown in {family} {style} brak: wyświetlany krojem {family} {style} missing brak @@ -4110,6 +4191,7 @@ theme Appearance Wygląd Show Pixel Grid (Above 600% Zoom) Pokaż siatkę pikseli (powyżej 600%) Show Slice Numbers Pokaż numery plasterków Show The Home Screen When No Documents Are Open Pokaż ekran startowy, gdy nie ma otwartych dokumentów + Show Tool Cards Pokaż karty narzędzi Show Tool Tips Pokaż podpowiedzi Size/Leading Rozmiar/interlinia Snapping Tolerance Tolerancja przyciągania @@ -4231,6 +4313,8 @@ theme Appearance Wygląd Spot Colors Kolory dodatkowe Swatch Options Opcje próbki Ungroup Color Group Rozgrupuj grupę kolorów + Color Group Options Opcje grupy kolorów + Color Group Options… Opcje grupy kolorów… Copy to User Defined Kopiuj do zdefiniowanych przez użytkownika Swatch Library Biblioteka próbek Clear All Tabs Usuń wszystkie tabulatory @@ -4522,6 +4606,7 @@ font-technology Variable Zmienne 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. With one symbol instance selected, the Transform panel uses the symbol's registration point as its reference point. Gdy zaznaczone jest jedno wystąpienie symbolu, panel Przekształć używa punktu rejestracji symbolu jako punktu odniesienia. + Drawing a rectangle, ellipse, polygon, star or line opens the Transform panel if it is closed. Narysowanie prostokąta, elipsy, wielokąta, gwiazdy lub linii otwiera panel Przekształć, jeśli jest zamknięty. Darkens the canvas outside the artboards while the Artboard tool is active. Przyciemnia obszar roboczy poza obszarami kompozycji, gdy aktywne jest narzędzie Obszar kompozycji. With Fade Region Outside Artboard on, the area outside the artboards stays dark while you drag with the Artboard tool. Gdy włączone jest Przyciemnij obszar poza obszarem kompozycji, obszar poza obszarami kompozycji pozostaje ciemny podczas przeciągania narzędziem Obszar kompozycji. How near, in pixels, the pointer must be to an object, anchor or handle for a click to select it. Jak blisko, w pikselach, wskaźnik musi być od obiektu, punktu kontrolnego lub uchwytu, aby kliknięcie go zaznaczyło. @@ -4616,6 +4701,9 @@ font-technology Variable Zmienne Channel Kanał Circle Okrąg Circle Tool Narzędzie Okrąg + Curvature Circle Tool Narzędzie Okrąg krzywizny + Cusp Ostrze + Straight segment Prosty segment Circle too large Okrąg jest za duży Clip to Art Przytnij do kompozycji Colorize Koloruj @@ -5186,6 +5274,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg a freeform gradient keeps at least one point gradient dowolny musi mieć co najmniej jeden punkt @msg a gradient needs at least two stops gradient potrzebuje co najmniej dwóch punktów koloru @msg a graphic style named `{to}` already exists styl graficzny o nazwie `{to}` już istnieje +@msg a swatch or color group named `{name}` already exists próbka lub grupa kolorów o nazwie `{name}` już istnieje @msg a key object sits on that point w tym punkcie leży obiekt kluczowy @msg a page is missing brak strony @msg a page out of range strona spoza zakresu @@ -5327,6 +5416,11 @@ liquify-list-end {0}, {1} {0} i {1} @msg no anchor points selected nie zaznaczono punktów kontrolnych @msg `points` must be two or three [x, y] pairs of numbers `points` musi zawierać dwie lub trzy pary liczb [x, y] @msg direct-select two or three anchor points, or give `points` zaznacz bezpośrednio dwa lub trzy punkty kontrolne lub podaj `points` +@msg the path is straight there, so no circle matches its curvature ścieżka jest w tym miejscu prosta, więc żaden okrąg nie pasuje do jej krzywizny +@msg the path has a cusp there, so it has no single curvature ścieżka ma w tym miejscu ostrze, więc nie ma jednej krzywizny +@msg the path has a corner there, so it has no single curvature ścieżka ma w tym miejscu narożnik, więc nie ma jednej krzywizny +@msg a guide has no curvature circle linia pomocnicza nie ma okręgu krzywizny +@msg the circle that matches the path there would reach past the canvas okrąg pasujący w tym miejscu do ścieżki wykroczyłby poza płótno @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 @@ -5585,6 +5679,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg the PDF is password-protected: give its password PDF jest chroniony hasłem: podaj hasło @msg the PDF password is wrong hasło PDF jest nieprawidłowe @msg the Save PDF dialog didn't open okno Zapisz PDF nie otworzyło się +@msg the Save PDF dialog is not open okno Zapisz PDF nie jest otwarte @msg the WMF header is damaged nagłówek WMF jest uszkodzony @msg the art could not be sampled nie udało się pobrać próbki kompozycji @msg the art has no bounds kompozycja nie ma granic @@ -5808,6 +5903,7 @@ variable-list-end {0}, {1} {0} i {1} @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 +@msg give only one of `index`, `indices` and `t` podaj tylko jedno z: `index`, `indices`, `t` @msg column must be true or a number from 1 column musi mieć wartość true lub liczbę od 1 @msg x and y must both be numbers x i y muszą być liczbami @msg "{0}" is not a colour: write it as #rrggbb "{0}" nie jest kolorem: zapisz go jako #rrggbb @@ -5925,6 +6021,49 @@ variable-list-end {0}, {1} {0} i {1} @msg the PSD file's layer groups are nested too deeply grupy warstw pliku PSD są zagnieżdżone zbyt głęboko @msg a layer of the PSD file is too large to read warstwa pliku PSD jest zbyt duża, aby ją odczytać @msg the PSD file's layers take more memory to read than allowed odczytanie warstw pliku PSD wymaga więcej pamięci, niż jest dozwolone +@msg the file is no longer loaded plik nie jest już wczytany +@msg the layers can't be read ({e}): the file was placed as its merged image nie można odczytać warstw ({e}): plik umieszczono jako jego scalony obraz +@msg 1 type layer came in as pixels: the text isn't editable 1 warstwa tekstowa została wczytana jako piksele: tekstu nie można edytować +@msg {n} type layers came in as pixels: the text isn't editable warstwy tekstowe wczytane jako piksele: {n}; tekstu nie można edytować +@msg 1 adjustment layer was not applied 1 warstwa dopasowania nie została zastosowana +@msg {n} adjustment layers were not applied niezastosowane warstwy dopasowania: {n} +@msg 1 fill layer was not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels) 1 warstwa wypełnienia nie została narysowana (wypełnienie gradientem lub wzorkiem, kolor, którego nie można odczytać, albo kształt bez zapisanych pikseli) +@msg {n} fill layers were not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels) nienarysowane warstwy wypełnienia: {n} (wypełnienie gradientem lub wzorkiem, kolor, którego nie można odczytać, albo kształt bez zapisanych pikseli) +@msg the layer effects of 1 layer weren't drawn efekty warstwy 1 warstwy nie zostały narysowane +@msg the layer effects of {n} layers weren't drawn efekty warstw nie zostały narysowane; liczba warstw: {n} +@msg the vector masks of 1 layer weren't applied maski wektorowe 1 warstwy nie zostały zastosowane +@msg the vector masks of {n} layers weren't applied maski wektorowe warstw nie zostały zastosowane; liczba warstw: {n} +@msg the knockout of 1 layer wasn't applied wycięcie 1 warstwy nie zostało zastosowane +@msg the knockout of {n} layers wasn't applied wycięcie warstw nie zostało zastosowane; liczba warstw: {n} +@msg 1 layer was left out (hidden layers and the layers clipped to them) 1 warstwa została pominięta (ukryte warstwy i warstwy do nich przycięte) +@msg {n} layers were left out (hidden layers and the layers clipped to them) pominięte warstwy: {n} (ukryte warstwy i warstwy do nich przycięte) +@msg 1 layer clipped to a fill layer that wasn't drawn was left out 1 warstwa przycięta do nienarysowanej warstwy wypełnienia została pominięta +@msg {n} layers clipped to fill layers that weren't drawn were left out pominięte warstwy przycięte do nienarysowanych warstw wypełnienia: {n} +@msg layers in blend modes VectorCraft doesn't have ({modes}) were merged with the layers below them warstwy w trybach mieszania, których VectorCraft nie ma ({modes}), zostały scalone z warstwami pod nimi +@msg 1 layer in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed 1 warstwa w trybie mieszania, którego VectorCraft nie ma, została wczytana jako Normalny: scalenie wymaga więcej pamięci, niż dozwolono +@msg {n} layers in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed warstwy w trybach mieszania, których VectorCraft nie ma, wczytane jako Normalny: {n}; scalenie wymaga więcej pamięci, niż dozwolono +@msg 1 layer clipped to the layer below came in unclipped: the merge needs more memory than allowed 1 warstwa przycięta do warstwy poniżej została wczytana bez przycięcia: scalenie wymaga więcej pamięci, niż dozwolono +@msg {n} layers clipped to the layer below came in unclipped: the merge needs more memory than allowed warstwy przycięte do warstwy poniżej wczytane bez przycięcia: {n}; scalenie wymaga więcej pamięci, niż dozwolono +@msg hiddenLayers applies to a PSD file placed with layers: true hiddenLayers dotyczy pliku PSD umieszczanego z layers: true +@msg importSlices: a linked PSD file is placed as its flat image; give link: false to embed it with its slices importSlices: połączony plik PSD jest umieszczany jako jego spłaszczony obraz; podaj link: false, aby osadzić go z plasterkami +@msg layers: a linked PSD file is placed as its flat image; leave link out or give link: false layers: połączony plik PSD jest umieszczany jako jego spłaszczony obraz; pomiń link lub podaj link: false +@msg the slices can't be read ({e}) and were left out nie można odczytać plasterków ({e}), więc je pominięto +@msg 1 slice lies outside the canvas or has no size and was left out 1 plasterek leży poza obszarem roboczym lub nie ma rozmiaru i został pominięty +@msg {n} slices lie outside the canvas or have no size and were left out pominięte plasterki leżące poza obszarem roboczym lub bez rozmiaru: {n} +@msg 1 slice would lie outside the canvas and was left out 1 plasterek leżałby poza obszarem roboczym i został pominięty +@msg {n} slices would lie outside the canvas and were left out pominięte plasterki, które leżałyby poza obszarem roboczym: {n} +@msg the slices' descriptor holds too many values deskryptor plasterków zawiera zbyt wiele wartości +@msg the slices' descriptor has a version other than 16 deskryptor plasterków ma wersję inną niż 16 +@msg the slices are stored in version {v}, which isn't read plasterki są zapisane w wersji {v}, która nie jest odczytywana +@msg the file has {count} slices, more than the {MAX_SLICES} read liczba plasterków w pliku wynosi {count}, więcej niż odczytywane {MAX_SLICES} +@msg the slices' descriptor has no list of slices deskryptor plasterków nie ma listy plasterków +@msg the slices' descriptor lists something other than a slice deskryptor plasterków wymienia coś innego niż plasterek +@msg a slice in the slices' descriptor has no bounds plasterek w deskryptorze plasterków nie ma granic +@msg a slice's bounds in the slices' descriptor aren't numbers granice plasterka w deskryptorze plasterków nie są liczbami +@msg a text in the slices has more than the {MAX_TEXT} characters read tekst w plasterkach ma więcej niż odczytywane {MAX_TEXT} znaków +@msg the slices' descriptor nests too deep deskryptor plasterków jest zagnieżdżony zbyt głęboko +@msg the slices' descriptor has a reference of an unknown kind ({_1}) deskryptor plasterków ma odwołanie nieznanego rodzaju ({_1}) +@msg the slices' descriptor has a value of an unknown type ({_1}) deskryptor plasterków ma wartość nieznanego typu ({_1}) @msg the layers can't be read ({e}): the file opened as its merged image nie można odczytać warstw ({e}): plik otwarto jako jego scalony obraz @msg {depth}-bit PSD files in this colour mode can't be read nie można odczytać {depth}-bitowych plików PSD w tym trybie koloru @msg the PSD file is cut short plik PSD jest ucięty @@ -7985,6 +8124,8 @@ breakText Glyphs Glify # Path Precision Tools add-on: Tangent Circle. Tangent Circle… Okrąg styczny… Tangent Circle Okrąg styczny + Tangent Circle Tool Narzędzie Okrąg styczny + No tangent circle here Brak okręgu stycznego w tym miejscu Circle: Okrąg: @msg `ids` names an object twice `ids` wskazuje ten sam obiekt dwa razy @msg select two or three paths or compound paths zaznacz dwie lub trzy ścieżki lub ścieżki złożone @@ -8000,6 +8141,16 @@ breakText Glyphs Glify @msg `circle` is past the last circle found ({found}) `circle` wykracza poza ostatni znaleziony okrąg ({found}) @msg object {value} is not a path or compound path obiekt {value} nie jest ścieżką ani ścieżką złożoną @msg these shapes are too small to measure te kształty są za małe, aby je zmierzyć +# Path Precision Tools add-on: Add Bounding Rectangle and Add Bounding Circle. + Add Bounding Rectangle Dodaj prostokąt otaczający + Add Bounding Circle Dodaj okrąg otaczający + Add Bounding Rectangle… Dodaj prostokąt otaczający… + Add Bounding Circle… Dodaj okrąg otaczający… + One per Object Jeden na obiekt +@msg nothing to enclose nie ma czego otoczyć +@msg `offset` must be 0 or more `offset` musi wynosić 0 lub więcej +@msg the shape would have no size kształt nie miałby rozmiaru +@msg the shape would reach past the edge of the canvas kształt wykroczyłby poza krawędź płótna # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Narzędzia dokumentu Save a Timestamped Copy Zapisz kopię z datą i godziną @@ -10271,6 +10422,39 @@ breakText Glyphs Glify No objects are selected. Nie zaznaczono żadnych obiektów. Open a document to mark its fold lines. Otwórz dokument, aby oznaczyć jego linie zgięcia. Remove Fold Line Role Usuń rodzaj linii +# Tool cards (General › Show Tool Cards): one sentence on what each tool does. + Shows a card with what a toolbar tool does and what its keys do instead of its tip; it needs Show Tool Tips. Zamiast podpowiedzi pokazuje kartę z tym, co robią narzędzie z paska i jego klawisze; wymaga opcji Pokaż podpowiedzi. + Selects whole objects and groups to move, resize or rotate them. Zaznacza całe obiekty i grupy, aby je przesuwać, skalować lub obracać. + Selects anchor points and path segments to reshape a path. Zaznacza punkty kontrolne i segmenty ścieżki, aby zmienić kształt ścieżki. + Draws paths point by point, with straight segments and smooth curves. Rysuje ścieżki punkt po punkcie, z prostymi segmentami i gładkimi krzywymi. + Draws smooth curves through the points you click. Rysuje gładkie krzywe przechodzące przez klikane punkty. + Adds text at a point, or in a frame you drag. Dodaje tekst w punkcie lub w przeciągniętej ramce. + Draws rectangles and squares. Rysuje prostokąty i kwadraty. + Draws rectangles with rounded corners. Rysuje prostokąty z zaokrąglonymi narożnikami. + Draws ellipses and circles. Rysuje elipsy i okręgi. + Draws polygons with sides of equal length. Rysuje wielokąty o bokach równej długości. + Draws stars. Rysuje gwiazdy. + Turns objects around a reference point. Obraca obiekty wokół punktu odniesienia. + Flips objects across an axis through a reference point. Odbija obiekty względem osi przechodzącej przez punkt odniesienia. + Resizes objects from a reference point. Skaluje obiekty względem punktu odniesienia. + Slants objects from a reference point. Pochyla obiekty względem punktu odniesienia. + Moves the view of the document. Przesuwa widok dokumentu. + Magnifies or reduces the view. Powiększa lub pomniejsza widok. + Copies the color and other attributes of one object to the selection. Kopiuje kolor i inne atrybuty jednego obiektu do zaznaczenia. + Sets the direction and length of a gradient. Ustawia kierunek i długość gradientu. + Creates, selects and resizes artboards. Tworzy, zaznacza i skaluje obszary kompozycji. + Changes the width of a stroke along its length. Zmienia szerokość obrysu wzdłuż jego długości. + Bends art by dragging pins placed on it. Wygina kompozycję przez przeciąganie umieszczonych na niej pinezek. + Pushes the outlines of paths in the direction you drag. Przesuwa kontury ścieżek w kierunku przeciągania. + Twists the outlines of paths into swirls. Skręca kontury ścieżek w wiry. + Pulls the outlines of paths in toward the brush. Ściąga kontury ścieżek do pędzla. + Pushes the outlines of paths out from the brush. Wypycha kontury ścieżek na zewnątrz od pędzla. + Adds curved details along the outlines of paths. Dodaje zaokrąglone detale wzdłuż konturów ścieżek. + Adds spiky details along the outlines of paths. Dodaje kolczaste detale wzdłuż konturów ścieżek. + Adds wrinkles along the outlines of paths. Dodaje zmarszczki wzdłuż konturów ścieżek. + Moves, copies and resizes objects on the perspective grid. Przesuwa, kopiuje i skaluje obiekty na siatce perspektywy. + Makes a series of steps between two or more objects. Tworzy serię kroków między dwoma lub więcej obiektami. + Places dimension lines that show measured lengths. Umieszcza linie wymiarowe pokazujące zmierzone długości. Tap Krótkie naciśnięcie Clear Hold Wyczyść przytrzymanie Hold Shortcuts Skróty przytrzymania @@ -10301,7 +10485,18 @@ breakText Glyphs Glify @msg A panel is not joined to the rest by a crease. Panel nie jest połączony z resztą żadną linią bigowania. @msg A fold line is on a non-printing layer. Linia zgięcia znajduje się na warstwie niedrukowanej. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panele: {panels}, zawiasy: {hinges}, błędy: {errors}, ostrzeżenia: {warnings} + Paper Cutouts Wycinanki papierowe + Coral Layers Warstwy koralowe + Mint Layers Warstwy miętowe + Midnight Layers Warstwy północy + Sunflower Sheet Arkusz słonecznika + Rose Layers Warstwy różowe + Monochrome Stack Monochromatyczny stos Dashed Arrow Przerywana strzałka + Fine Stipple Drobne kropkowanie + Dense Stipple Gęste kropkowanie + Soft Stipple Miękkie kropkowanie + Bold Stipple Grube kropkowanie Pressure Sensitive Czułe na nacisk Flex Ribbon Elastyczna wstążka Pulse Stroke Pulsujące pociągnięcie @@ -10317,3 +10512,7 @@ breakText Glyphs Glify @msg Other blanks not shown: {count} Inne wykroje nie są pokazane: {count} @msg A joint does not close by {gap} pt. Połączenie nie domyka się o {gap} pt. @msg Two panels pass through each other. Dwa panele przechodzą przez siebie. + +# #5804 native-picked raster editor (draft translations; native review welcome). + Edit Original with: Edytuj oryginał w: +file-filter Applications Aplikacje diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a5a1533cbb..2c9cd7db95 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -465,6 +465,9 @@ antiAlias Sharp Nítido Choose… Escolher… Circle Círculo Circle Tool Ferramenta Círculo + Curvature Circle Tool Ferramenta Círculo de curvatura + Cusp Cúspide + Straight segment Segmento reto Circle too large Círculo grande demais Clean Up… Limpar… Clear Limpar @@ -544,6 +547,9 @@ antiAlias Sharp Nítido Box Channel Canal da Caixa Color box Caixa de cor Color Wheel Options Opções da Roda de Cores + Show Harmony Mostrar Harmonia + Harmony Rule Regra de Harmonia + Harmony color Cor da harmonia Color Type: Tipo de Cor: Color blindness – Deuteranopia-type Daltonismo – tipo deuteranopia Color blindness – Protanopia-type Daltonismo – tipo protanopia @@ -720,10 +726,25 @@ antiAlias Sharp Nítido Customize… Personalizar… Cut Recortar Cut Path at Selected Anchor Points Cortar Caminho nos Pontos de Ancoragem Selecionados + PSD Import Options Opções de Importação PSD + Place PSD Colocar PSD + Convert Layers to Objects Converter Camadas em Objetos + Import Hidden Layers Importar Camadas Ocultas + Flatten Layers to a Single Image Achatar Camadas em uma Única Imagem + Import Slices Importar Fatias DXF Import Options Opções de Importação DXF DXF Info Informações DXF DXF Options Opções DXF DXF Options Dialog Diálogo de Opções DXF + HP-GL Options Opções HP-GL + HP-GL Options Dialog Diálogo de Opções HP-GL + Curve Tolerance: Tolerância das curvas: + Origin: Origem: + Pens: Canetas: + One Pen per Color Uma caneta por cor + Pen Table Tabela de canetas + Draw the Nearest Path Next Desenhar em seguida o caminho mais próximo + Draw Inner Paths First Desenhar primeiro os caminhos internos Dark Escuro Darken Escurecer Dashed Tracejado @@ -1160,6 +1181,15 @@ antiAlias Sharp Nítido Shading Color Cor do Sombreamento Black Overprint Preto em Sobreimpressão Draw Hidden Faces Desenhar Faces Ocultas + Map Art… Mapear Ilustração… + Map Art Mapear Ilustração + First Surface Primeira Superfície + Previous Surface Superfície Anterior + Next Surface Próxima Superfície + Last Surface Última Superfície + Scale to Fit Dimensionar para Caber + Shade Artwork Sombrear Ilustração + Invisible Geometry Geometria Invisível Eyedropper Conta-gotas Eyedropper Applies: O Conta-gotas Aplica: Eyedropper Options Opções do Conta-gotas @@ -1451,6 +1481,8 @@ antiAlias Sharp Nítido More Options Mais Opções Show Properties Panel Mostrar Painel Propriedades Hide Corner Widget Ocultar Widget de Canto + Hide Shape Widgets Ocultar Widgets de Forma + Show Shape Widgets Mostrar Widgets de Forma Hide Corner Widget for angles greater than Ocultar Widget de Canto para ângulos maiores que Hide Edges Ocultar Bordas Hide Gradient Annotator Ocultar Anotador de Gradiente @@ -1938,6 +1970,9 @@ antiAlias Sharp Nítido embedding for preview and print incorporação para visualização e impressão embedding allowed incorporação permitida {file}; {embedding} {file}; {embedding} + unknown type tipo desconhecido + {type}; {uses} {type}; {uses} +@plural {n} use|{n} uses {n} uso|{n} usos substituted: shown in {family} {style} ({detail}) substituída: exibida em {family} {style} ({detail}) missing: shown in {family} {style} ausente: exibida em {family} {style} missing ausente @@ -2188,6 +2223,8 @@ antiAlias Sharp Nítido Overprint and Transparency Flattener Options Opções de Sobreimpressão e Achatamento de Transparência Custom… Personalizado… Custom Transparency Flattener Options Opções Personalizadas de Achatamento de Transparência + The PDF preset keeps the flattener preset but not the Custom… settings. O predefinido PDF mantém o predefinido de achatamento, mas não as configurações de Personalizado…. + PDF 1.3 files clip rasterized areas to their regions, and Overprint sets whether overprints are kept. Arquivos PDF 1.3 recortam as áreas rasterizadas às suas regiões, e Sobreimpressão define se as sobreimpressões são mantidas. EPS has no alpha transparency, and Overprints sets whether overprints are kept. O EPS não tem transparência alfa, e Sobreimpressões define se as sobreimpressões são mantidas. Overprint: Sobreimpressão: Overprints: Sobreimpressões: @@ -2643,6 +2680,9 @@ digits Malayalam Malaiala Rotate View to Selection Girar Visualização para a Seleção Reset the rows to the artwork's colors Redefinir as linhas para as cores da arte Color Theme Picker Seletor de Tema de Cores + Undo Changes Desfazer Alterações + Redo Changes Refazer Alterações +@msg Recolor Artwork is not open Recolorir Arte não está aberto Click or drag across the art to pick its colors; Shift adds more Clique ou arraste sobre a arte para pegar suas cores; Shift adiciona mais Prominent Colors Cores Proeminentes Save All Colors Salvar Todas as Cores @@ -2695,6 +2735,7 @@ digits Malayalam Malaiala A live rectangle's properties show one Corner Radius field for all four corners; off, each corner has its own field. As propriedades de um retângulo dinâmico mostram um só campo Raio do Canto para os quatro cantos; desativada, cada canto tem seu próprio campo. What edits in the Transform panel transform: the object, its pattern tiles or both; Default follows Transform Pattern Tiles. O que as edições no painel Transformar transformam: o objeto, seus blocos de padrão ou ambos; Padrão segue Transformar Blocos de Padrão. With one symbol instance selected, the Transform panel uses the symbol's registration point as its reference point. Com uma instância de símbolo selecionada, o painel Transformar usa o ponto de registro do símbolo como ponto de referência. + Drawing a rectangle, ellipse, polygon, star or line opens the Transform panel if it is closed. Desenhar um retângulo, uma elipse, um polígono, uma estrela ou uma linha abre o painel Transformar se ele estiver fechado. Darkens the canvas outside the artboards while the Artboard tool is active. Escurece a tela fora das pranchetas enquanto a ferramenta Prancheta está ativa. With Fade Region Outside Artboard on, the area outside the artboards stays dark while you drag with the Artboard tool. Com Escurecer Região Fora da Prancheta ativado, a área fora das pranchetas continua escura enquanto você arrasta com a ferramenta Prancheta. How near, in pixels, the pointer must be to an object, anchor or handle for a click to select it. Quão perto, em pixels, o ponteiro precisa estar de um objeto, ponto de ancoragem ou alça para que um clique o selecione. @@ -2862,6 +2903,7 @@ digits Malayalam Malaiala Save Preset Salvar Predefinido Save Document Preset Salvar Predefinido de Documento Save Preset… Salvar Predefinido… + Save Summary… Salvar Resumo… Save Print Preset Salvar Predefinido de Impressão Save Recovery Data Salvar Dados de Recuperação Save Save for Web Preset Salvar Predefinido de Salvar para Web @@ -3120,6 +3162,7 @@ digits Malayalam Malaiala Show List View Mostrar Exibição de Lista Show Note Mostrar Nota Show Options Mostrar Opções + Show on Shape Creation Mostrar ao Criar Formas Show Recent Colors Mostrar Cores Recentes Toggle RGB Percent Alternar RGB em Porcentagem Show Original Path Mostrar Caminho Original @@ -3145,6 +3188,7 @@ digits Malayalam Malaiala Show Thumbnails Mostrar Miniaturas Show Tile Edge Mostrar Borda do Bloco Show Tints/Shades Mostrar Tons/Sombras + Show Tool Cards Mostrar Cartões de Ferramenta Show Tool Tips Mostrar Dicas de Ferramenta Show Transparency Grid Mostrar Grade de Transparência Show Video Rulers Mostrar Réguas de Vídeo @@ -3495,6 +3539,8 @@ digits Malayalam Malaiala Unembed… Desincorporar… Ungroup Desagrupar Ungroup Color Group Desagrupar Grupo de Cores + Color Group Options Opções de Grupo de Cores + Color Group Options… Opções de Grupo de Cores… Uniform Uniforme Unite Unir Units Unidades @@ -3805,6 +3851,25 @@ imageTrace Outline Contorno Preserve Embedded Profiles Preservar perfis incorporados Convert to Working Space Converter para espaço de trabalho Preserve Numbers Preservar números + Profile Mismatches: Incompatibilidades de perfil: + Ask When Opening Perguntar ao abrir + Ask When Pasting Perguntar ao colar + Missing Profiles: Perfis ausentes: + Embedded Profile Mismatch Incompatibilidade do perfil incorporado + Missing Profile Perfil ausente + Paste Profile Mismatch Incompatibilidade de perfil ao colar + “{name}” is not tagged with a {model} profile. “{name}” não tem um perfil {model}. + “{name}” is tagged with the {model} profile “{profile}”, which is not the {model} working space “{working}”. “{name}” tem o perfil {model} “{profile}”, que não é o espaço de trabalho {model} “{working}”. + Use the embedded profile Usar o perfil incorporado + Convert the colors to the working space Converter as cores para o espaço de trabalho + Discard the embedded profile Descartar o perfil incorporado + Leave as is Deixar como está + Assign the working space Atribuir o espaço de trabalho + Assign profile: Atribuir perfil: + Preserve the color numbers Preservar os valores das cores + Convert to keep the colors' appearance Converter para manter a aparência das cores +@msg `{path}` goes with `{key}`: "assign" only `{path}` só acompanha `{key}`: "assign" + The pasted colors come from a document whose {model} profile is “{from}”; this document's is “{to}”. As cores coladas vêm de um documento com o perfil {model} “{from}”; o deste documento é “{to}”. Texture Textura Craquelure… Craquelê… Grain… Granulação… @@ -3914,6 +3979,17 @@ font-technology Variable Variáveis Largest: Maior: Direction: Direção: Symbolism Tools Options Opções das ferramentas de simbolismo + Tool: Ferramenta: + Symbol Set Density Densidade do conjunto de símbolos + Symbol Sprayer Options Opções do Pulverizador de Símbolos + Scrunch: Amontoar: + Spin: Girar: + Screen: Peneira: + Stain: Mancha: + Symbol Sizer Options Opções do Dimensionador de Símbolos + Proportional Resizing Redimensionamento proporcional + Resizing Affects Density Redimensionamento afeta a densidade + Show Brush Size and Intensity Mostrar tamanho e intensidade do pincel Symbol Set Density: Densidade do conjunto de símbolos: Flatten Artwork Achatar arte-final Graphics Gráficos @@ -3955,6 +4031,15 @@ font-technology Variable Variáveis YakumonoZenkaku YakumonoZenkaku Kinsoku Set Conjunto Kinsoku Kinsoku Shori Type Tipo de Kinsoku Shori + Kinsoku Shori Settings… Configurações de Kinsoku Shori… + Kinsoku Shori Settings Configurações de Kinsoku Shori + Kinsoku Sets Conjuntos Kinsoku + Kinsoku Set Base Base do conjunto Kinsoku + Based on: Com base em: + Cannot Start Line Não pode iniciar linha + Cannot End Line Não pode terminar linha + Hanging Punctuation Pontuação suspensa + Inseparable Characters Caracteres inseparáveis Push In First Primeiro para dentro Push Out First Primeiro para fora Push Out Only Somente para fora @@ -4063,6 +4148,8 @@ font-technology Variable Variáveis Outlines Contornos Outlines with Source Image Contornos com imagem de origem Source Image Imagem de origem + Split View Visualização dividida + Divider Divisor Press and hold to view the source image Mantenha pressionado para ver a imagem de origem Image Trace View Exibição de vetorização de imagem Stroke (X), double-click for the Color Picker Traço (X), clique duas vezes para o seletor de cores @@ -4341,6 +4428,7 @@ axis Both Ambos @msg a freeform gradient keeps at least one point um gradiente de forma livre mantém pelo menos um ponto @msg a gradient needs at least two stops um gradiente precisa de pelo menos duas paradas @msg a graphic style named `{to}` already exists já existe um estilo gráfico chamado `{to}` +@msg a swatch or color group named `{name}` already exists já existe uma amostra ou um grupo de cores chamado `{name}` @msg a key object sits on that point há um objeto-chave nesse ponto @msg a page is missing falta uma página @msg a page out of range uma página fora do intervalo @@ -4473,6 +4561,11 @@ axis Both Ambos @msg no anchor points selected nenhum ponto de ancoragem selecionado @msg `points` must be two or three [x, y] pairs of numbers `points` deve ter dois ou três pares de números [x, y] @msg direct-select two or three anchor points, or give `points` selecione diretamente dois ou três pontos de ancoragem ou informe `points` +@msg the path is straight there, so no circle matches its curvature o caminho é reto nesse ponto, então nenhum círculo corresponde à sua curvatura +@msg the path has a cusp there, so it has no single curvature o caminho tem uma cúspide nesse ponto, então não tem uma curvatura única +@msg the path has a corner there, so it has no single curvature o caminho tem um canto nesse ponto, então não tem uma curvatura única +@msg a guide has no curvature circle uma guia não tem círculo de curvatura +@msg the circle that matches the path there would reach past the canvas o círculo que corresponde ao caminho nesse ponto ultrapassaria a tela @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 @@ -4727,6 +4820,7 @@ axis Both Ambos @msg the PDF is password-protected: give its password o PDF é protegido por senha: informe a senha @msg the PDF password is wrong a senha do PDF está incorreta @msg the Save PDF dialog didn't open a caixa de diálogo Salvar PDF não abriu +@msg the Save PDF dialog is not open a caixa de diálogo Salvar PDF não está aberta @msg the WMF header is damaged o cabeçalho WMF está danificado @msg the art could not be sampled não foi possível amostrar a arte @msg the art has no bounds a arte não tem limites @@ -4949,6 +5043,7 @@ variable-list-end {0}, {1} {0} e {1} @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 +@msg give only one of `index`, `indices` and `t` informe apenas um entre `index`, `indices` e `t` @msg column must be true or a number from 1 column deve ser true ou um número a partir de 1 @msg x and y must both be numbers x e y devem ser números @msg "{0}" is not a colour: write it as #rrggbb "{0}" não é uma cor: escreva-a como #rrggbb @@ -5055,6 +5150,49 @@ variable-list-end {0}, {1} {0} e {1} @msg the PSD file's layer groups are nested too deeply os grupos de camadas do arquivo PSD estão aninhados profundamente demais @msg a layer of the PSD file is too large to read uma camada do arquivo PSD é grande demais para ser lida @msg the PSD file's layers take more memory to read than allowed as camadas do arquivo PSD precisam de mais memória do que o permitido para serem lidas +@msg the file is no longer loaded o arquivo não está mais carregado +@msg the layers can't be read ({e}): the file was placed as its merged image as camadas não podem ser lidas ({e}): o arquivo foi colocado como sua imagem mesclada +@msg 1 type layer came in as pixels: the text isn't editable 1 camada de texto entrou como pixels: o texto não é editável +@msg {n} type layers came in as pixels: the text isn't editable {n} camadas de texto entraram como pixels: o texto não é editável +@msg 1 adjustment layer was not applied 1 camada de ajuste não foi aplicada +@msg {n} adjustment layers were not applied {n} camadas de ajuste não foram aplicadas +@msg 1 fill layer was not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels) 1 camada de preenchimento não foi desenhada (um preenchimento de gradiente ou de padrão, uma cor que não pode ser lida ou uma forma que não guarda pixels) +@msg {n} fill layers were not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels) {n} camadas de preenchimento não foram desenhadas (um preenchimento de gradiente ou de padrão, uma cor que não pode ser lida ou uma forma que não guarda pixels) +@msg the layer effects of 1 layer weren't drawn os efeitos de camada de 1 camada não foram desenhados +@msg the layer effects of {n} layers weren't drawn os efeitos de camada de {n} camadas não foram desenhados +@msg the vector masks of 1 layer weren't applied as máscaras vetoriais de 1 camada não foram aplicadas +@msg the vector masks of {n} layers weren't applied as máscaras vetoriais de {n} camadas não foram aplicadas +@msg the knockout of 1 layer wasn't applied o vazamento de 1 camada não foi aplicado +@msg the knockout of {n} layers wasn't applied o vazamento de {n} camadas não foi aplicado +@msg 1 layer was left out (hidden layers and the layers clipped to them) 1 camada foi omitida (camadas ocultas e as camadas recortadas nelas) +@msg {n} layers were left out (hidden layers and the layers clipped to them) {n} camadas foram omitidas (camadas ocultas e as camadas recortadas nelas) +@msg 1 layer clipped to a fill layer that wasn't drawn was left out 1 camada recortada em uma camada de preenchimento não desenhada foi omitida +@msg {n} layers clipped to fill layers that weren't drawn were left out {n} camadas recortadas em camadas de preenchimento não desenhadas foram omitidas +@msg layers in blend modes VectorCraft doesn't have ({modes}) were merged with the layers below them camadas em modos de mesclagem que o VectorCraft não tem ({modes}) foram mescladas com as camadas abaixo delas +@msg 1 layer in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed 1 camada em um modo de mesclagem que o VectorCraft não tem entrou como Normal: a mesclagem precisa de mais memória do que o permitido +@msg {n} layers in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed {n} camadas em modos de mesclagem que o VectorCraft não tem entraram como Normal: a mesclagem precisa de mais memória do que o permitido +@msg 1 layer clipped to the layer below came in unclipped: the merge needs more memory than allowed 1 camada recortada na camada abaixo entrou sem recorte: a mesclagem precisa de mais memória do que o permitido +@msg {n} layers clipped to the layer below came in unclipped: the merge needs more memory than allowed {n} camadas recortadas na camada abaixo entraram sem recorte: a mesclagem precisa de mais memória do que o permitido +@msg hiddenLayers applies to a PSD file placed with layers: true hiddenLayers se aplica a um arquivo PSD colocado com layers: true +@msg importSlices: a linked PSD file is placed as its flat image; give link: false to embed it with its slices importSlices: um arquivo PSD vinculado é colocado como sua imagem achatada; informe link: false para incorporá-lo com suas fatias +@msg layers: a linked PSD file is placed as its flat image; leave link out or give link: false layers: um arquivo PSD vinculado é colocado como sua imagem achatada; omita link ou informe link: false +@msg the slices can't be read ({e}) and were left out as fatias não podem ser lidas ({e}) e foram omitidas +@msg 1 slice lies outside the canvas or has no size and was left out 1 fatia fica fora da tela de pintura ou não tem tamanho e foi omitida +@msg {n} slices lie outside the canvas or have no size and were left out {n} fatias ficam fora da tela de pintura ou não têm tamanho e foram omitidas +@msg 1 slice would lie outside the canvas and was left out 1 fatia ficaria fora da tela de pintura e foi omitida +@msg {n} slices would lie outside the canvas and were left out {n} fatias ficariam fora da tela de pintura e foram omitidas +@msg the slices' descriptor holds too many values o descritor das fatias contém valores demais +@msg the slices' descriptor has a version other than 16 o descritor das fatias tem uma versão diferente de 16 +@msg the slices are stored in version {v}, which isn't read as fatias estão salvas na versão {v}, que não é lida +@msg the file has {count} slices, more than the {MAX_SLICES} read o arquivo tem {count} fatias, mais do que as {MAX_SLICES} lidas +@msg the slices' descriptor has no list of slices o descritor das fatias não tem uma lista de fatias +@msg the slices' descriptor lists something other than a slice o descritor das fatias lista algo que não é uma fatia +@msg a slice in the slices' descriptor has no bounds uma fatia no descritor das fatias não tem limites +@msg a slice's bounds in the slices' descriptor aren't numbers os limites de uma fatia no descritor das fatias não são números +@msg a text in the slices has more than the {MAX_TEXT} characters read um texto nas fatias tem mais do que os {MAX_TEXT} caracteres lidos +@msg the slices' descriptor nests too deep o descritor das fatias está aninhado fundo demais +@msg the slices' descriptor has a reference of an unknown kind ({_1}) o descritor das fatias tem uma referência de um tipo desconhecido ({_1}) +@msg the slices' descriptor has a value of an unknown type ({_1}) o descritor das fatias tem um valor de um tipo desconhecido ({_1}) @msg the layers can't be read ({e}): the file opened as its merged image as camadas não podem ser lidas ({e}): o arquivo foi aberto como sua imagem mesclada @msg {depth}-bit PSD files in this colour mode can't be read arquivos PSD de {depth} bits neste modo de cor não podem ser lidos @msg the PSD file is cut short o arquivo PSD está incompleto @@ -5514,6 +5652,7 @@ variable-list-end {0}, {1} {0} e {1} Pressure Pressão Tilt Inclinação Bearing Orientação + Stylus Wheel Roda da caneta Bristle Length: Comprimento das Cerdas: Bristle Density: Densidade das Cerdas: Bristle Thickness: Espessura das Cerdas: @@ -8147,6 +8286,8 @@ breakText Glyphs Glifos # Path Precision Tools add-on: Tangent Circle. Tangent Circle… Círculo tangente… Tangent Circle Círculo tangente + Tangent Circle Tool Ferramenta Círculo tangente + No tangent circle here Nenhum círculo tangente aqui Circle: Círculo: @msg `ids` names an object twice `ids` indica um objeto duas vezes @msg select two or three paths or compound paths selecione dois ou três caminhos ou caminhos compostos @@ -8162,6 +8303,16 @@ breakText Glyphs Glifos @msg `circle` is past the last circle found ({found}) `circle` passa do último círculo encontrado ({found}) @msg object {value} is not a path or compound path o objeto {value} não é um caminho nem um caminho composto @msg these shapes are too small to measure estas formas são pequenas demais para medir +# Path Precision Tools add-on: Add Bounding Rectangle and Add Bounding Circle. + Add Bounding Rectangle Adicionar Retângulo Delimitador + Add Bounding Circle Adicionar Círculo Delimitador + Add Bounding Rectangle… Adicionar Retângulo Delimitador… + Add Bounding Circle… Adicionar Círculo Delimitador… + One per Object Um por objeto +@msg nothing to enclose nada para envolver +@msg `offset` must be 0 or more `offset` deve ser 0 ou mais +@msg the shape would have no size a forma não teria tamanho +@msg the shape would reach past the edge of the canvas a forma ultrapassaria a borda da tela # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Ferramentas de Documento Save a Timestamped Copy Salvar uma Cópia com Data e Hora @@ -10480,6 +10631,39 @@ swatch Yellow Green Verde-amarelado No objects are selected. Nenhum objeto selecionado. Open a document to mark its fold lines. Abra um documento para marcar suas linhas de dobra. Remove Fold Line Role Remover Tipo de Linha +# Tool cards (General › Show Tool Cards): one sentence on what each tool does. + Shows a card with what a toolbar tool does and what its keys do instead of its tip; it needs Show Tool Tips. Mostra um cartão com o que uma ferramenta da barra e suas teclas fazem, no lugar da dica; requer Mostrar Dicas de Ferramenta. + Selects whole objects and groups to move, resize or rotate them. Seleciona objetos e grupos inteiros para movê-los, redimensioná-los ou girá-los. + Selects anchor points and path segments to reshape a path. Seleciona pontos de ancoragem e segmentos de caminho para remodelar um caminho. + Draws paths point by point, with straight segments and smooth curves. Desenha caminhos ponto a ponto, com segmentos retos e curvas suaves. + Draws smooth curves through the points you click. Desenha curvas suaves que passam pelos pontos em que você clica. + Adds text at a point, or in a frame you drag. Adiciona texto em um ponto ou em um quadro que você arrasta. + Draws rectangles and squares. Desenha retângulos e quadrados. + Draws rectangles with rounded corners. Desenha retângulos com cantos arredondados. + Draws ellipses and circles. Desenha elipses e círculos. + Draws polygons with sides of equal length. Desenha polígonos com lados de mesmo comprimento. + Draws stars. Desenha estrelas. + Turns objects around a reference point. Gira objetos em torno de um ponto de referência. + Flips objects across an axis through a reference point. Reflete objetos em um eixo que passa por um ponto de referência. + Resizes objects from a reference point. Redimensiona objetos a partir de um ponto de referência. + Slants objects from a reference point. Inclina objetos a partir de um ponto de referência. + Moves the view of the document. Move a visualização do documento. + Magnifies or reduces the view. Amplia ou reduz a visualização. + Copies the color and other attributes of one object to the selection. Copia a cor e outros atributos de um objeto para a seleção. + Sets the direction and length of a gradient. Define a direção e o comprimento de um degradê. + Creates, selects and resizes artboards. Cria, seleciona e redimensiona mesas de trabalho. + Changes the width of a stroke along its length. Altera a largura de um traçado ao longo do seu comprimento. + Bends art by dragging pins placed on it. Deforma a arte arrastando alfinetes colocados nela. + Pushes the outlines of paths in the direction you drag. Empurra os contornos dos caminhos na direção em que você arrasta. + Twists the outlines of paths into swirls. Torce os contornos dos caminhos em espirais. + Pulls the outlines of paths in toward the brush. Puxa os contornos dos caminhos em direção ao pincel. + Pushes the outlines of paths out from the brush. Empurra os contornos dos caminhos para fora a partir do pincel. + Adds curved details along the outlines of paths. Adiciona detalhes curvos ao longo dos contornos dos caminhos. + Adds spiky details along the outlines of paths. Adiciona detalhes pontiagudos ao longo dos contornos dos caminhos. + Adds wrinkles along the outlines of paths. Adiciona rugas ao longo dos contornos dos caminhos. + Moves, copies and resizes objects on the perspective grid. Move, copia e redimensiona objetos na grade de perspectiva. + Makes a series of steps between two or more objects. Cria uma série de etapas entre dois ou mais objetos. + Places dimension lines that show measured lengths. Insere linhas de cota que mostram comprimentos medidos. Tap Toque Rápido Clear Hold Limpar Pressionamento Longo Hold Shortcuts Atalhos de Pressionamento Longo @@ -10510,7 +10694,18 @@ swatch Yellow Green Verde-amarelado @msg A panel is not joined to the rest by a crease. Um painel não está unido ao restante por nenhuma linha de vinco. @msg A fold line is on a non-printing layer. Uma linha de dobra está em uma camada não imprimível. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Painéis: {panels}, dobradiças: {hinges}, erros: {errors}, avisos: {warnings} + Paper Cutouts Recortes de papel + Coral Layers Camadas de coral + Mint Layers Camadas de menta + Midnight Layers Camadas da meia-noite + Sunflower Sheet Folha de girassol + Rose Layers Camadas de rosa + Monochrome Stack Pilha monocromática Dashed Arrow Seta tracejada + Fine Stipple Pontilhado fino + Dense Stipple Pontilhado denso + Soft Stipple Pontilhado suave + Bold Stipple Pontilhado grosso Pressure Sensitive Sensível à pressão Flex Ribbon Fita flexível Pulse Stroke Traço pulsante @@ -10526,3 +10721,7 @@ swatch Yellow Green Verde-amarelado @msg Other blanks not shown: {count} Outras planificações não exibidas: {count} @msg A joint does not close by {gap} pt. Uma junção não fecha por {gap} pt. @msg Two panels pass through each other. Dois painéis se atravessam. + +# #5804 native-picked raster editor (draft translations; native review welcome). + Edit Original with: Editar original com: +file-filter Applications Aplicativos diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index bf80837d00..05b2f89f78 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -496,6 +496,9 @@ font-technology Variable Вариативные Choose… Выбрать… Circle Круг Circle Tool Инструмент «Круг» + Curvature Circle Tool Инструмент «Круг кривизны» + Cusp Точка возврата + Straight segment Прямой сегмент Circle too large Круг слишком большой Classic Defaults Классические значения по умолчанию Clean Up… Очистить… @@ -603,6 +606,9 @@ font-technology Variable Вариативные Box Channel Канал квадрата Color box Цветовой квадрат Color Wheel Options Параметры цветового круга + Show Harmony Показать гармонию + Harmony Rule Правило гармонии + Harmony color Цвет гармонии Color Type: Тип цвета: Color: Цвет: Colorize Тонировать @@ -1028,10 +1034,25 @@ font-technology Variable Вариативные Duplicate Symbol Дублировать символ Duplicate {kind} Style Дублировать стиль {kind} Dutch Нидерландский + PSD Import Options Параметры импорта PSD + Place PSD Поместить PSD + Convert Layers to Objects Преобразовать слои в объекты + Import Hidden Layers Импортировать скрытые слои + Flatten Layers to a Single Image Свести слои в одно изображение + Import Slices Импортировать фрагменты DXF Import Options Параметры импорта DXF DXF Info Сведения о DXF DXF Options Параметры DXF DXF Options Dialog Диалоговое окно «Параметры DXF» + HP-GL Options Параметры HP-GL + HP-GL Options Dialog Диалоговое окно «Параметры HP-GL» + Curve Tolerance: Допуск кривых: + Origin: Начало координат: + Pens: Перья: + One Pen per Color Одно перо на цвет + Pen Table Таблица перьев + Draw the Nearest Path Next Следующим рисовать ближайший контур + Draw Inner Paths First Сначала рисовать внутренние контуры e.g. 1-3, 5 напр. 1-3, 5 Each page prints as one image, at the document's raster effects resolution. Каждая страница печатается как одно изображение с разрешением растровых эффектов документа. Earth Tones Земляные тона @@ -1268,6 +1289,15 @@ font-technology Variable Вариативные Shading Color Цвет затенения Black Overprint Чёрный с наложением Draw Hidden Faces Рисовать скрытые грани + Map Art… Наложение графики… + Map Art Наложение графики + First Surface Первая поверхность + Previous Surface Предыдущая поверхность + Next Surface Следующая поверхность + Last Surface Последняя поверхность + Scale to Fit Масштабировать по размеру + Shade Artwork Затенять графику + Invisible Geometry Невидимая геометрия Eyedropper Пипетка Sample Color from Screen Взять цвет с экрана This system has no screen color sampler В этой системе нет средства выбора цвета с экрана @@ -1397,6 +1427,17 @@ font-technology Variable Вариативные Largest: Самое большое: Direction: Направление: Symbolism Tools Options Параметры инструментов символов + Tool: Инструмент: + Symbol Set Density Плотность набора символов + Symbol Sprayer Options Параметры распылителя символов + Scrunch: Сжатие: + Spin: Вращение: + Screen: Прозрачность: + Stain: Тонирование: + Symbol Sizer Options Параметры размера символов + Proportional Resizing Пропорциональное изменение размера + Resizing Affects Density Изменение размера влияет на плотность + Show Brush Size and Intensity Показывать размер и интенсивность кисти Symbol Set Density: Плотность набора символов: Flat Image Плоское изображение Flat Logo Плоский логотип @@ -1678,6 +1719,8 @@ file-filter Templates Шаблоны More Options Дополнительные параметры Show Properties Panel Показать панель «Свойства» Hide Corner Widget Скрыть угловой виджет + Hide Shape Widgets Скрыть виджеты фигур + Show Shape Widgets Показать виджеты фигур Hide Corner Widget for angles greater than Скрывать угловой виджет для углов больше Hide Edges Скрыть края Hide Gradient Annotator Скрыть аннотатор градиента @@ -2250,6 +2293,15 @@ file-filter Templates Шаблоны YakumonoZenkaku YakumonoZenkaku Kinsoku Set Набор kinsoku Kinsoku Shori Type Тип kinsoku shori + Kinsoku Shori Settings… Настройки kinsoku shori… + Kinsoku Shori Settings Настройки kinsoku shori + Kinsoku Sets Наборы kinsoku + Kinsoku Set Base Основа набора kinsoku + Based on: На основе: + Cannot Start Line Не может начинать строку + Cannot End Line Не может заканчивать строку + Hanging Punctuation Висячая пунктуация + Inseparable Characters Неразрывные символы Push In First Сначала втягивать Push Out First Сначала выталкивать Push Out Only Только выталкивать @@ -2366,6 +2418,7 @@ file-filter Templates Шаблоны Pressure Нажим Tilt Наклон Bearing Азимут + Stylus Wheel Колесико пера Shape: Форма: Bristle Length: Длина щетинок: Bristle Density: Плотность щетинок: @@ -2396,6 +2449,9 @@ file-filter Templates Шаблоны embedding for preview and print внедрение для просмотра и печати embedding allowed внедрение разрешено {file}; {embedding} {file}; {embedding} + unknown type неизвестный тип + {type}; {uses} {type}; {uses} +@plural {n} use|{n} uses {n} использование|{n} использования|{n} использований substituted: shown in {family} {style} ({detail}) заменен: показан шрифтом {family} {style} ({detail}) missing: shown in {family} {style} отсутствует: показан шрифтом {family} {style} missing отсутствует @@ -2668,6 +2724,8 @@ file-filter Templates Шаблоны Overprint and Transparency Flattener Options Параметры наложения и объединения прозрачностей Custom… Пользовательские… Custom Transparency Flattener Options Пользовательские параметры объединения прозрачностей + The PDF preset keeps the flattener preset but not the Custom… settings. Набор PDF сохраняет набор объединения, но не параметры из «Пользовательские…». + PDF 1.3 files clip rasterized areas to their regions, and Overprint sets whether overprints are kept. Файлы PDF 1.3 обрезают растрированные области по их контурам, а параметр «Наложение» определяет, сохраняются ли наложения. EPS has no alpha transparency, and Overprints sets whether overprints are kept. В EPS нет альфа-прозрачности, а параметр «Наложения» определяет, сохраняются ли наложения. Overprint Black… Наложение чёрного… Overprint Fill Наложение заливки @@ -3186,6 +3244,9 @@ digits Malayalam Малаялам Rotate View to Selection Повернуть вид по выделению Reset the rows to the artwork's colors Сбросить строки к цветам рисунка Color Theme Picker Выбор цветовой темы + Undo Changes Отменить изменения + Redo Changes Повторить изменения +@msg Recolor Artwork is not open Окно «Перекрасить рисунок» не открыто Click or drag across the art to pick its colors; Shift adds more Щёлкните или проведите по рисунку, чтобы взять его цвета; Shift добавляет ещё Prominent Colors Преобладающие цвета Save All Colors Сохранить все цвета @@ -3240,6 +3301,7 @@ digits Malayalam Малаялам A live rectangle's properties show one Corner Radius field for all four corners; off, each corner has its own field. Свойства динамического прямоугольника показывают одно поле «Радиус угла» для всех четырёх углов; если выключено, у каждого угла своё поле. What edits in the Transform panel transform: the object, its pattern tiles or both; Default follows Transform Pattern Tiles. Что трансформируют изменения на панели «Трансформировать»: объект, плитки его узора или и то и другое; «По умолчанию» следует «Трансформировать плитки узора». With one symbol instance selected, the Transform panel uses the symbol's registration point as its reference point. Когда выделен один экземпляр символа, панель «Трансформировать» использует точку регистрации символа как опорную точку. + Drawing a rectangle, ellipse, polygon, star or line opens the Transform panel if it is closed. Рисование прямоугольника, эллипса, многоугольника, звезды или линии открывает панель «Трансформировать», если она закрыта. Darkens the canvas outside the artboards while the Artboard tool is active. Затемняет холст вне монтажных областей, пока активен инструмент «Монтажная область». With Fade Region Outside Artboard on, the area outside the artboards stays dark while you drag with the Artboard tool. Когда включено «Затемнять область вне монтажной области», область вне монтажных областей остаётся тёмной, пока вы перетаскиваете инструментом «Монтажная область». How near, in pixels, the pointer must be to an object, anchor or handle for a click to select it. Насколько близко, в пикселях, указатель должен быть к объекту, опорной точке или маркеру, чтобы щелчок выделил его. @@ -3420,6 +3482,7 @@ digits Malayalam Малаялам Save Document Preset Сохранить набор документа Preset {number} Набор {number} Save Preset… Сохранить набор… + Save Summary… Сохранить сводку… Save Print Preset Сохранить набор печати Save Recovery Data Сохранить данные восстановления Save Save for Web Preset Сохранить набор «Сохранить для web» @@ -3726,6 +3789,7 @@ digits Malayalam Малаялам Show Modified Показать изменённые Show Note Показать примечание Show Options Показать параметры + Show on Shape Creation Показывать при создании фигуры Show Recent Colors Показать последние цвета Toggle RGB Percent Переключить RGB в процентах Show Original Path Показать исходный контур @@ -3753,6 +3817,7 @@ digits Malayalam Малаялам Show Thumbnails Показать миниатюры Show Tile Edge Показать край плитки Show Tints/Shades Показать оттенки/тени + Show Tool Cards Показывать карточки инструментов Show Tool Tips Показывать подсказки Show Transparency Grid Показать сетку прозрачности Show Video Rulers Показать видео-линейки @@ -3836,6 +3901,8 @@ digits Malayalam Малаялам Outlines Контуры Outlines with Source Image Контуры с исходным изображением Source Image Исходное изображение + Split View Разделённый вид + Divider Разделитель Press and hold to view the source image Удерживайте, чтобы увидеть исходное изображение Image Trace View Просмотр трассировки изображения Snap Options Параметры привязки @@ -4287,6 +4354,8 @@ digits Malayalam Малаялам Unembed… Извлечь… Ungroup Разгруппировать Ungroup Color Group Разгруппировать цветовую группу + Color Group Options Параметры цветовой группы + Color Group Options… Параметры цветовой группы… Unicode Unicode Unicode (UTF-16) Unicode (UTF-16) Unicode (UTF-8) Unicode (UTF-8) @@ -5097,6 +5166,7 @@ liquify-list-end {0}, {1} {0} и {1} @msg a freeform gradient keeps at least one point произвольный градиент сохраняет как минимум одну точку @msg a gradient needs at least two stops градиенту нужны как минимум две точки перехода @msg a graphic style named `{to}` already exists графический стиль с именем `{to}` уже существует +@msg a swatch or color group named `{name}` already exists образец или цветовая группа с именем `{name}` уже существует @msg a key object sits on that point в этой точке находится ключевой объект @msg a page is missing страница отсутствует @msg a page out of range страница вне диапазона @@ -5238,6 +5308,11 @@ liquify-list-end {0}, {1} {0} и {1} @msg no anchor points selected опорные точки не выделены @msg `points` must be two or three [x, y] pairs of numbers `points` должен содержать две или три пары чисел [x, y] @msg direct-select two or three anchor points, or give `points` выделите прямым выделением две или три опорные точки или задайте `points` +@msg the path is straight there, so no circle matches its curvature контур в этом месте прямой, поэтому его кривизне не соответствует ни одна окружность +@msg the path has a cusp there, so it has no single curvature у контура в этом месте точка возврата, поэтому у него нет единой кривизны +@msg the path has a corner there, so it has no single curvature у контура в этом месте угол, поэтому у него нет единой кривизны +@msg a guide has no curvature circle у направляющей нет круга кривизны +@msg the circle that matches the path there would reach past the canvas окружность, соответствующая контуру в этом месте, вышла бы за пределы холста @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 нет монтажной области @@ -5496,6 +5571,7 @@ liquify-list-end {0}, {1} {0} и {1} @msg the PDF is password-protected: give its password PDF защищён паролем: укажите его пароль @msg the PDF password is wrong неверный пароль PDF @msg the Save PDF dialog didn't open диалоговое окно «Сохранить PDF» не открылось +@msg the Save PDF dialog is not open диалоговое окно «Сохранить PDF» не открыто @msg the WMF header is damaged заголовок WMF повреждён @msg the art could not be sampled не удалось взять образец рисунка @msg the art has no bounds у рисунка нет границ @@ -5719,6 +5795,7 @@ variable-list-end {0}, {1} {0} и {1} @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 +@msg give only one of `index`, `indices` and `t` укажите только один из `index`, `indices` и `t` @msg column must be true or a number from 1 column должен быть true или числом от 1 @msg x and y must both be numbers x и y должны быть числами @msg "{0}" is not a colour: write it as #rrggbb «{0}» не является цветом: запишите его как #rrggbb @@ -5864,6 +5941,49 @@ variable-list-end {0}, {1} {0} и {1} @msg the PSD file's layer groups are nested too deeply группы слоёв файла PSD вложены слишком глубоко @msg a layer of the PSD file is too large to read слой файла PSD слишком велик для чтения @msg the PSD file's layers take more memory to read than allowed для чтения слоёв файла PSD нужно больше памяти, чем разрешено +@msg the file is no longer loaded файл больше не загружен +@msg the layers can't be read ({e}): the file was placed as its merged image не удаётся прочитать слои ({e}): файл помещён как сведённое изображение +@msg 1 type layer came in as pixels: the text isn't editable 1 текстовый слой импортирован как пиксели: текст нельзя редактировать +@msg {n} type layers came in as pixels: the text isn't editable текстовых слоёв, импортированных как пиксели: {n}; текст нельзя редактировать +@msg 1 adjustment layer was not applied 1 корректирующий слой не применён +@msg {n} adjustment layers were not applied не применено корректирующих слоёв: {n} +@msg 1 fill layer was not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels) 1 слой-заливка не отрисован (градиентная или узорная заливка, цвет, который не удаётся прочитать, или фигура без сохранённых пикселей) +@msg {n} fill layers were not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels) не отрисовано слоёв-заливок: {n} (градиентная или узорная заливка, цвет, который не удаётся прочитать, или фигура без сохранённых пикселей) +@msg the layer effects of 1 layer weren't drawn эффекты слоя для 1 слоя не отрисованы +@msg the layer effects of {n} layers weren't drawn эффекты слоёв не отрисованы; число слоёв: {n} +@msg the vector masks of 1 layer weren't applied векторные маски 1 слоя не применены +@msg the vector masks of {n} layers weren't applied векторные маски слоёв не применены; число слоёв: {n} +@msg the knockout of 1 layer wasn't applied выбивка 1 слоя не применена +@msg the knockout of {n} layers wasn't applied выбивка слоёв не применена; число слоёв: {n} +@msg 1 layer was left out (hidden layers and the layers clipped to them) 1 слой пропущен (скрытые слои и обрезанные по ним слои) +@msg {n} layers were left out (hidden layers and the layers clipped to them) пропущено слоёв: {n} (скрытые слои и обрезанные по ним слои) +@msg 1 layer clipped to a fill layer that wasn't drawn was left out 1 слой, обрезанный по неотрисованному слою-заливке, пропущен +@msg {n} layers clipped to fill layers that weren't drawn were left out пропущено слоёв, обрезанных по неотрисованным слоям-заливкам: {n} +@msg layers in blend modes VectorCraft doesn't have ({modes}) were merged with the layers below them слои в режимах наложения, которых нет в VectorCraft ({modes}), сведены со слоями под ними +@msg 1 layer in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed 1 слой в режиме наложения, которого нет в VectorCraft, импортирован как Обычный: для сведения нужно больше памяти, чем разрешено +@msg {n} layers in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed слоёв в режимах наложения, которых нет в VectorCraft, импортировано как Обычный: {n}; для сведения нужно больше памяти, чем разрешено +@msg 1 layer clipped to the layer below came in unclipped: the merge needs more memory than allowed 1 слой, обрезанный по нижнему слою, импортирован без обрезки: для сведения нужно больше памяти, чем разрешено +@msg {n} layers clipped to the layer below came in unclipped: the merge needs more memory than allowed слоёв, обрезанных по нижнему слою и импортированных без обрезки: {n}; для сведения нужно больше памяти, чем разрешено +@msg hiddenLayers applies to a PSD file placed with layers: true hiddenLayers относится к PSD-файлу, помещаемому с layers: true +@msg importSlices: a linked PSD file is placed as its flat image; give link: false to embed it with its slices importSlices: связанный PSD-файл помещается как плоское изображение; укажите link: false, чтобы внедрить его с фрагментами +@msg layers: a linked PSD file is placed as its flat image; leave link out or give link: false layers: связанный PSD-файл помещается как плоское изображение; не указывайте link или укажите link: false +@msg the slices can't be read ({e}) and were left out не удаётся прочитать фрагменты ({e}), они пропущены +@msg 1 slice lies outside the canvas or has no size and was left out 1 фрагмент лежит вне холста или не имеет размера и пропущен +@msg {n} slices lie outside the canvas or have no size and were left out пропущено фрагментов вне холста или без размера: {n} +@msg 1 slice would lie outside the canvas and was left out 1 фрагмент оказался бы вне холста и пропущен +@msg {n} slices would lie outside the canvas and were left out пропущено фрагментов, которые оказались бы вне холста: {n} +@msg the slices' descriptor holds too many values дескриптор фрагментов содержит слишком много значений +@msg the slices' descriptor has a version other than 16 версия дескриптора фрагментов отличается от 16 +@msg the slices are stored in version {v}, which isn't read фрагменты сохранены в версии {v}, которая не читается +@msg the file has {count} slices, more than the {MAX_SLICES} read фрагментов в файле: {count}, больше читаемых {MAX_SLICES} +@msg the slices' descriptor has no list of slices в дескрипторе фрагментов нет списка фрагментов +@msg the slices' descriptor lists something other than a slice дескриптор фрагментов перечисляет что-то, кроме фрагмента +@msg a slice in the slices' descriptor has no bounds у фрагмента в дескрипторе фрагментов нет границ +@msg a slice's bounds in the slices' descriptor aren't numbers границы фрагмента в дескрипторе фрагментов не являются числами +@msg a text in the slices has more than the {MAX_TEXT} characters read текст во фрагментах длиннее читаемых {MAX_TEXT} символов +@msg the slices' descriptor nests too deep дескриптор фрагментов вложен слишком глубоко +@msg the slices' descriptor has a reference of an unknown kind ({_1}) в дескрипторе фрагментов есть ссылка неизвестного вида ({_1}) +@msg the slices' descriptor has a value of an unknown type ({_1}) в дескрипторе фрагментов есть значение неизвестного типа ({_1}) @msg the layers can't be read ({e}): the file opened as its merged image не удаётся прочитать слои ({e}): файл открыт как сведённое изображение @msg {depth}-bit PSD files in this colour mode can't be read {depth}-битные файлы PSD в этом цветовом режиме не читаются @msg the PSD file is cut short файл PSD обрезан @@ -5891,6 +6011,25 @@ variable-list-end {0}, {1} {0} и {1} Preserve Embedded Profiles Сохранять встроенные профили Convert to Working Space Преобразовывать в рабочее пространство Preserve Numbers Сохранять числа + Profile Mismatches: Несоответствие профилей: + Ask When Opening Спрашивать при открытии + Ask When Pasting Спрашивать при вставке + Missing Profiles: Отсутствующие профили: + Embedded Profile Mismatch Несоответствие встроенного профиля + Missing Profile Отсутствует профиль + Paste Profile Mismatch Несоответствие профиля при вставке + “{name}” is not tagged with a {model} profile. У «{name}» нет профиля {model}. + “{name}” is tagged with the {model} profile “{profile}”, which is not the {model} working space “{working}”. У «{name}» профиль {model} «{profile}», который не является рабочим пространством {model} «{working}». + Use the embedded profile Использовать встроенный профиль + Convert the colors to the working space Преобразовать цвета в рабочее пространство + Discard the embedded profile Отбросить встроенный профиль + Leave as is Оставить как есть + Assign the working space Назначить рабочее пространство + Assign profile: Назначить профиль: + Preserve the color numbers Сохранить числовые значения цветов + Convert to keep the colors' appearance Преобразовать, сохранив вид цветов +@msg `{path}` goes with `{key}`: "assign" only `{path}` используется только с `{key}`: "assign" + The pasted colors come from a document whose {model} profile is “{from}”; this document's is “{to}”. Вставленные цвета взяты из документа с профилем {model} «{from}»; у этого документа профиль «{to}». Texture Текстура Craquelure… Кракелюры… Grain… Зерно… @@ -8118,6 +8257,8 @@ breakText Glyphs Глифы # Path Precision Tools add-on: Tangent Circle. Tangent Circle… Касательная окружность… Tangent Circle Касательная окружность + Tangent Circle Tool Инструмент «Касательная окружность» + No tangent circle here Здесь нет касательной окружности Circle: Окружность: @msg `ids` names an object twice `ids` указывает объект дважды @msg select two or three paths or compound paths выделите два или три контура или составных контура @@ -8133,6 +8274,16 @@ breakText Glyphs Глифы @msg `circle` is past the last circle found ({found}) `circle` больше числа найденных окружностей ({found}) @msg object {value} is not a path or compound path объект {value} не является контуром или составным контуром @msg these shapes are too small to measure эти фигуры слишком малы для измерения +# Path Precision Tools add-on: Add Bounding Rectangle and Add Bounding Circle. + Add Bounding Rectangle Добавить описанный прямоугольник + Add Bounding Circle Добавить описанную окружность + Add Bounding Rectangle… Добавить описанный прямоугольник… + Add Bounding Circle… Добавить описанную окружность… + One per Object По одной на объект +@msg nothing to enclose нечего окружать +@msg `offset` must be 0 or more `offset` должно быть 0 или больше +@msg the shape would have no size у фигуры не было бы размера +@msg the shape would reach past the edge of the canvas фигура вышла бы за край холста # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Инструменты документа Save a Timestamped Copy Сохранить копию с датой и временем @@ -10526,6 +10677,50 @@ shape Open Открытый @msg Two panels pass through each other. Две панели проходят друг сквозь друга. @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} пикселей — слишком большой размер для PSD (не более {MAX_SIDE} пикселей по стороне): уменьшите разрешение @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer должен быть "singleLine", "everyLine", "standardSingleLine" или "standardEveryLine" + Fine Stipple Тонкая точечная штриховка + Dense Stipple Плотная точечная штриховка + Soft Stipple Мягкая точечная штриховка + Bold Stipple Крупная точечная штриховка + Paper Cutouts Бумажные вырезки + Coral Layers Коралловые слои + Mint Layers Мятные слои + Midnight Layers Полуночные слои + Sunflower Sheet Лист подсолнуха + Rose Layers Розовые слои + Monochrome Stack Монохромная стопка +# Tool cards (General › Show Tool Cards): one sentence on what each tool does. + Shows a card with what a toolbar tool does and what its keys do instead of its tip; it needs Show Tool Tips. Вместо подсказки показывает карточку о том, что делают инструмент панели и его клавиши; требуется Показывать подсказки. + Selects whole objects and groups to move, resize or rotate them. Выделяет объекты и группы целиком, чтобы перемещать, масштабировать или поворачивать их. + Selects anchor points and path segments to reshape a path. Выделяет опорные точки и сегменты контура, чтобы изменить форму контура. + Draws paths point by point, with straight segments and smooth curves. Рисует контуры точка за точкой, с прямыми сегментами и плавными кривыми. + Draws smooth curves through the points you click. Рисует плавные кривые через точки, по которым вы щёлкаете. + Adds text at a point, or in a frame you drag. Добавляет текст в точке или в рамке, которую вы растягиваете. + Draws rectangles and squares. Рисует прямоугольники и квадраты. + Draws rectangles with rounded corners. Рисует прямоугольники со скруглёнными углами. + Draws ellipses and circles. Рисует эллипсы и окружности. + Draws polygons with sides of equal length. Рисует многоугольники с равными сторонами. + Draws stars. Рисует звёзды. + Turns objects around a reference point. Поворачивает объекты вокруг опорной точки. + Flips objects across an axis through a reference point. Зеркально отражает объекты относительно оси, проходящей через опорную точку. + Resizes objects from a reference point. Масштабирует объекты от опорной точки. + Slants objects from a reference point. Наклоняет объекты от опорной точки. + Moves the view of the document. Перемещает вид документа. + Magnifies or reduces the view. Увеличивает или уменьшает масштаб вида. + Copies the color and other attributes of one object to the selection. Копирует цвет и другие атрибуты одного объекта на выделение. + Sets the direction and length of a gradient. Задаёт направление и длину градиента. + Creates, selects and resizes artboards. Создаёт, выделяет и масштабирует монтажные области. + Changes the width of a stroke along its length. Изменяет ширину обводки по её длине. + Bends art by dragging pins placed on it. Изгибает графику перетаскиванием булавок, расставленных на ней. + Pushes the outlines of paths in the direction you drag. Сдвигает очертания контуров в направлении перетаскивания. + Twists the outlines of paths into swirls. Закручивает очертания контуров в вихри. + Pulls the outlines of paths in toward the brush. Стягивает очертания контуров к кисти. + Pushes the outlines of paths out from the brush. Раздувает очертания контуров от кисти наружу. + Adds curved details along the outlines of paths. Добавляет изогнутые детали вдоль очертаний контуров. + Adds spiky details along the outlines of paths. Добавляет острые детали вдоль очертаний контуров. + Adds wrinkles along the outlines of paths. Добавляет складки вдоль очертаний контуров. + Moves, copies and resizes objects on the perspective grid. Перемещает, копирует и масштабирует объекты на сетке перспективы. + Makes a series of steps between two or more objects. Создаёт ряд переходов между двумя или более объектами. + Places dimension lines that show measured lengths. Размещает размерные линии с измеренными длинами. Tap Короткое нажатие Clear Hold Очистить удержание Hold Shortcuts Клавиши удержания @@ -10542,3 +10737,7 @@ shape Open Открытый Pulse Stroke Пульсирующий штрих Round Flow Круглый поток Chisel Flow Косой поток + +# #5804 native-picked raster editor (draft translations; native review welcome). + Edit Original with: Редактировать оригинал в: +file-filter Applications Приложения diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 0099bc516d..21432d55ee 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -487,6 +487,9 @@ font-technology Variable Variabla Choose… Välj… Circle Cirkel Circle Tool Cirkelverktyg + Curvature Circle Tool Krökningscirkelverktyg + Cusp Spets + Straight segment Rakt segment Circle too large Cirkeln är för stor Classic Defaults Klassiska standardvärden Clean Up… Rensa upp… @@ -588,6 +591,9 @@ font-technology Variable Variabla Box Channel Rutans kanal Color box Färgruta Color Wheel Options Alternativ för färghjulet + Show Harmony Visa harmoni + Harmony Rule Harmoniregel + Harmony color Harmonifärg Color Type: Färgtyp: Color: Färg: Colorize Färglägg @@ -1013,10 +1019,25 @@ font-technology Variable Variabla Duplicate Symbol Duplicera symbol Duplicate {kind} Style Duplicera {kind}-stil Dutch Nederländska + PSD Import Options Importalternativ för PSD + Place PSD Placera PSD + Convert Layers to Objects Konvertera lager till objekt + Import Hidden Layers Importera dolda lager + Flatten Layers to a Single Image Platta till lager till en enda bild + Import Slices Importera skivor DXF Import Options Importalternativ för DXF DXF Info DXF-info DXF Options DXF-alternativ DXF Options Dialog Dialogruta för DXF-alternativ + HP-GL Options HP-GL-alternativ + HP-GL Options Dialog Dialogruta för HP-GL-alternativ + Curve Tolerance: Kurvtolerans: + Origin: Origo: + Pens: Pennor: + One Pen per Color En penna per färg + Pen Table Penntabell + Draw the Nearest Path Next Rita den närmaste banan härnäst + Draw Inner Paths First Rita inre banor först e.g. 1-3, 5 t.ex. 1-3, 5 Each page prints as one image, at the document's raster effects resolution. Varje sida skrivs ut som en bild, med dokumentets upplösning för rastereffekter. Earth Tones Jordtoner @@ -1239,6 +1260,15 @@ font-technology Variable Variabla Shading Color Skuggningsfärg Black Overprint Svart övertryck Draw Hidden Faces Rita dolda ytor + Map Art… Mappa bildmaterial… + Map Art Mappa bildmaterial + First Surface Första ytan + Previous Surface Föregående yta + Next Surface Nästa yta + Last Surface Sista ytan + Scale to Fit Skala för att passa + Shade Artwork Skugga bildmaterial + Invisible Geometry Osynlig geometri Eyedropper Pipett Eyedropper Applies: Pipetten tillämpar: Eyedropper Options Pipettalternativ @@ -1346,6 +1376,17 @@ font-technology Variable Variabla Largest: Störst: Direction: Riktning: Symbolism Tools Options Alternativ för symbolverktyg + Tool: Verktyg: + Symbol Set Density Täthet för symboluppsättning + Symbol Sprayer Options Alternativ för symbolspruta + Scrunch: Dra ihop: + Spin: Rotera: + Screen: Opacitet: + Stain: Färga: + Symbol Sizer Options Alternativ för symbolstorlek + Proportional Resizing Proportionell storleksändring + Resizing Affects Density Storleksändring påverkar tätheten + Show Brush Size and Intensity Visa penselstorlek och intensitet Symbol Set Density: Täthet för symboluppsättning: Flat Image Platt bild Flat Logo Platt logotyp @@ -1615,6 +1656,8 @@ font-technology Variable Variabla More Options Fler alternativ Show Properties Panel Visa panelen Egenskaper Hide Corner Widget Dölj hörnwidget + Hide Shape Widgets Dölj formwidgetar + Show Shape Widgets Visa formwidgetar Hide Corner Widget for angles greater than Dölj hörnwidget för vinklar större än Hide Edges Dölj kanter Hide Gradient Annotator Dölj gradientreglage @@ -2152,6 +2195,15 @@ font-technology Variable Variabla YakumonoZenkaku YakumonoZenkaku Kinsoku Set Kinsoku-uppsättning Kinsoku Shori Type Kinsoku Shori-typ + Kinsoku Shori Settings… Kinsoku Shori-inställningar… + Kinsoku Shori Settings Kinsoku Shori-inställningar + Kinsoku Sets Kinsoku-uppsättningar + Kinsoku Set Base Grund för Kinsoku-uppsättning + Based on: Baserad på: + Cannot Start Line Kan inte inleda rad + Cannot End Line Kan inte avsluta rad + Hanging Punctuation Hängande skiljetecken + Inseparable Characters Oskiljbara tecken Push In First Skjut in först Push Out First Skjut ut först Push Out Only Skjut endast ut @@ -2268,6 +2320,7 @@ font-technology Variable Variabla Pressure Tryck Tilt Lutning Bearing Riktning + Stylus Wheel Pennhjul Shape: Form: Bristle Length: Borstlängd: Bristle Density: Borsttäthet: @@ -2298,6 +2351,9 @@ font-technology Variable Variabla embedding for preview and print inbäddning för förhandsvisning och utskrift embedding allowed inbäddning tillåten {file}; {embedding} {file}; {embedding} + unknown type okänd typ + {type}; {uses} {type}; {uses} +@plural {n} use|{n} uses {n} användning|{n} användningar substituted: shown in {family} {style} ({detail}) ersatt: visas med {family} {style} ({detail}) missing: shown in {family} {style} saknas: visas med {family} {style} missing saknas @@ -2570,6 +2626,8 @@ font-technology Variable Variabla Overprint and Transparency Flattener Options Alternativ för övertryck och transparensutplattning Custom… Anpassad… Custom Transparency Flattener Options Anpassade alternativ för transparensutplattning + The PDF preset keeps the flattener preset but not the Custom… settings. PDF-förinställningen sparar utplattningsförinställningen men inte inställningarna under Anpassad…. + PDF 1.3 files clip rasterized areas to their regions, and Overprint sets whether overprints are kept. PDF 1.3-filer klipper rastrerade områden till sina regioner, och Övertryck avgör om övertryck behålls. EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS har ingen alfatransparens, och Övertryck avgör om övertryck behålls. Overprint Black… Övertryck svart… Overprint Fill Övertryck fyllning @@ -3075,6 +3133,9 @@ digits Malayalam Malayalam Rotate View to Selection Rotera vyn efter markeringen Reset the rows to the artwork's colors Återställ raderna till teckningens färger Color Theme Picker Färgtemaväljare + Undo Changes Ångra ändringar + Redo Changes Gör om ändringar +@msg Recolor Artwork is not open Färga om grafik är inte öppet Click or drag across the art to pick its colors; Shift adds more Klicka eller dra över teckningen för att hämta dess färger; Skift lägger till fler Prominent Colors Framträdande färger Save All Colors Spara alla färger @@ -3129,6 +3190,7 @@ digits Malayalam Malayalam A live rectangle's properties show one Corner Radius field for all four corners; off, each corner has its own field. Egenskaperna för en dynamisk rektangel visar ett fält Hörnradie för alla fyra hörn; när det är av har varje hörn ett eget fält. What edits in the Transform panel transform: the object, its pattern tiles or both; Default follows Transform Pattern Tiles. Vad ändringar i panelen Transformera transformerar: objektet, dess mönsterrutor eller båda; Standard följer Transformera mönsterrutor. With one symbol instance selected, the Transform panel uses the symbol's registration point as its reference point. När en symbolinstans är markerad använder panelen Transformera symbolens registreringspunkt som referenspunkt. + Drawing a rectangle, ellipse, polygon, star or line opens the Transform panel if it is closed. När du ritar en rektangel, en ellips, en polygon, en stjärna eller en linje öppnas panelen Transformera om den är stängd. Darkens the canvas outside the artboards while the Artboard tool is active. Gör arbetsytan utanför ritytorna mörkare medan verktyget Rityta är aktivt. With Fade Region Outside Artboard on, the area outside the artboards stays dark while you drag with the Artboard tool. När Tona ned området utanför ritytan är på förblir området utanför ritytorna mörkt medan du drar med verktyget Rityta. How near, in pixels, the pointer must be to an object, anchor or handle for a click to select it. Hur nära, i pixlar, pekaren måste vara ett objekt, en ankarpunkt eller ett handtag för att ett klick ska markera det. @@ -3308,6 +3370,7 @@ digits Malayalam Malayalam Save Preset Spara förinställning Save Document Preset Spara dokumentförinställning Save Preset… Spara förinställning… + Save Summary… Spara sammanfattning… Save Print Preset Spara utskriftsförinställning Save Recovery Data Spara återställningsdata Save Save for Web Preset Spara förinställning för Spara för webben @@ -3601,6 +3664,7 @@ digits Malayalam Malayalam Show Modified Visa ändrade Show Note Visa anteckning Show Options Visa alternativ + Show on Shape Creation Visa när form skapas Show Recent Colors Visa senaste färger Toggle RGB Percent Växla RGB i procent Show Original Path Visa ursprunglig bana @@ -3626,6 +3690,7 @@ digits Malayalam Malayalam Show Thumbnails Visa miniatyrer Show Tile Edge Visa rutkant Show Tints/Shades Visa ljusa/mörka toner + Show Tool Cards Visa verktygskort Show Tool Tips Visa verktygstips Show Transparency Grid Visa transparensrutnät Show Video Rulers Visa videolinjaler @@ -3711,6 +3776,8 @@ digits Malayalam Malayalam Outlines Konturlinjer Outlines with Source Image Konturlinjer med källbild Source Image Källbild + Split View Delad vy + Divider Delningslinje Press and hold to view the source image Håll ned för att visa källbilden Image Trace View Vy för bildkalkering Snap Options Fästalternativ @@ -4165,6 +4232,8 @@ digits Malayalam Malayalam Unembed… Ta bort inbäddning… Ungroup Dela upp grupp Ungroup Color Group Dela upp färggrupp + Color Group Options Färggruppsalternativ + Color Group Options… Färggruppsalternativ… Unicode Unicode Unicode (UTF-16) Unicode (UTF-16) Unicode (UTF-8) Unicode (UTF-8) @@ -4968,6 +5037,8 @@ liquify-list-end {0}, {1} {0} och {1} @msg a freeform gradient keeps at least one point en fri gradient behåller minst en punkt @msg a gradient needs at least two stops en gradient behöver minst två stopp @msg a graphic style named `{to}` already exists det finns redan en grafisk stil med namnet `{to}` +@msg a swatch or color group named `{name}` already exists det finns redan en färgruta eller färggrupp med namnet `{name}` +@msg no colour group `{group}` ingen färggrupp `{group}` @msg a key object sits on that point ett nyckelobjekt ligger på den punkten @msg a page is missing en sida saknas @msg a page out of range en sida utanför intervallet @@ -5102,6 +5173,11 @@ liquify-list-end {0}, {1} {0} och {1} @msg no anchor points selected inga ankarpunkter är markerade @msg `points` must be two or three [x, y] pairs of numbers `points` måste vara två eller tre talpar [x, y] @msg direct-select two or three anchor points, or give `points` direktmarkera två eller tre ankarpunkter eller ange `points` +@msg the path is straight there, so no circle matches its curvature banan är rak där, så ingen cirkel matchar dess krökning +@msg the path has a cusp there, so it has no single curvature banan har en spets där, så den har ingen entydig krökning +@msg the path has a corner there, so it has no single curvature banan har ett hörn där, så den har ingen entydig krökning +@msg a guide has no curvature circle en stödlinje har ingen krökningscirkel +@msg the circle that matches the path there would reach past the canvas cirkeln som matchar banan där skulle nå utanför arbetsytan @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 @@ -5351,6 +5427,7 @@ liquify-list-end {0}, {1} {0} och {1} @msg the PDF is password-protected: give its password PDF-filen är lösenordsskyddad: ange lösenordet @msg the PDF password is wrong PDF-lösenordet är fel @msg the Save PDF dialog didn't open dialogrutan Spara PDF öppnades inte +@msg the Save PDF dialog is not open dialogrutan Spara PDF är inte öppen @msg the WMF header is damaged WMF-huvudet är skadat @msg the art could not be sampled grafiken kunde inte samplas @msg the art has no bounds grafiken har ingen avgränsning @@ -5574,6 +5651,7 @@ variable-list-end {0}, {1} {0} och {1} @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 +@msg give only one of `index`, `indices` and `t` ange bara en av `index`, `indices` och `t` @msg column must be true or a number from 1 column måste vara true eller ett tal från 1 @msg x and y must both be numbers x och y måste båda vara tal @msg "{0}" is not a colour: write it as #rrggbb "{0}" är inte en färg: skriv den som #rrggbb @@ -5737,6 +5815,49 @@ variable-list-end {0}, {1} {0} och {1} @msg the PSD file's layer groups are nested too deeply PSD-filens lagergrupper är kapslade för djupt @msg a layer of the PSD file is too large to read ett lager i PSD-filen är för stort för att läsas @msg the PSD file's layers take more memory to read than allowed PSD-filens lager kräver mer minne för att läsas än vad som tillåts +@msg the file is no longer loaded filen är inte längre inläst +@msg the layers can't be read ({e}): the file was placed as its merged image lagren kan inte läsas ({e}): filen placerades som sin sammanslagna bild +@msg 1 type layer came in as pixels: the text isn't editable 1 textlager kom in som pixlar: texten går inte att redigera +@msg {n} type layers came in as pixels: the text isn't editable {n} textlager kom in som pixlar: texten går inte att redigera +@msg 1 adjustment layer was not applied 1 justeringslager tillämpades inte +@msg {n} adjustment layers were not applied {n} justeringslager tillämpades inte +@msg 1 fill layer was not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels) 1 fyllningslager ritades inte (en övertonings- eller mönsterfyllning, en färg som inte kan läsas eller en form som inte lagrar några pixlar) +@msg {n} fill layers were not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels) {n} fyllningslager ritades inte (en övertonings- eller mönsterfyllning, en färg som inte kan läsas eller en form som inte lagrar några pixlar) +@msg the layer effects of 1 layer weren't drawn lagereffekterna för 1 lager ritades inte +@msg the layer effects of {n} layers weren't drawn lagereffekterna för {n} lager ritades inte +@msg the vector masks of 1 layer weren't applied vektormaskerna för 1 lager tillämpades inte +@msg the vector masks of {n} layers weren't applied vektormaskerna för {n} lager tillämpades inte +@msg the knockout of 1 layer wasn't applied utsparningen för 1 lager tillämpades inte +@msg the knockout of {n} layers wasn't applied utsparningen för {n} lager tillämpades inte +@msg 1 layer was left out (hidden layers and the layers clipped to them) 1 lager utelämnades (dolda lager och de lager som är urklippta mot dem) +@msg {n} layers were left out (hidden layers and the layers clipped to them) {n} lager utelämnades (dolda lager och de lager som är urklippta mot dem) +@msg 1 layer clipped to a fill layer that wasn't drawn was left out 1 lager urklippt mot ett fyllningslager som inte ritades utelämnades +@msg {n} layers clipped to fill layers that weren't drawn were left out {n} lager urklippta mot fyllningslager som inte ritades utelämnades +@msg layers in blend modes VectorCraft doesn't have ({modes}) were merged with the layers below them lager i blandningslägen som VectorCraft inte har ({modes}) slogs samman med lagren under dem +@msg 1 layer in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed 1 lager i ett blandningsläge som VectorCraft inte har kom in som Normal: sammanslagningen kräver mer minne än tillåtet +@msg {n} layers in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed {n} lager i blandningslägen som VectorCraft inte har kom in som Normal: sammanslagningen kräver mer minne än tillåtet +@msg 1 layer clipped to the layer below came in unclipped: the merge needs more memory than allowed 1 lager urklippt mot lagret under kom in utan urklipp: sammanslagningen kräver mer minne än tillåtet +@msg {n} layers clipped to the layer below came in unclipped: the merge needs more memory than allowed {n} lager urklippta mot lagret under kom in utan urklipp: sammanslagningen kräver mer minne än tillåtet +@msg hiddenLayers applies to a PSD file placed with layers: true hiddenLayers gäller en PSD-fil som placeras med layers: true +@msg importSlices: a linked PSD file is placed as its flat image; give link: false to embed it with its slices importSlices: en länkad PSD-fil placeras som sin platta bild; ange link: false för att bädda in den med dess skivor +@msg layers: a linked PSD file is placed as its flat image; leave link out or give link: false layers: en länkad PSD-fil placeras som sin platta bild; utelämna link eller ange link: false +@msg the slices can't be read ({e}) and were left out skivorna kan inte läsas ({e}) och utelämnades +@msg 1 slice lies outside the canvas or has no size and was left out 1 skiva ligger utanför arbetsytan eller saknar storlek och utelämnades +@msg {n} slices lie outside the canvas or have no size and were left out {n} skivor ligger utanför arbetsytan eller saknar storlek och utelämnades +@msg 1 slice would lie outside the canvas and was left out 1 skiva skulle ligga utanför arbetsytan och utelämnades +@msg {n} slices would lie outside the canvas and were left out {n} skivor skulle ligga utanför arbetsytan och utelämnades +@msg the slices' descriptor holds too many values skivornas deskriptor innehåller för många värden +@msg the slices' descriptor has a version other than 16 skivornas deskriptor har en annan version än 16 +@msg the slices are stored in version {v}, which isn't read skivorna är sparade i version {v}, som inte läses +@msg the file has {count} slices, more than the {MAX_SLICES} read filen har {count} skivor, fler än de {MAX_SLICES} som läses +@msg the slices' descriptor has no list of slices skivornas deskriptor har ingen lista över skivor +@msg the slices' descriptor lists something other than a slice skivornas deskriptor listar något annat än en skiva +@msg a slice in the slices' descriptor has no bounds en skiva i skivornas deskriptor saknar gränser +@msg a slice's bounds in the slices' descriptor aren't numbers gränserna för en skiva i skivornas deskriptor är inte tal +@msg a text in the slices has more than the {MAX_TEXT} characters read en text i skivorna har fler än de {MAX_TEXT} tecken som läses +@msg the slices' descriptor nests too deep skivornas deskriptor är kapslad för djupt +@msg the slices' descriptor has a reference of an unknown kind ({_1}) skivornas deskriptor har en referens av okänt slag ({_1}) +@msg the slices' descriptor has a value of an unknown type ({_1}) skivornas deskriptor har ett värde av okänd typ ({_1}) @msg the layers can't be read ({e}): the file opened as its merged image lagren kan inte läsas ({e}): filen öppnades som sin sammanslagna bild @msg {depth}-bit PSD files in this colour mode can't be read {depth}-bitars PSD-filer i det här färgläget kan inte läsas @msg the PSD file is cut short PSD-filen är avkortad @@ -5764,6 +5885,25 @@ variable-list-end {0}, {1} {0} och {1} Preserve Embedded Profiles Behåll inbäddade profiler Convert to Working Space Konvertera till arbetsfärgrymd Preserve Numbers Behåll värden + Profile Mismatches: Profilavvikelser: + Ask When Opening Fråga vid öppning + Ask When Pasting Fråga vid inklistring + Missing Profiles: Profiler som saknas: + Embedded Profile Mismatch Avvikande inbäddad profil + Missing Profile Profil saknas + Paste Profile Mismatch Profilavvikelse vid inklistring + “{name}” is not tagged with a {model} profile. ”{name}” har ingen {model}-profil. + “{name}” is tagged with the {model} profile “{profile}”, which is not the {model} working space “{working}”. ”{name}” har {model}-profilen ”{profile}”, som inte är {model}-arbetsfärgrymden ”{working}”. + Use the embedded profile Använd den inbäddade profilen + Convert the colors to the working space Konvertera färgerna till arbetsfärgrymden + Discard the embedded profile Ignorera den inbäddade profilen + Leave as is Lämna som det är + Assign the working space Tilldela arbetsfärgrymden + Assign profile: Tilldela profil: + Preserve the color numbers Behåll färgvärdena + Convert to keep the colors' appearance Konvertera så att färgerna ser likadana ut +@msg `{path}` goes with `{key}`: "assign" only `{path}` hör bara ihop med `{key}`: "assign" + The pasted colors come from a document whose {model} profile is “{from}”; this document's is “{to}”. De inklistrade färgerna kommer från ett dokument med {model}-profilen ”{from}”; det här dokumentets är ”{to}”. Texture Textur Craquelure… Krakelering… Grain… Korn… @@ -8162,6 +8302,8 @@ breakText Glyphs Glyfer # Path Precision Tools add-on: Tangent Circle. Tangent Circle… Tangentcirkel… Tangent Circle Tangentcirkel + Tangent Circle Tool Tangentcirkelverktyget + No tangent circle here Ingen tangentcirkel här Circle: Cirkel: @msg `ids` names an object twice `ids` anger ett objekt två gånger @msg select two or three paths or compound paths markera två eller tre banor eller sammansatta banor @@ -8177,6 +8319,16 @@ breakText Glyphs Glyfer @msg `circle` is past the last circle found ({found}) `circle` ligger efter den sista funna cirkeln ({found}) @msg object {value} is not a path or compound path objekt {value} är inte en bana eller sammansatt bana @msg these shapes are too small to measure formerna är för små för att mätas +# Path Precision Tools add-on: Add Bounding Rectangle and Add Bounding Circle. + Add Bounding Rectangle Lägg till omslutande rektangel + Add Bounding Circle Lägg till omslutande cirkel + Add Bounding Rectangle… Lägg till omslutande rektangel… + Add Bounding Circle… Lägg till omslutande cirkel… + One per Object En per objekt +@msg nothing to enclose inget att omsluta +@msg `offset` must be 0 or more `offset` måste vara 0 eller mer +@msg the shape would have no size formen skulle inte ha någon storlek +@msg the shape would reach past the edge of the canvas formen skulle sträcka sig utanför arbetsytans kant # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Dokumentverktyg Save a Timestamped Copy Spara en kopia med tidsstämpel @@ -8674,6 +8826,7 @@ digits Hindi Hindi @msg a design needs a name en design behöver ett namn @msg a dictionary grew too large ett dictionary-objekt blev för stort @msg a document keeps at most {_1} graph designs ett dokument rymmer högst {_1} diagramdesigner +@msg the art of a graph design in a graph series is drawn again from the design: edit the design to change it grafiken för en diagramdesign i en diagramserie ritas om från designen: redigera designen för att ändra den @msg a document keeps at most {_1} saved selections ett dokument rymmer högst {_1} sparade markeringar @msg a document keeps at most {_1} views ett dokument rymmer högst {_1} vyer @msg a document links at most {MAX_SVG_SCRIPTS} JavaScript files ett dokument länkar högst {MAX_SVG_SCRIPTS} JavaScript-filer @@ -9778,6 +9931,440 @@ digits Hindi Hindi @msg x and y must be given together x och y måste anges tillsammans @msg zone needs an anchor: dock beside a panel with anchor, or in a new dock column with side (Start or End) zone behöver ett ankare: docka bredvid en panel med anchor eller i en ny dockkolumn med side (Start eller End) @msg zoom must be positive zoom måste vara positiv +@msg 'caller', 'callee' and 'arguments' cannot be used on strict mode functions 'caller', 'callee' och 'arguments' kan inte användas på funktioner i strikt läge +@msg Alignment must be one of the choices Justering måste vara ett av alternativen +@msg Boolean.prototype.{name} was called on a value that is not a Boolean Boolean.prototype.{name} anropades på ett värde som inte är en Boolean +@msg CMYK images whose samples couldn't be read in CMYK were imported in RGB CMYK-bilder vars sampel inte kunde läsas i CMYK importerades i RGB +@msg Cannot write to the location of “{name}”; choose where to save it Det går inte att skriva till platsen för ”{name}”; välj var filen ska sparas +@msg DCS files can only be placed linked: use File › Place with Link on DCS-filer kan bara placeras länkade: använd Fil › Placera med Länka aktiverat +@msg Date.prototype method called on a value that is not a Date object en Date.prototype-metod anropades på ett värde som inte är ett Date-objekt +@msg Error.prototype.toString was called on a value that is not an object Error.prototype.toString anropades på ett värde som inte är ett objekt +@msg Function.prototype.toString was called on a value that is not a function Function.prototype.toString anropades på ett värde som inte är en funktion +@msg Import SVG Filter reads SVG files, not SVGZ Importera SVG-filter läser SVG-filer, inte SVGZ +@msg JSON.parse: {why} (at offset {at}) JSON.parse: {why} (vid position {at}) +@msg JSON.stringify cannot write a structure that contains itself JSON.stringify kan inte skriva en struktur som innehåller sig själv +@msg Line Gap must be a number Radmellanrum måste vara ett tal +@msg Namespace.prototype.toString needs a Namespace Namespace.prototype.toString kräver ett Namespace-objekt +@msg New Document profiles need the preferences folder, which this run doesn't have Profiler för nytt dokument behöver inställningsmappen, som den här körningen saknar +@msg Number.prototype.{name} was called on a value that is not a number Number.prototype.{name} anropades på ett värde som inte är ett tal +@msg Object.create's prototype must be an object or null prototypen för Object.create måste vara ett objekt eller null +@msg Object.{function} was given a value that is not an object Object.{function} fick ett värde som inte är ett objekt +@msg QName.prototype.toString needs a QName QName.prototype.toString kräver ett QName-objekt +@msg RegExp.prototype.{name} was called on a value that is not a RegExp object RegExp.prototype.{name} anropades på ett värde som inte är ett RegExp-objekt +@msg Stencil Bridges: the selected art is too large or too detailed to bridge Schablonbryggor: den markerade teckningen är för stor eller för detaljerad för att förses med bryggor +@msg String.prototype.toString was called on a value that is not a string String.prototype.toString anropades på ett värde som inte är en sträng +@msg The {name} profile could not be read, so the new document has the default settings: {reason} Profilen {name} kunde inte läsas, så det nya dokumentet har standardinställningarna: {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 Överfyllning: fler än {_1} objektpar ligger tillräckligt nära varandra för överfyllning, eller så delar för många objekt samma horisontella område; överfyll färre objekt åt gången +@msg Weed Box and Lines: no weeding line fits outside the art, and the weed box is off Rensningsram och rensningslinjer: ingen rensningslinje får plats utanför teckningen, och rensningsramen är avstängd +@msg \\ at end of pattern \\ i slutet av mönstret +@msg `alignOn` cannot be empty `alignOn` får inte vara tomt +@msg `alignOn` must be a string `alignOn` måste vara en sträng +@msg `align` must be a string `align` måste vara en sträng +@msg `answer` for this {kind} dialog must be one of: {_1} `answer` för den här dialogrutan av typen {kind} måste vara något av: {_1} +@msg `artboard` must be the index of an artboard of the document `artboard` måste vara indexet för en rityta i dokumentet +@msg `artboardsAt` must be [x, y] `artboardsAt` måste vara [x, y] +@msg `artboards` names an artboard the document does not have `artboards` anger en rityta som dokumentet inte har +@msg `artboards` names an artboard twice `artboards` anger en rityta två gånger +@msg `at` must be [x, y] (got {at}) `at` måste vara [x, y] (fick {at}) +@msg `at` must be a point [x, y] `at` måste vara en punkt [x, y] +@msg `beside` needs `side` `beside` kräver `side` +@msg `code` must be a whole number `code` måste vara ett heltal +@msg `colorMode` must be one of rgb, cmyk `colorMode` måste vara något av rgb, cmyk +@msg `colors` does not apply to the {name} reduction `colors` gäller inte för reduceringen {name} +@msg `colors` must be a whole number from 2 to 256 `colors` måste vara ett heltal från 2 till 256 +@msg `colors` must be at least 9 for the uniform reduction `colors` måste vara minst 9 för reduceringen uniform +@msg `colors` must be between 1 and {MAX_THEME_COLORS} (got {n}) `colors` måste vara mellan 1 och {MAX_THEME_COLORS} (fick {n}) +@msg `count` must be a whole number from 0 to {MAX_COUNT} `count` måste vara ett heltal från 0 till {MAX_COUNT} +@msg `ditherAmount` must be a number from 0 to 100 `ditherAmount` måste vara ett tal från 0 till 100 +@msg `fidelity` must be from {lo} to {hi} pt `fidelity` måste vara från {lo} till {hi} pt +@msg `focal` and `radius` cannot be used together `focal` och `radius` kan inte användas tillsammans +@msg `focal` must be an array of [subpath, anchor] pairs `focal` måste vara en array av par [subpath, anchor] +@msg `focal` names [{si}, {ai}], which is not an anchor of the path `focal` anger [{si}, {ai}], som inte är en ankarpunkt på banan +@msg `glyphAlternate` takes only null, which takes a glyph choice away (text.setGlyphAlternate makes one) `glyphAlternate` tar bara null, som tar bort ett glyfval (text.setGlyphAlternate skapar ett) +@msg `group` must be one of {_1} `group` måste vara något av {_1} +@msg `group` must be the Objects on Path group of `member` and `target` `group` måste vara den grupp Objekt på bana som `member` och `target` tillhör +@msg `id` is an object id, not {v} `id` är ett objekt-id, inte {v} +@msg `item` needs `index` `item` kräver `index` +@msg `kerningBefore` belongs to a line's first character, not to a character style (text.setRangeStyle sets it) `kerningBefore` hör till det första tecknet på en rad, inte till en teckenstil (text.setRangeStyle anger det) +@msg `kinsokuType` must be "pushInFirst", "pushOutFirst" or "pushOutOnly" `kinsokuType` måste vara "pushInFirst", "pushOutFirst" eller "pushOutOnly" +@msg `leader` must be a string `leader` måste vara en sträng +@msg `max` must be 1 to {MAX_SUGGESTIONS} `max` måste vara 1 till {MAX_SUGGESTIONS} +@msg `name` must be a name that is not empty `name` måste vara ett namn som inte är tomt +@msg `name` must not be empty `name` får inte vara tomt +@msg `origin` must be [x, y] in points `origin` måste vara [x, y] i punkter +@msg `picks` must be an array (got {v}) `picks` måste vara en array (fick {v}) +@msg `picks` must hold 1 to {MAX_PICKS} picks (got {_1}) `picks` måste innehålla 1 till {MAX_PICKS} val (fick {_1}) +@msg `points` must hold from 2 to 100000 points `points` måste innehålla från 2 till 100000 punkter +@msg `radius` must be 0 or more `radius` måste vara 0 eller mer +@msg `rect` must be [x, y, width, height] `rect` måste vara [x, y, width, height] +@msg `rect` must be [x0, y0, x1, y1] (got {r}) `rect` måste vara [x0, y0, x1, y1] (fick {r}) +@msg `replace` must be a string `replace` måste vara en sträng +@msg `rows` must be lists of numbers or nulls, not {r} `rows` måste vara listor med tal eller null, inte {r} +@msg `scale` must be a number from 0.001 to 1000 `scale` måste vara ett tal från 0,001 till 1000 +@msg `scope.{key}` must be a non-empty array `scope.{key}` måste vara en icke-tom array +@msg `side` must be "left", "right", "top" or "bottom" `side` måste vara "left", "right", "top" eller "bottom" +@msg `side` places the artboard: leave out x, y, width and height `side` placerar ritytan: utelämna x, y, width och height +@msg `source` is the only path in series group `target` `source` är den enda banan i seriegruppen `target` +@msg `spacing` makes more than {MAX_COUNT} lines across the box `spacing` ger fler än {MAX_COUNT} linjer över ramen +@msg `spacing` must be more than 0 and at most {MAX_DISTANCE} pt `spacing` måste vara större än 0 och högst {MAX_DISTANCE} pt +@msg `target` must be an object of the same Objects on Path group as `member` `target` måste vara ett objekt i samma grupp Objekt på bana som `member` +@msg `tolerance` must be from 0 to 100 pt `tolerance` måste vara från 0 till 100 pt +@msg `version` must be 0 or {_1} `version` måste vara 0 eller {_1} +@msg `version` must be 0 or {newest} `version` måste vara 0 eller {newest} +@msg `warichuAlign` must be one of {_1} `warichuAlign` måste vara något av {_1} +@msg `warichuLines` must be a whole number from {_1} to {_2} `warichuLines` måste vara ett heltal från {_1} till {_2} +@msg `weight` must be from 0.01 to 1000 pt `weight` måste vara från 0,01 till 1000 pt +@msg `weights` must be a list of {_1} numbers, one per row (got {v}) `weights` måste vara en lista med {_1} tal, ett per rad (fick {v}) +@msg `xml` must be a string `xml` måste vara en sträng +@msg `{KEY}` entry {n} gives the paragraph at byte {start} of {_1} other indents than an entry before it post {n} i `{KEY}` ger stycket vid byte {start} i {_1} andra indrag än en tidigare post +@msg `{KEY}` entry {n} must be an object post {n} i `{KEY}` måste vara ett objekt +@msg `{KEY}` entry {n} sets neither `leftIndent` nor `firstLineIndent` post {n} i `{KEY}` anger varken `leftIndent` eller `firstLineIndent` +@msg `{KEY}` entry {n}: `id` must be an object id post {n} i `{KEY}`: `id` måste vara ett objekt-id +@msg `{KEY}` entry {n}: `start` must be a byte offset post {n} i `{KEY}`: `start` måste vara en byteposition +@msg `{KEY}` entry {n}: `{k}` must be a number from -{MAX_PARA} to {MAX_PARA} pt post {n} i `{KEY}`: `{k}` måste vara ett tal från -{MAX_PARA} till {MAX_PARA} pt +@msg `{KEY}` entry {n}: no paragraph of {_1} starts at byte {start} post {n} i `{KEY}`: inget stycke i {_1} börjar vid byte {start} +@msg `{KEY}` entry {n}: unknown key `{k}` post {n} i `{KEY}`: okänd nyckel `{k}` +@msg `{KEY}` entry {n}: {_1} is not a type object post {n} i `{KEY}`: {_1} är inte ett textobjekt +@msg `{KEY}` is empty `{KEY}` är tom +@msg `{KEY}` must be a list `{KEY}` måste vara en lista +@msg `{KEY}` takes at most {MAX_PARAGRAPH_INDENTS} entries (got {_1}) `{KEY}` tar högst {MAX_PARAGRAPH_INDENTS} poster (fick {_1}) +@msg `{KEY}` takes no `{other}` beside it `{KEY}` tar inget `{other}` bredvid sig +@msg `{base}` is larger than {_1} MB `{base}` är större än {_1} MB +@msg `{base}` is not in the DCS file's folder `{base}` finns inte i DCS-filens mapp +@msg `{key}` holds more than {MAX_EDIT_WORDS} words `{key}` innehåller fler än {MAX_EDIT_WORDS} ord +@msg `{key}` must be 0 or more `{key}` måste vara 0 eller mer +@msg `{key}` must be [x, y] numbers `{key}` måste vara talen [x, y] +@msg `{key}` must be a list of words `{key}` måste vara en lista med ord +@msg `{key}` must be a list, not {v} `{key}` måste vara en lista, inte {v} +@msg `{key}` must be a number or null, not {v} `{key}` måste vara ett tal eller null, inte {v} +@msg `{key}` must be a whole number of 0 or more `{key}` måste vara ett heltal som är 0 eller mer +@msg `{key}` must be from 0 to {MAX_DISTANCE} pt `{key}` måste vara från 0 till {MAX_DISTANCE} pt +@msg `{key}` must be from 0.01 to 1000 pt `{key}` måste vara från 0,01 till 1000 pt +@msg `{key}` must be from {lo} to {hi}, not {v} `{key}` måste vara från {lo} till {hi}, inte {v} +@msg `{key}` must be one of auto, always, never `{key}` måste vara något av auto, always, never +@msg `{key}` must be one of miter, round, bevel `{key}` måste vara något av miter, round, bevel +@msg `{key}` must be one word of at most {_1} characters `{key}` måste vara ett ord på högst {_1} tecken +@msg `{key}` must hold single words of at most {_1} characters `{key}` måste innehålla enstaka ord på högst {_1} tecken +@msg `{key}` must name an object attached to the path of an Objects on Path group `{key}` måste ange ett objekt som är fäst på banan i en grupp Objekt på bana +@msg `{key}` names an object that is hidden or locked `{key}` anger ett objekt som är dolt eller låst +@msg `{name}` is a file of its own, which can only be found next to the DCS file's path `{name}` är en egen fil, som bara kan hittas intill DCS-filens sökväg +@msg `{name}`: {_1}: {e} `{name}`: {_1}: {e} +@msg `{u}` is no Unicode character `{u}` är inget Unicode-tecken +@msg `{word}` isn't in the custom dictionary `{word}` finns inte i den egna ordlistan +@msg a CMap has too many mappings en CMap har för många mappningar +@msg a \\u escape needs four hexadecimal digits en \\u-escapesekvens kräver fyra hexadecimala siffror +@msg a comma in an XPath expression must separate function arguments ett kommatecken i ett XPath-uttryck måste skilja funktionsargument åt +@msg a document holds at most {_1} SVG filters ett dokument rymmer högst {_1} SVG-filter +@msg a document with unsaved changes has no recovery copy ett dokument med osparade ändringar har ingen återställningskopia +@msg a font's data is too large ett typsnitts data är för stora +@msg a font's subroutines are too large ett typsnitts subrutiner är för stora +@msg a function declaration without a name en funktionsdeklaration utan namn +@msg a host value has too many entries ett värde från värden har för många poster +@msg a host value is nested too deep ett värde från värden är för djupt kapslat +@msg a namespace declaration uses a reserved prefix or URI en namnrymdsdeklaration använder ett reserverat prefix eller en reserverad URI +@msg a namespace qualifier is undefined en namnrymdskvalificerare är odefinierad +@msg a namespace with an empty URI cannot have a prefix en namnrymd med tom URI kan inte ha ett prefix +@msg a number has no digits ett tal saknar siffror +@msg a number's exponent has no digits ett tals exponent saknar siffror +@msg a number's fraction has no digits ett tals decimaldel saknar siffror +@msg a property descriptor cannot have both a value or writable and a get or set en egenskapsbeskrivning kan inte ha både value eller writable och get eller set +@msg a property descriptor must be an object en egenskapsbeskrivning måste vara ett objekt +@msg a property's {name} must be a function or undefined en egenskaps {name} måste vara en funktion eller undefined +@msg a stream in it would decode to more than 256 MB, or its decode parameters can't be applied en ström i den skulle avkodas till mer än 256 MB, eller så kan dess avkodningsparametrar inte tillämpas +@msg a string holds a control character en sträng innehåller ett styrtecken +@msg a string holds an escape sequence JSON does not have en sträng innehåller en escapesekvens som JSON inte har +@msg a string is not closed en sträng är inte avslutad +@msg an SVG filter is named by its id: give `xml` with `name` ett SVG-filter får sitt namn av sitt id: ange `xml` tillsammans med `name` +@msg an XML element has two attributes with the same name ett XML-element har två attribut med samma namn +@msg an XML value cannot be inserted into itself or its descendants ett XML-värde kan inte infogas i sig självt eller i sina underordnade +@msg an XML value's children cannot be assigned by position underordnade till ett XML-värde kan inte tilldelas efter position +@msg an XML value's children cannot be deleted by position underordnade till ett XML-värde kan inte tas bort efter position +@msg an XMLList converts to XML only when it has one item en XMLList konverteras till XML bara när den har en post +@msg an XPath node test is missing ett XPath-nodtest saknas +@msg an XPath operand is missing en XPath-operand saknas +@msg an XPath operator is missing en XPath-operator saknas +@msg an XPath predicate or step cannot follow here ett XPath-predikat eller XPath-steg kan inte följa här +@msg an XPath predicate or step follows a value that is not a node-set ett XPath-predikat eller XPath-steg följer på ett värde som inte är en noduppsättning +@msg an XPath step is missing ett XPath-steg saknas +@msg an image couldn't be decoded and is missing from the picture en bild kunde inte avkodas och saknas i bilden +@msg an image of {w} × {h} pixels is too large to convert (at most {_1} pixels) en bild på {w} × {h} pixlar är för stor för att konverteras (högst {_1} pixlar) +@msg area type in a thread cannot use Dynamic Text: {frames} områdestext i ett textflöde kan inte använda Dynamisk text: {frames} +@msg at least one row that isn't excluded needs a weight above 0 minst en rad som inte är utesluten behöver en vikt över 0 +@msg bad point {v}: expected [x, y] ogiltig punkt {v}: väntade [x, y] +@msg blend must be a mode name blend måste vara namnet på ett läge +@msg both sides of an XPath | must select nodes båda sidor av ett | i XPath måste välja noder +@msg canceled avbrutet +@msg character dimensions cannot be represented with the source text transform teckenmåtten kan inte återges med källans texttransformering +@msg character dimensions cannot be represented with the target text transform teckenmåtten kan inte återges med målets texttransformering +@msg continuation must be an array of path chunks continuation måste vara en array av bandelar +@msg continuation requires points continuation kräver points +@msg each path chunk must contain 1 to 4096 points varje bandel måste innehålla 1 till 4096 punkter +@msg each pick is {{at: [x, y]}} or {{rect: [x0, y0, x1, y1]}} (got {v}) varje val är {{at: [x, y]}} eller {{rect: [x0, y0, x1, y1]}} (fick {v}) +@msg each weight must be a number of 0 or more (got {v}) varje vikt måste vara ett tal som är 0 eller mer (fick {v}) +@msg finally table {t} out of range finally-tabell {t} utanför intervallet +@msg flags cannot be given with a RegExp object flaggor kan inte anges tillsammans med ett RegExp-objekt +@msg function declaration index out of range funktionsdeklarationens index ligger utanför intervallet +@msg give `char`, `text`, `code` or `unicode` ange `char`, `text`, `code` eller `unicode` +@msg give `count` or `spacing`, not both ange `count` eller `spacing`, inte båda +@msg give `name`, an SVG filter's name ange `name`, namnet på ett SVG-filter +@msg give `path`, an SVG file, or `svg`, SVG text ange `path`, en SVG-fil, eller `svg`, SVG-text +@msg give `xml`, one SVG element ange `xml`, ett SVG-element +@msg give exactly one of `at`, `rect` and `points` ange exakt en av `at`, `rect` och `points` +@msg give exactly one of `path`, `data` and `dataBase64` ange exakt en av `path`, `data` och `dataBase64` +@msg give index or indexes, not both ange index eller indexes, inte båda +@msg give opacity or blend ange opacity eller blend +@msg handler at {_1} expects {_2} values but its range starts with {d} hanteraren vid {_1} förväntar sig {_2} värden men dess intervall börjar med {d} +@msg handler depth too large hanterarens djup är för stort +@msg handler range {_1}..{_2} out of range hanterarintervallet {_1}..{_2} ligger utanför intervallet +@msg hiddenLayers must be true or false hiddenLayers måste vara true eller false +@msg hvcC hvcC +@msg images in a spot ink whose samples couldn't be read were imported in RGB bilder i en dekorfärg vars sampel inte kunde läsas importerades i RGB +@msg images past the most pixels one file may hold were left out bilder utöver det största antal pixlar en fil får innehålla utelämnades +@msg images too large to read were left out bilder som är för stora för att läsas utelämnades +@msg indexes may hold at most {MAX_GUIDE_INDEXES} entries indexes får innehålla högst {MAX_GUIDE_INDEXES} poster +@msg indexes must be an array of guide indexes indexes måste vara en array av stödlinjeindex +@msg instruction out of range instruktionen ligger utanför intervallet +@msg instruction {pc} ({op}) pops below the stack instruktion {pc} ({op}) hämtar fler värden än stacken innehåller +@msg instruction {pc} reached with stack depths {seen} and {d} instruktion {pc} nås med stackdjupen {seen} och {d} +@msg invalid group ogiltig grupp +@msg invalid object id {v}: expected a non-negative integer ogiltigt objekt-id {v}: ett icke-negativt heltal förväntades +@msg invalid regular expression flag '{_1}' ogiltig flagga '{_1}' för reguljärt uttryck +@msg invalid regular expression: {m} ogiltigt reguljärt uttryck: {m} +@msg invalid time value ogiltigt tidsvärde +@msg it draws its image through a clipping path den ritar sin bild genom en urklippsbana +@msg it draws no image den ritar ingen bild +@msg it is larger than {MAX_DICTIONARY_FILE_BYTES} bytes den är större än {MAX_DICTIONARY_FILE_BYTES} byte +@msg it isn't a file det är inte en fil +@msg it names {_1} plates, and at most {MAX_PLATES} are read den anger {_1} plåtar, och högst {MAX_PLATES} läses +@msg its art is too long or too detailed for a head dess grafik är för lång eller för detaljerad för en pilspets +@msg its art paints nothing dess grafik målar ingenting +@msg its image is too large to read dess bild är för stor för att läsas +@msg its plates are too large: more than {MAX_SAMPLES} pixels together dess plåtar är för stora: fler än {MAX_SAMPLES} pixlar sammanlagt +@msg its plates are too large: {_1} plates of {w} × {h} pixels dess plåtar är för stora: {_1} plåtar på {w} × {h} pixlar +@msg its plates can't be kept together dess plåtar kan inte hållas samman +@msg its shapes could not be combined into one dess former kunde inte kombineras till en +@msg jump to {pc}, past the end hopp till {pc}, förbi slutet +@msg legacyNameEncoding must be one of {_1} legacyNameEncoding måste vara något av {_1} +@msg localize: the first argument must be a localization object or a string localize: det första argumentet måste vara ett lokaliseringsobjekt eller en sträng +@msg missing `picks` `picks` saknas +@msg missing `word` `word` saknas +@msg needs a closing quote after the name kräver ett avslutande citattecken efter namnet +@msg needs a name kräver ett namn +@msg needs a name of at most 64 bytes kräver ett namn på högst 64 byte +@msg needs a name of letters, digits and _, or a quoted name kräver ett namn med bokstäver, siffror och _, eller ett namn inom citattecken +@msg needs a name without control characters kräver ett namn utan styrtecken +@msg nesting too deep för djup kapsling +@msg no HP-GL format inget HP-GL-format +@msg no New Document profile called `{shown}` ({_1}) ingen profil för nytt dokument med namnet `{shown}` ({_1}) +@msg no SVG filter at index {k} inget SVG-filter vid index {k} +@msg no arrowheads file here ingen pilspetsfil här +@msg no character has code {code} inget tecken har koden {code} +@msg no custom arrowhead {name} (see stroke.arrowheads.list) ingen anpassad pilspets {name} (se stroke.arrowheads.list) +@msg no file to open ingen fil att öppna +@msg no instructions inga instruktioner +@msg no layer to rename inget lager att byta namn på +@msg no random numbers ({e}) inga slumptal ({e}) +@msg no selected or given object has a visible 3D effect inget markerat eller angivet objekt har en synlig 3D-effekt +@msg no such artboard {v} ritytan {v} finns inte +@msg no symbol named `{_1}` ingen symbol med namnet `{_1}` +@msg node {_1} already has the text variable `{_2}` nod {_1} har redan textvariabeln `{_2}` +@msg not a DCS file inte en DCS-fil +@msg not a RegExp object inte ett RegExp-objekt +@msg not a regular expression inte ett reguljärt uttryck +@msg not an action set: the text doesn't start with /version and a number inte en åtgärdsuppsättning: texten börjar inte med /version och ett tal +@msg nothing to repeat inget att upprepa +@msg object {_1} needs a 3D effect objekt {_1} behöver en 3D-effekt +@msg object {_1}: a hollow Extrude & Bevel has no caps: turn on Cap to map a graphic objekt {_1}: en ihålig Extrudera och fasa saknar lock: aktivera Lock för att mappa en grafik +@msg object {_1}: with a depth of 0 the object has one face: map its graphics onto the front objekt {_1}: med djupet 0 har objektet en enda yta: mappa dess grafik på framsidan +@msg object {_1}: {_2} objekt {_1}: {_2} +@msg object {_1}: {e} objekt {_1}: {e} +@msg object {_1}: {name} at index {index} has no lighting presets; set its lights with effect.setParams objekt {_1}: {name} vid index {index} har inga belysningsförinställningar; ange dess ljus med effect.setParams +@msg opacity must be a number opacity måste vara ett tal +@msg operand too large operanden är för stor +@msg path chunks must share their boundary point bandelar måste dela sin gränspunkt +@msg pdfCompatible: false needs the artboards to keep the editable artwork when useArtboards is false pdfCompatible: false kräver ritytorna för att behålla den redigerbara grafiken när useArtboards är false +@msg point x must be a number punktens x måste vara ett tal +@msg point y must be a number punktens y måste vara ett tal +@msg points must be [x,y] pairs points måste vara par [x,y] +@msg points must be finite canvas points points måste vara ändliga punkter på arbetsytan +@msg range out of order in character class intervall i fel ordning i teckenklass +@msg reduce of an empty array with no initial value reduce på en tom array utan startvärde +@msg regular expression flag '{_1}' given twice flaggan '{_1}' för reguljärt uttryck anges två gånger +@msg sampled text would exceed the canvas (coordinates out of range) den samplade texten skulle hamna utanför arbetsytan (koordinater utanför intervallet) +@msg select an SVG filter markera ett SVG-filter +@msg select an object with a 3D effect markera ett objekt med en 3D-effekt +@msg select an object with a 3D effect, or give its id in ids markera ett objekt med en 3D-effekt, eller ange dess id i ids +@msg select one layer, group or object to rename markera ett lager, en grupp eller ett objekt att byta namn på +@msg select the art to weed markera teckningen som ska rensas +@msg select the banner, or mark every artboard markera bannern, eller märk upp alla ritytor +@msg select type on a path or area type markera text på bana eller områdestext +@msg source text transform is collapsed or unrepresentable källans texttransformering är kollapsad eller kan inte återges +@msg table must be true or false table måste vara true eller false +@msg takes one name tar ett namn +@msg target text transform is collapsed or unrepresentable målets texttransformering är kollapsad eller kan inte återges +@msg that makes too many pieces (at most 100000) or dash steps: simplify the dash pattern or make the dashes longer det ger för många delar (högst 100000) eller strecksteg: förenkla streckmönstret eller gör strecken längre +@msg the Layers panel is not shown panelen Lager visas inte +@msg the Layers panel's search, filter or Show Layers Only hides its row sökningen, filtret eller Visa endast lager i panelen Lager döljer dess rad +@msg the Objects on Path group is hidden or locked gruppen Objekt på bana är dold eller låst +@msg the SVG file is larger than {MAX_IMPORT_BYTES} bytes SVG-filen är större än {MAX_IMPORT_BYTES} byte +@msg the XML operation needs an XML or XMLList value XML-åtgärden kräver ett XML- eller XMLList-värde +@msg the XPath expression does not evaluate to a node-set XPath-uttrycket ger ingen noduppsättning +@msg the XPath expression ends early XPath-uttrycket slutar för tidigt +@msg the XPath expression has an unmatched ) XPath-uttrycket har en ) utan motsvarande ( +@msg the XPath expression has an unmatched ] XPath-uttrycket har en ] utan motsvarande [ +@msg the XPath expression has an unmatched closing bracket XPath-uttrycket har en avslutande parentes utan inledande +@msg the XPath expression selects a namespace node, which is not an XML value XPath-uttrycket väljer en namnrymdsnod, som inte är ett XML-värde +@msg the XPath expression selects the root node, which is not an XML value XPath-uttrycket väljer rotnoden, som inte är ett XML-värde +@msg the XPath function {name} needs a node-set XPath-funktionen {name} kräver en noduppsättning +@msg the XPath function {name} takes the wrong number of arguments XPath-funktionen {name} fick fel antal argument +@msg the XPath name functions need a node-set XPath-namnfunktionerna kräver en noduppsättning +@msg the XPath prefix {shown} is not bound to a namespace XPath-prefixet {shown} är inte bundet till en namnrymd +@msg the XPath variable ${shown} is not bound XPath-variabeln ${shown} är inte bunden +@msg the artwork is too large for EPS: what follows 256 MB of PostScript was left out grafiken är för stor för EPS: det som följer efter 256 MB PostScript utelämnades +@msg the banner has no width or height bannern saknar bredd eller höjd +@msg the bitmaps hold more pixels than one file may bitmapparna innehåller fler pixlar än en fil får innehålla +@msg the code runs past its last instruction koden fortsätter förbi sin sista instruktion +@msg the curve tolerance must be from 0.01 to 10 points kurvtoleransen måste vara från 0,01 till 10 punkter +@msg the custom dictionary couldn't be saved to {_1}: {e} den egna ordlistan kunde inte sparas i {_1}: {e} +@msg the custom dictionary {_1} can't be read ({why}), so it is left as it is den egna ordlistan {_1} kan inte läsas ({why}), så den lämnas som den är +@msg the document already has an SVG filter named {name} dokumentet har redan ett SVG-filter med namnet {name} +@msg the document has another SVG filter named {name}: use svgFilter.apply, or svgFilter.define with `replace` to edit it dokumentet har ett annat SVG-filter med namnet {name}: använd svgFilter.apply, eller svgFilter.define med `replace` för att redigera det +@msg the document has no SVG filter named {name} dokumentet har inget SVG-filter med namnet {name} +@msg the document has no SVG filter named {r} dokumentet har inget SVG-filter med namnet {r} +@msg the document has no color swatches dokumentet har inga färgrutor +@msg the document's swatches hold {_1} colors; the document reduction takes at most 255 dokumentets färgrutor innehåller {_1} färger; reduceringen document tar högst 255 +@msg the file isn't valid SVG: {e} filen är inte giltig SVG: {e} +@msg the file names no plate filen anger ingen plåt +@msg the grommet inset is too large for the banner öljetternas avstånd från kanten är för stort för bannern +@msg the guide is hidden or locked stödlinjen är dold eller låst +@msg the hem is too deep for the banner fållen är för djup för bannern +@msg the library's file is outside the read roots bibliotekets fil ligger utanför läsrötterna +@msg a linked JavaScript file is outside the read roots en länkad JavaScript-fil ligger utanför läsrötterna +@msg the line is too long, or the paths it passes too many, to check linjen är för lång, eller passerar för många banor, för att kunna kontrolleras +@msg the method needs an XML value metoden kräver ett XML-värde +@msg the parameters or body do not form one function parametrarna eller funktionskroppen bildar inte en funktion +@msg the pasted SVG filter {name} draws differently from the document's filter of that name, and no free name fits it det inklistrade SVG-filtret {name} ritar annorlunda än dokumentets filter med det namnet, och inget ledigt namn passar det +@msg the paths are too many or too tangled to find where they cross banorna är för många eller för intrasslade för att hitta var de korsar varandra +@msg the pen table holds more than 255 pens penntabellen innehåller fler än 255 pennor +@msg the plates can't be kept plåtarna kan inte behållas +@msg the position table does not match the instructions positionstabellen stämmer inte med instruktionerna +@msg the prompt's text is longer than {MAX_PROMPT_BYTES} bytes promptens text är längre än {MAX_PROMPT_BYTES} byte +@msg the radix must be between 2 and 36 talbasen måste vara mellan 2 och 36 +@msg the rectangle or line reaches too many paths to check rektangeln eller linjen når för många banor för att kunna kontrolleras +@msg the selected art is nested more than {MAX_DEPTH} levels deep den markerade teckningen är kapslad djupare än {MAX_DEPTH} nivåer +@msg the selected art is too large to measure den markerade teckningen är för stor för att mätas +@msg the selection has no outlines to weed around markeringen har inga ytterlinjer att rensa runt +@msg the spacing makes more than {MAX_GROMMETS} grommets avståndet ger fler än {MAX_GROMMETS} öljetter +@msg the value bind was called on is not a function värdet som bind anropades på är inte en funktion +@msg the value is not a valid XML name värdet är inte ett giltigt XML-namn +@msg the value is not an XML attribute name värdet är inte ett XML-attributnamn +@msg the value is not an XML name värdet är inte ett XML-namn +@msg the weeding lines cross the art's outlines too many times to measure; use fewer lines rensningslinjerna korsar teckningens ytterlinjer för många gånger för att kunna mätas; använd färre linjer +@msg the weeding lines pass too close to too many outline segments to measure; use fewer lines or a smaller gap rensningslinjerna går för nära för många ytterlinjesegment för att kunna mätas; använd färre linjer eller ett mindre mellanrum +@msg the weeding lines would be more than {max_pieces} pieces rensningslinjerna skulle bli fler än {max_pieces} delar +@msg the {_1} plate lies outside the file plåten {_1} ligger utanför filen +@msg there is no banner to mark det finns ingen banner att märka upp +@msg this is a binary DXF file, which can't be read: save it from the CAD app as an ASCII DXF and open that det här är en binär DXF-fil, som inte kan läsas: spara den från CAD-appen som ASCII DXF och öppna den filen +@msg this warp's points can't be edited: use Reset with Mesh first den här förvrängningens punkter kan inte redigeras: använd Återställ med nät först +@msg toExponential() digits must be between 0 and 20 antalet siffror för toExponential() måste vara mellan 0 och 20 +@msg toFixed() digits must be between 0 and 20 antalet siffror för toFixed() måste vara mellan 0 och 20 +@msg toISOString is not a function toISOString är inte en funktion +@msg toPrecision() argument must be between 1 and 21 argumentet till toPrecision() måste vara mellan 1 och 21 +@msg toSource: a getter cannot be written as source toSource: en getter kan inte skrivas som källkod +@msg toSource: an array with properties besides its elements, a property that is not enumerable or another prototype cannot be written as source toSource: en array med egenskaper utöver sina element, en egenskap som inte är uppräkningsbar eller en annan prototyp kan inte skrivas som källkod +@msg toSource: an object with a property that is not enumerable, or whose prototype is not Object.prototype, cannot be written as source toSource: ett objekt med en egenskap som inte är uppräkningsbar, eller vars prototyp inte är Object.prototype, kan inte skrivas som källkod +@msg toSource: the source is too long toSource: källkoden är för lång +@msg toSource: the value contains itself toSource: värdet innehåller sig självt +@msg toSource: the value has too many entries toSource: värdet har för många poster +@msg toSource: the value is nested too deep toSource: värdet är för djupt kapslat +@msg toString is not a function toString är inte en funktion +@msg too many quantifiers för många kvantifierare +@msg turn on at least one side aktivera minst en sida +@msg unknown OpenType feature `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt; prefix - to turn off; swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take an alternate's number as `tag=N` with N from 0 to {_1}, as `salt=2`) okänd OpenType-funktion `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt; prefixet - stänger av; swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom och aalt tar ett alternativs nummer som `tag=N` med N från 0 till {_1}, som `salt=2`) +@msg unknown dither `{d}` (diffusion, pattern, noise or none) okänd dithering `{d}` (diffusion, pattern, noise eller none) +@msg unknown panel `{panel}` okänd panel `{panel}` +@msg unknown parameter `{key}` okänd parameter `{key}` +@msg unknown reduction `{reduction}` (selective, perceptual, adaptive, web, gray, blackWhite, uniform or document) okänd reducering `{reduction}` (selective, perceptual, adaptive, web, gray, blackWhite, uniform eller document) +@msg unmatched ')' ')' utan motsvarande '(' +@msg unterminated character class oavslutad teckenklass +@msg unterminated group oavslutad grupp +@msg with no hem and no grommets there is nothing to mark utan fåll och utan öljetter finns det inget att märka upp +@msg wordGap and lineGap need area type in the selection wordGap och lineGap kräver områdestext i markeringen +@msg xpath needs its variables as an object xpath kräver sina variabler som ett objekt +@msg xpath needs the expression as a string xpath kräver uttrycket som en sträng +@msg {GRANT_NOT_REMOVED}, and its settings and cache can't be moved back from {_1} to {_2}: {e} {GRANT_NOT_REMOVED}, och dess inställningar och cache kan inte flyttas tillbaka från {_1} till {_2}: {e} +@msg {_1} is not a folder: {e} {_1} är inte en mapp: {e} +@msg {_1}: {_2} and {_3} are in the way {_1}: {_2} och {_3} ligger i vägen +@msg {code}: {0} {code}: {0} +@msg {dir}: {e} {dir}: {e} +@msg {file} names more than one linked JavaScript file {file} anger fler än en länkad JavaScript-fil +@msg {k}: a custom arrowhead's path needs an area to fill and at most {most} anchors and {most} subpaths, each anchor within {far} head units of its tip {k}: banan för en anpassad pilspets behöver en yta att fylla och högst {most} ankarpunkter och {most} delbanor, med varje ankarpunkt inom {far} pilspetsenheter från spetsen +@msg {k}: bad custom arrowhead path: {e} {k}: ogiltig bana för anpassad pilspets: {e} +@msg {k}: bad custom arrowhead: {e} {k}: ogiltig anpassad pilspets: {e} +@msg {k}: custom must be a name {k}: custom måste vara ett namn +@msg {name} must be a number {name} måste vara ett tal +@msg {path}: copy takes a DCS file only when its plates are inside it; relink to it where its plate files are {path}: copy tar en DCS-fil bara när dess plåtar ligger i filen; länka om till den där dess plåtfiler finns +@msg {path}: larger than {_1} MB {path}: större än {_1} MB +@msg {saving} failed: {e} {saving} misslyckades: {e} +@msg {shown} is not an XPath 1.0 function {shown} är inte en XPath 1.0-funktion +@msg {v} names no layer or sublayer {v} anger inget lager eller underlager +@msg {what} is not a function {what} är inte en funktion +@msg {what} would print more than {MAX_COPIES_PER_SHEET} copies on a sheet: scale it up {what} skulle skriva ut fler än {MAX_COPIES_PER_SHEET} kopior på ett ark: öka skalan +@msg {what} {i} out of range {what} {i} utanför intervallet +@msg `background` must be "", "matte" or #rrggbb `background` måste vara "", "matte" eller #rrggbb +@msg `count` must be a whole number from 1 to 100 `count` måste vara ett heltal från 1 till 100 +@msg `diameter` must be from 0.1 to 2500 pt `diameter` måste vara från 0,1 till 2500 pt +@msg `to` must be [x, y] `to` måste vara [x, y] +@msg `{k}` must be a number `{k}` måste vara ett tal +@msg `{k}` must be a string `{k}` måste vara en sträng +@msg `{k}` must be a whole number `{k}` måste vara ett heltal +@msg `{name}` is a built-in profile and stays `{name}` är en inbyggd profil och finns kvar +@msg a preset named `{n}` exists det finns redan en förinställning med namnet `{n}` +@msg an image of {width} × {height} pixels is too large to draw en bild på {width} × {height} pixlar är för stor för att ritas +@msg at must be [x, y] at måste vara [x, y] +@msg axis must be "vertical", "horizontal" or an angle in degrees, not `{given}` axis måste vara "vertical", "horizontal" eller en vinkel i grader, inte `{given}` +@msg bad color {c} ogiltig färg {c} +@msg bad colour {v} ogiltig färg {v} +@msg missing `effect` id id för `effect` saknas +@msg missing `find` `find` saknas +@msg missing `id` `id` saknas +@msg missing `to` `to` saknas +@msg missing ids ids saknas +@msg missing indexes indexes saknas +@msg missing name name saknas +@msg names is empty names är tom +@msg no artboard {artboard} (0-based; the document has {_1}) ingen rityta {artboard} (räknat från 0; dokumentet har {_1}) +@msg no brush named `{n}` ingen pensel med namnet `{n}` +@msg no colour group `{group}` ingen färggrupp `{group}` +@msg no export preset `{name}` (see document.exportPresets.list) ingen exportförinställning `{name}` (se document.exportPresets.list) +@msg no formats to export inga format att exportera +@msg no perspective grid preset named `{n}` ingen förinställning för perspektivrutnät med namnet `{n}` +@msg no print preset named `{n}` ingen utskriftsförinställning med namnet `{n}` +@msg no saved PDF preset named `{name}` ingen sparad PDF-förinställning med namnet `{name}` +@msg no saved preset called `{name}` ingen sparad förinställning med namnet `{name}` +@msg no saved presets to export (name built-in ones in `names`) inga sparade förinställningar att exportera (ange inbyggda i `names`) +@msg no saved print preset named `{name}` ingen sparad utskriftsförinställning med namnet `{name}` +@msg no swatch `{n}` ingen färgruta `{n}` +@msg no swatch library `{key}` (see swatch.library.list) inget färgrutebibliotek `{key}` (se swatch.library.list) +@msg no symbol named `{name}` ingen symbol med namnet `{name}` +@msg node {_1} is not type nod {_1} är inte text +@msg nothing to export: the document has no visible art inget att exportera: dokumentet har ingen synlig grafik +@msg on must be true or false on måste vara true eller false +@msg params must be an object params måste vara ett objekt +@msg resolution must be between 1 and 2400 ppi upplösningen måste vara mellan 1 och 2400 ppi +@msg select one Intertwine group markera en sammanflätningsgrupp +@msg the header `{cell}` for `{name}` would read back as the variable `{other}`: rename one of them rubriken `{cell}` för `{name}` skulle läsas som variabeln `{other}`: byt namn på en av dem +@msg the image's pixels can't be read: {e} bildens pixlar kan inte läsas: {e} +@msg the selection has no bounds markeringen har inga gränser +@msg unknown effect `{e}` okänd effekt `{e}` +@msg unknown highlight `{v}` okänd framhävning `{v}` +@msg unknown overprints `{v}` (preserve, simulate or discard) okänt övertrycksval `{v}` (preserve, simulate eller discard) +@msg unknown preference `{k}` okänd inställning `{k}` +@msg {key} must be [x,y] {key} måste vara [x,y] +@msg {key} must be one of {_1} {key} måste vara något av {_1} +@msg {k} must be a number from {min} to {max} {k} måste vara ett tal från {min} till {max} +@msg {k} must be a string {k} måste vara en sträng +@msg {k} must be true or false {k} måste vara true eller false # Importer plug-ins (File › Open With, document.open) Open With Öppna med @@ -10129,6 +10716,50 @@ digits Hindi Hindi @msg A joint does not close by {gap} pt. En fog sluter inte med {gap} pt. @msg Two panels pass through each other. Två paneler går igenom varandra. @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} pixlar är för stort för PSD (högst {MAX_SIDE} pixlar per sida): sänk upplösningen + Fine Stipple Fin prickning + Dense Stipple Tät prickning + Soft Stipple Mjuk prickning + Bold Stipple Kraftig prickning + Paper Cutouts Pappersutklipp + Coral Layers Korallager + Mint Layers Myntalager + Midnight Layers Midnattslager + Sunflower Sheet Solrosark + Rose Layers Rosenlager + Monochrome Stack Monokrom stapel +# Tool cards (General › Show Tool Cards): one sentence on what each tool does. + Shows a card with what a toolbar tool does and what its keys do instead of its tip; it needs Show Tool Tips. Visar ett kort med vad ett verktyg i verktygsfältet och dess tangenter gör i stället för dess tips; kräver Visa verktygstips. + Selects whole objects and groups to move, resize or rotate them. Markerar hela objekt och grupper för att flytta, skala eller rotera dem. + Selects anchor points and path segments to reshape a path. Markerar ankarpunkter och bansegment för att ändra formen på en bana. + Draws paths point by point, with straight segments and smooth curves. Ritar banor punkt för punkt, med raka segment och mjuka kurvor. + Draws smooth curves through the points you click. Ritar mjuka kurvor genom punkterna du klickar på. + Adds text at a point, or in a frame you drag. Lägger till text vid en punkt eller i en ram som du drar upp. + Draws rectangles and squares. Ritar rektanglar och kvadrater. + Draws rectangles with rounded corners. Ritar rektanglar med rundade hörn. + Draws ellipses and circles. Ritar ellipser och cirklar. + Draws polygons with sides of equal length. Ritar polygoner med lika långa sidor. + Draws stars. Ritar stjärnor. + Turns objects around a reference point. Roterar objekt runt en referenspunkt. + Flips objects across an axis through a reference point. Spegelvänder objekt över en axel genom en referenspunkt. + Resizes objects from a reference point. Skalar objekt från en referenspunkt. + Slants objects from a reference point. Lutar objekt från en referenspunkt. + Moves the view of the document. Flyttar vyn av dokumentet. + Magnifies or reduces the view. Förstorar eller förminskar vyn. + Copies the color and other attributes of one object to the selection. Kopierar färgen och andra attribut från ett objekt till markeringen. + Sets the direction and length of a gradient. Anger riktning och längd för en gradient. + Creates, selects and resizes artboards. Skapar, markerar och skalar ritytor. + Changes the width of a stroke along its length. Ändrar bredden på en kontur längs dess längd. + Bends art by dragging pins placed on it. Böjer teckningar genom att dra i nålar som placerats på dem. + Pushes the outlines of paths in the direction you drag. Skjuter banornas konturer i den riktning du drar. + Twists the outlines of paths into swirls. Vrider banornas konturer till virvlar. + Pulls the outlines of paths in toward the brush. Drar banornas konturer in mot penseln. + Pushes the outlines of paths out from the brush. Skjuter banornas konturer ut från penseln. + Adds curved details along the outlines of paths. Lägger till böjda detaljer längs banornas konturer. + Adds spiky details along the outlines of paths. Lägger till spetsiga detaljer längs banornas konturer. + Adds wrinkles along the outlines of paths. Lägger till rynkor längs banornas konturer. + Moves, copies and resizes objects on the perspective grid. Flyttar, kopierar och skalar objekt på perspektivrutnätet. + Makes a series of steps between two or more objects. Skapar en serie steg mellan två eller flera objekt. + Places dimension lines that show measured lengths. Placerar måttlinjer som visar uppmätta längder. Tap Kort tryck Clear Hold Rensa håll Hold Shortcuts Hållkortkommandon @@ -10145,3 +10776,7 @@ digits Hindi Hindi Pulse Stroke Pulserande drag Round Flow Runt flöde Chisel Flow Snedflöde + +# #5804 native-picked raster editor (draft translations; native review welcome). + Edit Original with: Redigera original med: +file-filter Applications Program diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 19e8f367c6..5e41b647b2 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -570,6 +570,88 @@ fn objects_on_path_detach_strings_are_in_complete_catalogs() { } } +/// The PSD Import Options dialog's labels, and the warnings and errors of opening and placing a +/// PSD or PSB file with its layers and slices: each complete catalog translates every one, keeping +/// its numbers, and translates a reason given inside one. +#[test] +fn psd_import_strings_are_in_complete_catalogs() { + use crate::io::opened_with_notes; + use vectorcraft_engine::cmd::fileio::{PSD_LAYER_WARNINGS, PSD_MERGED_WARNING}; + let labels = + ["Place PSD", "PSD Import Options", "Convert Layers to Objects", "Import Hidden Layers", "Flatten Layers to a Single Image", "Import Slices"]; + for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) { + for label in labels { + assert!(lang.catalog().plain(label).is_some(), "{} is missing {label}", lang.code); + } + } + let (nested, damaged) = ("the slices' descriptor nests too deep", "the PSD file's layer records are damaged"); + let unread_slices = "the slices can't be read (the slices' descriptor nests too deep) and were left out"; + let unread_layers = "the layers can't be read (the PSD file's layer records are damaged): the file was placed as its merged image"; + let merged = PSD_MERGED_WARNING.replace("{modes}", "Hue, Luminosity"); + let (one, many) = PSD_LAYER_WARNINGS[1]; + let (one, many) = (one.to_string(), many.replace("{n}", "3")); + let mut shown: Vec = PSD_LAYER_WARNINGS.iter().flat_map(|(one, many)| [one.to_string(), many.replace("{n}", "3")]).collect(); + shown.push(merged.clone()); + shown.extend( + [ + "the file is no longer loaded", + unread_layers, + "hiddenLayers applies to a PSD file placed with layers: true", + "importSlices: a linked PSD file is placed as its flat image; give link: false to embed it with its slices", + "layers: a linked PSD file is placed as its flat image; leave link out or give link: false", + unread_slices, + "1 slice lies outside the canvas or has no size and was left out", + "3 slices lie outside the canvas or have no size and were left out", + "1 slice would lie outside the canvas and was left out", + "3 slices would lie outside the canvas and were left out", + "the slices' descriptor holds too many values", + "the slices' descriptor has a version other than 16", + "the slices are stored in version 9, which isn't read", + "the file has 10001 slices, more than the 10000 read", + "the slices' descriptor has no list of slices", + "the slices' descriptor lists something other than a slice", + "a slice in the slices' descriptor has no bounds", + "a slice's bounds in the slices' descriptor aren't numbers", + "a text in the slices has more than the 65536 characters read", + nested, + "the slices' descriptor has a reference of an unknown kind (abcd)", + "the slices' descriptor has a value of an unknown type (abcd)", + ] + .map(String::from), + ); + let numbers = |s: &str| { + let mut all = s.split(|c: char| !c.is_ascii_digit()).filter(|n| !n.is_empty()).map(String::from).collect::>(); + all.sort(); + all + }; + let (note, notes) = ("Opened with {n} note: {first}", "Opened with {n} notes: {first}"); + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + for s in &shown { + let tr = message(lang, s); + assert_ne!(&tr, s, "{code}"); + assert_eq!(numbers(&tr), numbers(s), "{code}: {s} -> {tr}"); + } + for (s, inner) in [(unread_slices, nested), (unread_layers, damaged)] { + let (tr, inner_tr) = (message(lang, s), message(lang, inner)); + assert_ne!(inner_tr, inner, "{code}: {inner}"); + assert!(tr.contains(&inner_tr) && !tr.contains(inner), "{code}: {s} -> {tr}"); + } + assert!(message(lang, &merged).contains("Hue, Luminosity"), "{code}"); + let opened = opened_with_notes(1, &one); + let (forms, _) = lang.catalog().message_forms(&opened).expect("the Open heading has a row"); + let heading = &forms[(lang.0.plural)(1).min(forms.len() - 1)]; + assert!(heading != note && heading != notes, "{code}"); + assert_eq!(message(lang, &opened), fmt(heading, &[("n", "1"), ("first", &message(lang, &one))]), "{code}"); + } + assert_eq!(message(de(), &many), "3 Einstellungsebenen wurden nicht angewendet"); + assert_eq!(message(de(), &opened_with_notes(1, &one)), "Mit 1 Hinweis geöffnet: 1 Einstellungsebene wurde nicht angewendet"); + assert_eq!( + message(de(), unread_slices), + "die Slices können nicht gelesen werden (der Deskriptor der Slices ist zu tief verschachtelt) und wurden weggelassen" + ); +} + /// Make Compound Shape's warning for a member that adds no area, which the status bar shows and /// the message scan doesn't read, is translated in each language of [`COMPLETE_MESSAGES`]. #[test] @@ -581,6 +663,21 @@ fn compound_shape_no_area_warning_is_translated() { } } +/// The Save PDF dialog's Save Summary… button and `ui.pdfSummary.save`'s error when no such +/// dialog is open. +#[test] +fn pdf_save_summary_strings_are_in_complete_catalogs() { + for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) { + assert!(lang.catalog().plain("Save Summary…").is_some(), "{} is missing Save Summary…", lang.code); + } + let closed = "the Save PDF dialog is not open"; + assert!(message_literals().contains(closed)); + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + assert_ne!(message(lang, closed), closed, "{code}"); + } +} + /// The status messages the Shape Builder tool gives when a gesture builds nothing come from the /// tools crate, which [`message_literals`] does not scan, so every complete catalog is checked for /// them here. @@ -668,7 +765,7 @@ fn built_in_library_style_names_are_in_complete_catalogs() { .flat_map(|(_, lib)| lib.styles.iter().map(|s| s.name.clone()).collect::>()) .collect(), ); - assert_eq!(names.len(), 86, "{names:?}"); + assert_eq!(names.len(), 92, "{names:?}"); let bad = lacking(&names, |c, n| c.plain(n).is_some()); assert!(bad.is_empty(), "{}", bad.join("\n")); } @@ -726,6 +823,21 @@ fn numbered_labels_translate_the_name_before_the_number() { assert_eq!(numbered_label(Lang::EN, "Grays 12"), "Grays 12"); } +/// General › Show Tool Cards and every tool's description on its card. +#[test] +fn tool_card_strings_are_in_complete_catalogs() { + let mut bad = vec![]; + let descriptions = vectorcraft_tools::catalog::all_tools().filter_map(|t| vectorcraft_tools::catalog::tool_description(t.id)); + let strings: Vec<&str> = std::iter::once("Show Tool Cards").chain(descriptions).collect(); + for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) { + let missing: Vec<&&str> = strings.iter().filter(|s| lang.catalog().plain(s).is_none()).collect(); + if !missing.is_empty() { + bad.push(format!("{} is missing {missing:?}", lang.code)); + } + } + assert!(bad.is_empty(), "{}", bad.join("\n")); +} + /// Window › Arrange's Tile layouts and the application bar's Arrange Documents button. #[test] fn tile_layout_labels_are_in_complete_catalogs() { @@ -747,6 +859,15 @@ fn marquee_selection_labels_are_in_complete_catalogs() { } } +/// The note the Tangent Circle tool shows on the canvas over a segment that gives no circle. +#[test] +fn tangent_circle_tool_note_is_in_complete_catalogs() { + let label = vectorcraft_tools::addons::tangent_circle::NO_CIRCLE; + for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) { + assert!(lang.catalog().plain(label).is_some(), "{} is missing {label}", lang.code); + } +} + /// The Artboard tool's add buttons take their tooltips from the tools crate, which the `tl!` scan /// does not read, so each complete catalog is checked for them here. #[test] @@ -872,11 +993,13 @@ fn document_info_labels_are_in_complete_catalogs() { /// The values Document Info makes and shows in the interface language: the font states and /// embedding permissions, the templates of the font, image, raster effects and Repeat object -/// values, the names of gradients named by their kind, the counted instances, rows and columns, and -/// the transparency settings' values. +/// values, the names of gradients named by their kind, the counted uses, instances, rows and +/// columns, and the transparency settings' values. #[test] fn document_info_values_are_in_complete_catalogs() { - const VALUES: [&str; 20] = [ + const VALUES: [&str; 22] = [ + "unknown type", + "{type}; {uses}", "built in", "embedding not allowed", "embedding for editing", @@ -898,7 +1021,8 @@ fn document_info_values_are_in_complete_catalogs() { "Diamond gradient", "Freeform gradient", ]; - const COUNTED: [(&str, &str); 3] = [("{n} instance", "{n} instances"), ("{n} row", "{n} rows"), ("{n} column", "{n} columns")]; + const COUNTED: [(&str, &str); 4] = + [("{n} use", "{n} uses"), ("{n} instance", "{n} instances"), ("{n} row", "{n} rows"), ("{n} column", "{n} columns")]; // The transparency settings' values: the grid's sizes and color presets, on and off, and the // built-in flattener presets. let transparency = ["Small", "Medium", "Large", "On", "Off", "High Resolution", "Medium Resolution", "Low Resolution"] @@ -963,6 +1087,16 @@ fn painted_and_sketched_style_names_are_in_every_catalog() { } } +#[test] +fn paper_cutout_style_names_are_in_every_catalog() { + let lib = vectorcraft_doc::style_libs::builtin_style_library("paper-cutouts").expect("built in"); + for lang in LANGUAGES.iter().filter(|lang| !lang.source.is_empty()) { + for label in std::iter::once(lib.name.as_str()).chain(lib.styles.iter().map(|g| g.name.as_str())) { + assert!(lang.catalog().plain(label).is_some(), "{} is missing {label}", lang.code); + } + } +} + /// The names the EPS options' menus show (preview, overprints, flattener preset and PostScript /// level), and Save As's Preview label. #[test] @@ -984,6 +1118,16 @@ fn eps_option_menu_names_are_in_complete_catalogs() { } } +/// HP-GL Options' Origin menu names (drawn translated by the dropdown, not through `tl!`). +#[test] +fn hpgl_origin_menu_names_are_in_complete_catalogs() { + for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) { + for label in crate::dialogs::hpgl_options::ORIGIN_NAMES { + assert!(lang.catalog().plain(label).is_some(), "{} is missing {label}", lang.code); + } + } +} + /// Each language counts with its own plural rule: the form a count picks (`one`, then `few`, then /// `other`/`many`). #[test] @@ -2187,6 +2331,7 @@ fn toggled_labels() -> Vec { "view.outline", "view.edges", "view.cornerWidget", + "view.shapeWidgets", "view.textThreads", "type.hiddenCharacters", "view.gradientAnnotator", @@ -3347,6 +3492,31 @@ fn a_repeated_placeholder_matches_the_same_text() { assert!(c.message("alert: the next answer is for prompt, not confirm").is_none()); } +/// Swedish shows the status and error messages of the script engine, the parameter checks, the +/// importers, the 3D effects and the cutting add-on in Swedish, with the values, names and command +/// ids they carry kept. +#[test] +fn swedish_translates_engine_import_and_parameter_messages() { + let sv = Lang::from_code("sv").expect("registered"); + for (english, swedish) in [ + ("`colors` must be a whole number from 2 to 256", "`colors` måste vara ett heltal från 2 till 256"), + ("JSON.parse: oops (at offset 12)", "JSON.parse: oops (vid position 12)"), + ("unknown dither `foo` (diffusion, pattern, noise or none)", "okänd dithering `foo` (diffusion, pattern, noise eller none)"), + ("not a DCS file", "inte en DCS-fil"), + ( + "object 7: with a depth of 0 the object has one face: map its graphics onto the front", + "objekt 7: med djupet 0 har objektet en enda yta: mappa dess grafik på framsidan", + ), + ("no custom arrowhead Fin (see stroke.arrowheads.list)", "ingen anpassad pilspets Fin (se stroke.arrowheads.list)"), + ("`warichuLines` must be a whole number from 1 to 6", "`warichuLines` måste vara ett heltal från 1 till 6"), + ("the rectangle or line reaches too many paths to check", "rektangeln eller linjen når för många banor för att kunna kontrolleras"), + ("the hem is too deep for the banner", "fållen är för djup för bannern"), + ("`diameter` must be from 0.1 to 2500 pt", "`diameter` måste vara från 0,1 till 2500 pt"), + ] { + assert_eq!(message(sv, english), swedish); + } +} + /// Of two templates that start with text, the one with the longer text before its first /// placeholder matches first, so a row that wraps a message takes it before a row with more text /// in all whose placeholder would take part of it; a quoted name may still hold a backtick. @@ -6499,7 +6669,7 @@ fn translated_messages_keep_the_field_names_and_values_their_english_lists() { /// the messages each one lacks. const COMPLETE_MESSAGES: &[&str] = &[ "cs", "de", "el", "es", "fr", "hi", "hu", "it", "ja", "ka", "ko", "pl", "pt-br", "ru", "sv", "uk", "vi", "zh-hans", "zh-hant", "fi", "tr", "ca", - "nl", "da", + "nl", "da", "id", ]; /// Crates whose error and status messages reach the status bar, the crates whose errors the diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index d708ba8484..300707f8fa 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -480,6 +480,9 @@ font-technology Variable Değişken Choose… Seç… Circle daire Circle Tool Daire Aracı + Curvature Circle Tool Eğrilik Çemberi Aracı + Cusp Sivri nokta + Straight segment Düz segment Circle too large Daire çok büyük Classic Defaults Klasik Varsayılanlar Clean Up… Temizleme… @@ -586,6 +589,9 @@ font-technology Variable Değişken Box Channel Kutu Kanalı Color box Renk kutusu Color Wheel Options Renk Tekerleği Seçenekleri + Show Harmony Uyumu Göster + Harmony Rule Uyum Kuralı + Harmony color Uyum rengi Color Type: Renk Türü: Color: Renk: Colorize Renklendir @@ -1009,10 +1015,25 @@ font-technology Variable Değişken Duplicate Symbol Yinelenen Sembol Duplicate {kind} Style Çoğaltılmış {kind} Stili Dutch Hollandaca + PSD Import Options PSD İçe Aktarma Seçenekleri + Place PSD PSD Yerleştir + Convert Layers to Objects Katmanları Nesnelere Dönüştür + Import Hidden Layers Gizli Katmanları İçe Aktar + Flatten Layers to a Single Image Katmanları Tek Görüntüde Düzleştir + Import Slices Dilimleri İçe Aktar DXF Import Options DXF İçe Aktarma Seçenekleri DXF Info DXF Bilgisi DXF Options DXF Seçenekleri DXF Options Dialog DXF Seçenekleri İletişim Kutusu + HP-GL Options HP-GL Seçenekleri + HP-GL Options Dialog HP-GL Seçenekleri İletişim Kutusu + Curve Tolerance: Eğri Toleransı: + Origin: Başlangıç Noktası: + Pens: Kalemler: + One Pen per Color Her Renk İçin Bir Kalem + Pen Table Kalem Tablosu + Draw the Nearest Path Next Sonra En Yakın Yolu Çiz + Draw Inner Paths First Önce İç Yolları Çiz e.g. 1-3, 5 örneğin 1-3, 5 Each page prints as one image, at the document's raster effects resolution. Her sayfa, belgenin tarama efektleri çözünürlüğünde tek bir görüntü olarak yazdırılır. Earth Tones Toprak Tonları @@ -1237,6 +1258,15 @@ font-technology Variable Değişken Shading Color Gölgeleme Rengi Black Overprint Siyah Üst Baskı Draw Hidden Faces Gizli Yüzleri Çiz + Map Art… Çizimi Eşle… + Map Art Çizimi Eşle + First Surface İlk Yüzey + Previous Surface Önceki Yüzey + Next Surface Sonraki Yüzey + Last Surface Son Yüzey + Scale to Fit Sığacak Şekilde Ölçekle + Shade Artwork Çizimi Gölgelendir + Invisible Geometry Görünmez Geometri Eyedropper Damlalık Sample Color from Screen Ekrandan Örnek Renk This system has no screen color sampler Bu sistemin ekran rengi örnekleyicisi yok @@ -1348,6 +1378,17 @@ font-technology Variable Değişken Largest: En büyük: Direction: Yön: Symbolism Tools Options Sembolizm Araçları Seçenekleri + Tool: Araç: + Symbol Set Density Sembol Seti Yoğunluğu + Symbol Sprayer Options Sembol Püskürtücü Seçenekleri + Scrunch: Sıkıştırma: + Spin: Döndürme: + Screen: Saydamlaştırma: + Stain: Renklendirme: + Symbol Sizer Options Sembol Boyutlandırıcı Seçenekleri + Proportional Resizing Orantılı Yeniden Boyutlandırma + Resizing Affects Density Yeniden Boyutlandırma Yoğunluğu Etkiler + Show Brush Size and Intensity Fırça Boyutunu ve Yoğunluğunu Göster Symbol Set Density: Sembol Seti Yoğunluğu: Flat Image Düz Resim Flat Logo Düz Logo @@ -1578,6 +1619,8 @@ font-technology Variable Değişken More Options Daha Fazla Seçenek Show Properties Panel Özellikler Panelini Göster Hide Corner Widget Köşe Widget'ını Gizle + Hide Shape Widgets Şekil Widget'larını Gizle + Show Shape Widgets Şekil Widget'larını Göster Hide Corner Widget for angles greater than Şu değerden daha büyük açılar için Köşe Widget'ını gizle: Hide Edges Kenarları Gizle Hide Gradient Annotator Degrade Açıklayıcıyı Gizle @@ -2039,6 +2082,15 @@ font-technology Variable Değişken YakumonoZenkaku YakumonoZenkaku Kinsoku Set Kinsoku Seti Kinsoku Shori Type Kinsoku Shori Türü + Kinsoku Shori Settings… Kinsoku Shori Ayarları… + Kinsoku Shori Settings Kinsoku Shori Ayarları + Kinsoku Sets Kinsoku Setleri + Kinsoku Set Base Kinsoku Seti Temeli + Based on: Temel: + Cannot Start Line Satır Başlatamaz + Cannot End Line Satır Bitiremez + Hanging Punctuation Asılı Noktalama + Inseparable Characters Ayrılmaz Karakterler Push In First Önce İçeri Push Out First Önce Dışarı Push Out Only Yalnızca Dışarı @@ -2147,6 +2199,7 @@ font-technology Variable Değişken Pressure Basınç Tilt Eğim Bearing Yön + Stylus Wheel Kalem tekerleği Shape: Şekil: Bristle Length: Kıl Uzunluğu: Bristle Density: Kıl Yoğunluğu: @@ -2415,6 +2468,8 @@ shape Open Açık Overprint and Transparency Flattener Options Üst Baskı ve Asetat Düzleştirici Seçenekleri Custom… Özel… Custom Transparency Flattener Options Özel Şeffaflık Düzleştirici Seçenekleri + The PDF preset keeps the flattener preset but not the Custom… settings. PDF ön ayarı düzleştirici ön ayarını korur, ancak Özel… ayarlarını korumaz. + PDF 1.3 files clip rasterized areas to their regions, and Overprint sets whether overprints are kept. PDF 1.3 dosyaları rasterleştirilmiş alanları kendi bölgelerine kırpar ve Üst baskı, üst baskıların korunup korunmayacağını belirler. EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS'de alfa şeffaflığı yoktur ve Üst baskılar, üst baskıların korunup korunmayacağını belirler. Overprint Black… Üst Baskı Siyah… Overprint Fill Üst Baskı Dolgusu @@ -2923,6 +2978,9 @@ digits Malayalam Malayalam Rotate View to Selection Görünümü Seçime Döndür Reset the rows to the artwork's colors Satırları resmin renklerine göre sıfırlayın Color Theme Picker Renk Teması Seçici + Undo Changes Değişiklikleri Geri Al + Redo Changes Değişiklikleri Yinele +@msg Recolor Artwork is not open Resmi Yeniden Renklendir açık değil Click or drag across the art to pick its colors; Shift adds more Renklerini almak için resme tıklayın veya üzerinde sürükleyin; Shift daha fazlasını ekler Prominent Colors Belirgin Renkler Save All Colors Tüm Renkleri Kaydet @@ -2977,6 +3035,7 @@ digits Malayalam Malayalam A live rectangle's properties show one Corner Radius field for all four corners; off, each corner has its own field. Canlı bir dikdörtgenin özellikleri dört köşenin tümü için tek bir Köşe Yarıçapı alanı gösterir; kapalıyken her köşenin kendi alanı olur. What edits in the Transform panel transform: the object, its pattern tiles or both; Default follows Transform Pattern Tiles. Dönüştür panelindeki düzenlemelerin neyi dönüştürdüğü: nesneyi, desen döşemelerini veya ikisini; Varsayılan, Desen Döşemelerini Dönüştür'ü izler. With one symbol instance selected, the Transform panel uses the symbol's registration point as its reference point. Bir sembol örneği seçiliyken Dönüştür paneli, sembolün kayıt noktasını referans noktası olarak kullanır. + Drawing a rectangle, ellipse, polygon, star or line opens the Transform panel if it is closed. Dikdörtgen, elips, çokgen, yıldız veya çizgi çizmek, kapalıysa Dönüştür panelini açar. Darkens the canvas outside the artboards while the Artboard tool is active. Çalışma Yüzeyi aracı etkinken çalışma yüzeylerinin dışındaki tuvali karartır. With Fade Region Outside Artboard on, the area outside the artboards stays dark while you drag with the Artboard tool. Çalışma Yüzeyi Dışındaki Bölgeyi Karart açıkken, Çalışma Yüzeyi aracıyla sürüklerken çalışma yüzeylerinin dışındaki alan karanlık kalır. How near, in pixels, the pointer must be to an object, anchor or handle for a click to select it. Bir tıklamanın nesneyi, bağlantı noktasını veya tutamacı seçmesi için işaretçinin ona piksel cinsinden ne kadar yakın olması gerektiği. @@ -3151,6 +3210,7 @@ digits Malayalam Malayalam Save Preset Ön Ayarı Kaydet Save Document Preset Belge Ön Ayarını Kaydet Save Preset… Ön Ayarı Kaydet… + Save Summary… Özeti Kaydet… Save Print Preset Yazdırma Ön Ayarını Kaydet Save Recovery Data Kurtarma Verilerini Kaydet Save Save for Web Preset Kaydet Web Ön Ayarı için Kaydet @@ -3484,6 +3544,7 @@ digits Malayalam Malayalam Show Modified Değiştirilenleri Göster Show Note Notu Göster Show Options Seçenekleri Göster + Show on Shape Creation Şekil Oluştururken Göster Show Recent Colors Son Renkleri Göster Toggle RGB Percent RGB Yüzde Gösterimini Değiştir Show Original Path Orijinal Yolu Göster @@ -3508,6 +3569,7 @@ digits Malayalam Malayalam Show Thumbnails Küçük Resimleri Göster Show Tile Edge Döşeme Kenarını Göster Show Tints/Shades Renk Tonlarını/Gölgeleri Göster + Show Tool Cards Araç Kartlarını Göster Show Tool Tips Araç İpuçlarını Göster Show Transparency Grid Şeffaflık Izgarasını Göster Show Video Rulers Video Cetvellerini Göster @@ -3591,6 +3653,8 @@ digits Malayalam Malayalam Outlines Ana hatlar Outlines with Source Image Kaynak Resimli Ana Hatlar Source Image Kaynak Resim + Split View Bölünmüş Görünüm + Divider Ayırıcı Press and hold to view the source image Kaynak resmi görmek için basılı tutun Image Trace View Görüntü İzleme Görünümü Snap Options Yapış Seçenekleri @@ -4026,6 +4090,8 @@ digits Malayalam Malayalam Unembed… Gömmeyi kaldır… Ungroup Grubu Çöz Ungroup Color Group Renk Grubunun Grubunu Çöz + Color Group Options Renk Grubu Seçenekleri + Color Group Options… Renk Grubu Seçenekleri… Unicode Unicode Unicode (UTF-16) Unicode (UTF-16) Unicode (UTF-8) Unicode (UTF-8) @@ -4786,6 +4852,7 @@ liquify-list-end {0}, {1} {0} ve {1} @msg a freeform gradient keeps at least one point serbest biçimli bir degrade en az bir noktayı korur @msg a gradient needs at least two stops bir degradenin en az iki durağa ihtiyacı vardır @msg a graphic style named `{to}` already exists `{to}` adlı bir grafik stili zaten mevcut +@msg a swatch or color group named `{name}` already exists `{name}` adlı bir renk örneği veya renk grubu zaten mevcut @msg a page is missing bir sayfa eksik @msg a page out of range aralık dışında bir sayfa @msg a page tree kid isn't a reference sayfa ağacı çocuğu bir referans değildir @@ -4931,6 +4998,11 @@ liquify-list-end {0}, {1} {0} ve {1} @msg no anchor points selected bağlantı noktası seçilmedi @msg `points` must be two or three [x, y] pairs of numbers `points` iki veya üç [x, y] sayı çifti olmalıdır @msg direct-select two or three anchor points, or give `points` iki veya üç bağlantı noktasını doğrudan seçin veya `points` verin +@msg the path is straight there, so no circle matches its curvature yol orada düz, bu yüzden hiçbir çember eğriliğiyle eşleşmiyor +@msg the path has a cusp there, so it has no single curvature yolun orada sivri bir noktası var, bu yüzden tek bir eğriliği yok +@msg the path has a corner there, so it has no single curvature yolun orada bir köşesi var, bu yüzden tek bir eğriliği yok +@msg a guide has no curvature circle bir kılavuzun eğrilik çemberi yoktur +@msg the circle that matches the path there would reach past the canvas yolla orada eşleşen çember tuvalin dışına taşardı @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 @@ -5198,6 +5270,7 @@ liquify-list-end {0}, {1} {0} ve {1} @msg the PDF is password-protected: give its password PDF şifre korumalıdır: şifresini verin @msg the PDF password is wrong PDF şifresi yanlış @msg the Save PDF dialog didn't open PDF'yi Kaydet iletişim kutusu açılmadı +@msg the Save PDF dialog is not open PDF'yi Kaydet iletişim kutusu açık değil @msg the WMF header is damaged WMF başlığı hasarlı @msg the art could not be sampled sanat örneği alınamadı @msg the art has no bounds sanatın sınırı yoktur @@ -5403,6 +5476,7 @@ liquify-list-end {0}, {1} {0} ve {1} @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 +@msg give only one of `index`, `indices` and `t` `index`, `indices` ve `t` değerlerinden yalnızca birini verin @msg column must be true or a number from 1 column true veya 1'den başlayan bir sayı olmalıdır @msg x and y must both be numbers x ve y'nin her ikisi de sayı olmalıdır @msg "{0}" is not a colour: write it as #rrggbb "{0}" bir renk değildir: #rrggbb olarak yazın @@ -5565,6 +5639,49 @@ liquify-list-end {0}, {1} {0} ve {1} @msg the PSD file's layer groups are nested too deeply PSD dosyasının katman grupları çok derin iç içe geçmiş @msg a layer of the PSD file is too large to read PSD dosyasının bir katmanı okunamayacak kadar büyük @msg the PSD file's layers take more memory to read than allowed PSD dosyasının katmanlarını okumak izin verilenden fazla bellek gerektiriyor +@msg the file is no longer loaded dosya artık yüklü değil +@msg the layers can't be read ({e}): the file was placed as its merged image katmanlar okunamıyor ({e}): dosya birleştirilmiş görüntüsü olarak yerleştirildi +@msg 1 type layer came in as pixels: the text isn't editable 1 metin katmanı piksel olarak geldi: metin düzenlenemez +@msg {n} type layers came in as pixels: the text isn't editable {n} metin katmanı piksel olarak geldi: metin düzenlenemez +@msg 1 adjustment layer was not applied 1 ayarlama katmanı uygulanmadı +@msg {n} adjustment layers were not applied {n} ayarlama katmanı uygulanmadı +@msg 1 fill layer was not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels) 1 dolgu katmanı çizilmedi (degrade veya desen dolgusu, okunamayan bir renk ya da piksel saklamayan bir şekil) +@msg {n} fill layers were not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels) {n} dolgu katmanı çizilmedi (degrade veya desen dolgusu, okunamayan bir renk ya da piksel saklamayan bir şekil) +@msg the layer effects of 1 layer weren't drawn 1 katmanın katman efektleri çizilmedi +@msg the layer effects of {n} layers weren't drawn {n} katmanın katman efektleri çizilmedi +@msg the vector masks of 1 layer weren't applied 1 katmanın vektör maskeleri uygulanmadı +@msg the vector masks of {n} layers weren't applied {n} katmanın vektör maskeleri uygulanmadı +@msg the knockout of 1 layer wasn't applied 1 katmanın boşaltması uygulanmadı +@msg the knockout of {n} layers wasn't applied {n} katmanın boşaltması uygulanmadı +@msg 1 layer was left out (hidden layers and the layers clipped to them) 1 katman dışarıda bırakıldı (gizli katmanlar ve onlara kırpılmış katmanlar) +@msg {n} layers were left out (hidden layers and the layers clipped to them) {n} katman dışarıda bırakıldı (gizli katmanlar ve onlara kırpılmış katmanlar) +@msg 1 layer clipped to a fill layer that wasn't drawn was left out çizilmeyen bir dolgu katmanına kırpılmış 1 katman dışarıda bırakıldı +@msg {n} layers clipped to fill layers that weren't drawn were left out çizilmeyen dolgu katmanlarına kırpılmış {n} katman dışarıda bırakıldı +@msg layers in blend modes VectorCraft doesn't have ({modes}) were merged with the layers below them VectorCraft’ta olmayan karışım modlarındaki katmanlar ({modes}) altlarındaki katmanlarla birleştirildi +@msg 1 layer in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed VectorCraft’ta olmayan bir karışım modundaki 1 katman Normal olarak geldi: birleştirme izin verilenden fazla bellek gerektiriyor +@msg {n} layers in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed VectorCraft’ta olmayan karışım modlarındaki {n} katman Normal olarak geldi: birleştirme izin verilenden fazla bellek gerektiriyor +@msg 1 layer clipped to the layer below came in unclipped: the merge needs more memory than allowed alttaki katmana kırpılmış 1 katman kırpılmadan geldi: birleştirme izin verilenden fazla bellek gerektiriyor +@msg {n} layers clipped to the layer below came in unclipped: the merge needs more memory than allowed alttaki katmana kırpılmış {n} katman kırpılmadan geldi: birleştirme izin verilenden fazla bellek gerektiriyor +@msg hiddenLayers applies to a PSD file placed with layers: true hiddenLayers, layers: true ile yerleştirilen bir PSD dosyası için geçerlidir +@msg importSlices: a linked PSD file is placed as its flat image; give link: false to embed it with its slices importSlices: bağlı bir PSD dosyası düz görüntüsü olarak yerleştirilir; dilimleriyle birlikte gömmek için link: false verin +@msg layers: a linked PSD file is placed as its flat image; leave link out or give link: false layers: bağlı bir PSD dosyası düz görüntüsü olarak yerleştirilir; link’i belirtmeyin ya da link: false verin +@msg the slices can't be read ({e}) and were left out dilimler okunamıyor ({e}) ve dışarıda bırakıldı +@msg 1 slice lies outside the canvas or has no size and was left out 1 dilim tuvalin dışında kalıyor ya da boyutu yok ve dışarıda bırakıldı +@msg {n} slices lie outside the canvas or have no size and were left out {n} dilim tuvalin dışında kalıyor ya da boyutu yok ve dışarıda bırakıldı +@msg 1 slice would lie outside the canvas and was left out 1 dilim tuvalin dışında kalacaktı ve dışarıda bırakıldı +@msg {n} slices would lie outside the canvas and were left out {n} dilim tuvalin dışında kalacaktı ve dışarıda bırakıldı +@msg the slices' descriptor holds too many values dilimlerin tanımlayıcısı çok fazla değer içeriyor +@msg the slices' descriptor has a version other than 16 dilimlerin tanımlayıcısının sürümü 16 değil +@msg the slices are stored in version {v}, which isn't read dilimler okunmayan {v} sürümünde saklanmış +@msg the file has {count} slices, more than the {MAX_SLICES} read dosyada {count} dilim var, okunan {MAX_SLICES} dilimden fazla +@msg the slices' descriptor has no list of slices dilimlerin tanımlayıcısında dilim listesi yok +@msg the slices' descriptor lists something other than a slice dilimlerin tanımlayıcısı dilim dışında bir şey listeliyor +@msg a slice in the slices' descriptor has no bounds dilimlerin tanımlayıcısındaki bir dilimin sınırları yok +@msg a slice's bounds in the slices' descriptor aren't numbers dilimlerin tanımlayıcısındaki bir dilimin sınırları sayı değil +@msg a text in the slices has more than the {MAX_TEXT} characters read dilimlerdeki bir metin okunan {MAX_TEXT} karakterden uzun +@msg the slices' descriptor nests too deep dilimlerin tanımlayıcısı çok derin iç içe geçmiş +@msg the slices' descriptor has a reference of an unknown kind ({_1}) dilimlerin tanımlayıcısında bilinmeyen türde bir başvuru var ({_1}) +@msg the slices' descriptor has a value of an unknown type ({_1}) dilimlerin tanımlayıcısında bilinmeyen tipte bir değer var ({_1}) @msg the layers can't be read ({e}): the file opened as its merged image katmanlar okunamıyor ({e}): dosya birleştirilmiş görüntüsü olarak açıldı @msg {depth}-bit PSD files in this colour mode can't be read Bu renk modunda {depth}-bit PSD dosyaları okunamaz @msg the PSD file is cut short PSD dosyası kısa kesildi @@ -5629,6 +5746,25 @@ liquify-list-end {0}, {1} {0} ve {1} Preserve Embedded Profiles Gömülü Profilleri Koru Convert to Working Space Çalışma Alanına Dönüştür Preserve Numbers Sayıları Koru + Profile Mismatches: Profil Uyuşmazlıkları: + Ask When Opening Açarken Sor + Ask When Pasting Yapıştırırken Sor + Missing Profiles: Eksik Profiller: + Embedded Profile Mismatch Gömülü Profil Uyuşmazlığı + Missing Profile Eksik Profil + Paste Profile Mismatch Yapıştırma Profili Uyuşmazlığı + “{name}” is not tagged with a {model} profile. “{name}” bir {model} profiline sahip değil. + “{name}” is tagged with the {model} profile “{profile}”, which is not the {model} working space “{working}”. “{name}”, {model} çalışma alanı “{working}” olmayan “{profile}” {model} profiline sahip. + Use the embedded profile Gömülü profili kullan + Convert the colors to the working space Renkleri çalışma alanına dönüştür + Discard the embedded profile Gömülü profili at + Leave as is Olduğu gibi bırak + Assign the working space Çalışma alanını ata + Assign profile: Profil ata: + Preserve the color numbers Renk değerlerini koru + Convert to keep the colors' appearance Renklerin görünümünü korumak için dönüştür +@msg `{path}` goes with `{key}`: "assign" only `{path}` yalnızca `{key}`: "assign" ile kullanılır + The pasted colors come from a document whose {model} profile is “{from}”; this document's is “{to}”. Yapıştırılan renkler {model} profili “{from}” olan bir belgeden geliyor; bu belgeninki “{to}”. Texture Doku Craquelure… Küçük çatlak… Grain… Tahıl… @@ -6863,6 +6999,9 @@ theme Appearance Görünüm embedding for preview and print önizleme ve yazdırma için gömme embedding allowed gömmeye izin veriliyor {file}; {embedding} {file}; {embedding} + unknown type bilinmeyen tür + {type}; {uses} {type}; {uses} +@plural {n} use|{n} uses {n} kullanım substituted: shown in {family} {style} ({detail}) yerine konan: {family} {style} ile gösteriliyor ({detail}) missing: shown in {family} {style} eksik: {family} {style} ile gösteriliyor missing eksik @@ -10018,6 +10157,8 @@ breakText Glyphs Glifler # Path Precision Tools add-on: Tangent Circle. Tangent Circle… Teğet Daire… Tangent Circle Teğet Daire + Tangent Circle Tool Teğet Daire Aracı + No tangent circle here Burada teğet daire yok Circle: Daire: @msg `ids` names an object twice `ids` bir nesneyi iki kez belirtiyor @msg select two or three paths or compound paths iki veya üç yol ya da bileşik yol seçin @@ -10033,6 +10174,16 @@ breakText Glyphs Glifler @msg `circle` is past the last circle found ({found}) `circle` bulunan son dairenin ötesinde ({found}) @msg object {value} is not a path or compound path {value} nesnesi bir yol veya bileşik yol değil @msg these shapes are too small to measure bu şekiller ölçülemeyecek kadar küçük +# Path Precision Tools add-on: Add Bounding Rectangle and Add Bounding Circle. + Add Bounding Rectangle Çevreleyen Dikdörtgen Ekle + Add Bounding Circle Çevreleyen Daire Ekle + Add Bounding Rectangle… Çevreleyen Dikdörtgen Ekle… + Add Bounding Circle… Çevreleyen Daire Ekle… + One per Object Nesne başına bir +@msg nothing to enclose çevrelenecek hiçbir şey yok +@msg `offset` must be 0 or more `offset` 0 veya daha büyük olmalıdır +@msg the shape would have no size şeklin boyutu olmayacaktır +@msg the shape would reach past the edge of the canvas şekil tuvalin kenarını aşacaktır # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Belge Araçları Save a Timestamped Copy Zaman Damgalı Bir Kopya Kaydet @@ -10366,6 +10517,39 @@ breakText Glyphs Glifler No objects are selected. Hiçbir nesne seçili değil. Open a document to mark its fold lines. Katlama çizgilerini işaretlemek için bir belgeyi açın. Remove Fold Line Role Çizgi Türünü Kaldır +# Tool cards (General › Show Tool Cards): one sentence on what each tool does. + Shows a card with what a toolbar tool does and what its keys do instead of its tip; it needs Show Tool Tips. Araç çubuğundaki bir aracın ve tuşlarının ne yaptığını ipucu yerine bir kartta gösterir; Araç İpuçlarını Göster gerekir. + Selects whole objects and groups to move, resize or rotate them. Taşımak, yeniden boyutlandırmak veya döndürmek için nesnelerin ve grupların tamamını seçer. + Selects anchor points and path segments to reshape a path. Bir yolu yeniden şekillendirmek için bağlantı noktalarını ve yol parçalarını seçer. + Draws paths point by point, with straight segments and smooth curves. Düz parçalar ve yumuşak eğrilerle noktadan noktaya yollar çizer. + Draws smooth curves through the points you click. Tıkladığınız noktalardan geçen yumuşak eğriler çizer. + Adds text at a point, or in a frame you drag. Bir noktaya veya sürükleyerek çizdiğiniz bir çerçeveye metin ekler. + Draws rectangles and squares. Dikdörtgenler ve kareler çizer. + Draws rectangles with rounded corners. Köşeleri yuvarlatılmış dikdörtgenler çizer. + Draws ellipses and circles. Elipsler ve daireler çizer. + Draws polygons with sides of equal length. Kenarları eşit uzunlukta çokgenler çizer. + Draws stars. Yıldızlar çizer. + Turns objects around a reference point. Nesneleri bir referans noktası etrafında döndürür. + Flips objects across an axis through a reference point. Nesneleri bir referans noktasından geçen bir eksene göre yansıtır. + Resizes objects from a reference point. Nesneleri bir referans noktasından yeniden boyutlandırır. + Slants objects from a reference point. Nesneleri bir referans noktasından eğer. + Moves the view of the document. Belgenin görünümünü kaydırır. + Magnifies or reduces the view. Görünümü büyütür veya küçültür. + Copies the color and other attributes of one object to the selection. Bir nesnenin rengini ve diğer niteliklerini seçime kopyalar. + Sets the direction and length of a gradient. Bir degradenin yönünü ve uzunluğunu ayarlar. + Creates, selects and resizes artboards. Çalışma yüzeyleri oluşturur, seçer ve yeniden boyutlandırır. + Changes the width of a stroke along its length. Bir konturun genişliğini uzunluğu boyunca değiştirir. + Bends art by dragging pins placed on it. Üzerine yerleştirilen raptiyeleri sürükleyerek resmi büker. + Pushes the outlines of paths in the direction you drag. Yolların dış hatlarını sürüklediğiniz yöne iter. + Twists the outlines of paths into swirls. Yolların dış hatlarını girdaplar halinde büker. + Pulls the outlines of paths in toward the brush. Yolların dış hatlarını fırçaya doğru çeker. + Pushes the outlines of paths out from the brush. Yolların dış hatlarını fırçadan dışarı doğru iter. + Adds curved details along the outlines of paths. Yolların dış hatları boyunca kavisli ayrıntılar ekler. + Adds spiky details along the outlines of paths. Yolların dış hatları boyunca sivri ayrıntılar ekler. + Adds wrinkles along the outlines of paths. Yolların dış hatları boyunca kırışıklıklar ekler. + Moves, copies and resizes objects on the perspective grid. Perspektif ızgarasındaki nesneleri taşır, kopyalar ve yeniden boyutlandırır. + Makes a series of steps between two or more objects. İki veya daha fazla nesne arasında bir dizi adım oluşturur. + Places dimension lines that show measured lengths. Ölçülen uzunlukları gösteren ölçü çizgileri yerleştirir. Tap Kısa Basma Clear Hold Basılı Tutmayı Temizle Hold Shortcuts Basılı Tutma Kısayolları @@ -10396,7 +10580,18 @@ breakText Glyphs Glifler @msg A panel is not joined to the rest by a crease. Bir panel geri kalanlara hiçbir pilyaj çizgisiyle bağlı değil. @msg A fold line is on a non-printing layer. Bir katlama çizgisi yazdırılmayan bir katmanda. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneller: {panels}, menteşeler: {hinges}, hatalar: {errors}, uyarılar: {warnings} + Paper Cutouts Kağıt Kesikleri + Coral Layers Mercan Katmanları + Mint Layers Nane Katmanları + Midnight Layers Gece Yarısı Katmanları + Sunflower Sheet Ayçiçeği Yaprağı + Rose Layers Gül Katmanları + Monochrome Stack Tek Renkli Yığın Dashed Arrow Kesikli Ok + Fine Stipple İnce noktalı gölgelendirme + Dense Stipple Yoğun noktalı gölgelendirme + Soft Stipple Yumuşak noktalı gölgelendirme + Bold Stipple Kalın noktalı gölgelendirme Pressure Sensitive Basınca Duyarlı Flex Ribbon Esnek Şerit Pulse Stroke Atımlı Çizgi @@ -10412,3 +10607,7 @@ breakText Glyphs Glifler @msg Other blanks not shown: {count} Gösterilmeyen diğer açınımlar: {count} @msg A joint does not close by {gap} pt. Bir birleşim {gap} pt kadar kapanmıyor. @msg Two panels pass through each other. İki panel birbirinin içinden geçiyor. + +# #5804 native-picked raster editor (draft translations; native review welcome). + Edit Original with: Orijinali şununla düzenle: +file-filter Applications Uygulamalar diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 057b16ad8f..198d9af639 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -494,6 +494,9 @@ font-technology Variable Варіативні Choose… Вибрати… Circle Коло Circle Tool Інструмент «Коло» + Curvature Circle Tool Інструмент «Коло кривини» + Cusp Точка звороту + Straight segment Прямий сегмент Circle too large Коло завелике Classic Defaults Класичні значення за промовчанням Clean Up… Очистити… @@ -601,6 +604,9 @@ font-technology Variable Варіативні Box Channel Канал квадрата Color box Колірний квадрат Color Wheel Options Параметри колірного кола + Show Harmony Показати гармонію + Harmony Rule Правило гармонії + Harmony color Колір гармонії Color Type: Тип кольору: Color: Колір: Colorize Тонувати @@ -1034,10 +1040,25 @@ font-technology Variable Варіативні Duplicate Symbol Дублювати символ Duplicate {kind} Style Дублювати стиль {kind} Dutch Нідерландська + PSD Import Options Параметри імпорту PSD + Place PSD Помістити PSD + Convert Layers to Objects Перетворити шари на об’єкти + Import Hidden Layers Імпортувати приховані шари + Flatten Layers to a Single Image Звести шари в одне зображення + Import Slices Імпортувати фрагменти DXF Import Options Параметри імпорту DXF DXF Info Відомості про DXF DXF Options Параметри DXF DXF Options Dialog Діалогове вікно «Параметри DXF» + HP-GL Options Параметри HP-GL + HP-GL Options Dialog Діалогове вікно «Параметри HP-GL» + Curve Tolerance: Допуск кривих: + Origin: Початок координат: + Pens: Пера: + One Pen per Color Одне перо на колір + Pen Table Таблиця пер + Draw the Nearest Path Next Наступним малювати найближчий контур + Draw Inner Paths First Спершу малювати внутрішні контури e.g. 1-3, 5 напр. 1-3, 5 Each page prints as one image, at the document's raster effects resolution. Кожна сторінка друкується як одне зображення з роздільною здатністю растрових ефектів документа. Earth Tones Земляні тони @@ -1276,6 +1297,15 @@ font-technology Variable Варіативні Shading Color Колір затінення Black Overprint Чорний із накладенням Draw Hidden Faces Малювати приховані грані + Map Art… Накладання графіки… + Map Art Накладання графіки + First Surface Перша поверхня + Previous Surface Попередня поверхня + Next Surface Наступна поверхня + Last Surface Остання поверхня + Scale to Fit Масштабувати за розміром + Shade Artwork Затінювати графіку + Invisible Geometry Невидима геометрія Eyedropper Піпетка Sample Color from Screen Взяти колір з екрана This system has no screen color sampler У цій системі немає засобу вибору кольору з екрана @@ -1405,6 +1435,17 @@ font-technology Variable Варіативні Largest: Найбільше: Direction: Напрямок: Symbolism Tools Options Параметри інструментів символів + Tool: Інструмент: + Symbol Set Density Щільність набору символів + Symbol Sprayer Options Параметри розпилювача символів + Scrunch: Стиск: + Spin: Обертання: + Screen: Прозорість: + Stain: Тонування: + Symbol Sizer Options Параметри розміру символів + Proportional Resizing Пропорційна зміна розміру + Resizing Affects Density Зміна розміру впливає на щільність + Show Brush Size and Intensity Показувати розмір та інтенсивність пензля Symbol Set Density: Щільність набору символів: Flat Image Плоске зображення Flat Logo Плоский логотип @@ -1686,6 +1727,8 @@ file-filter Templates Шаблони More Options Додаткові параметри Show Properties Panel Показати панель «Властивості» Hide Corner Widget Приховати кутовий віджет + Hide Shape Widgets Приховати віджети фігур + Show Shape Widgets Показати віджети фігур Hide Corner Widget for angles greater than Приховувати кутовий віджет для кутів, більших за Hide Edges Приховати краї Hide Gradient Annotator Приховати маркер градієнта @@ -2258,6 +2301,15 @@ file-filter Templates Шаблони YakumonoZenkaku YakumonoZenkaku Kinsoku Set Набір kinsoku Kinsoku Shori Type Тип kinsoku shori + Kinsoku Shori Settings… Налаштування kinsoku shori… + Kinsoku Shori Settings Налаштування kinsoku shori + Kinsoku Sets Набори kinsoku + Kinsoku Set Base Основа набору kinsoku + Based on: На основі: + Cannot Start Line Не може починати рядок + Cannot End Line Не може закінчувати рядок + Hanging Punctuation Висяча пунктуація + Inseparable Characters Нероздільні символи Push In First Спершу втягувати Push Out First Спершу виштовхувати Push Out Only Лише виштовхувати @@ -2374,6 +2426,7 @@ file-filter Templates Шаблони Pressure Натиск Tilt Нахил Bearing Азимут + Stylus Wheel Коліщатко пера Shape: Форма: Bristle Length: Довжина щетинок: Bristle Density: Щільність щетинок: @@ -2404,6 +2457,9 @@ file-filter Templates Шаблони embedding for preview and print вбудовування для перегляду й друку embedding allowed вбудовування дозволено {file}; {embedding} {file}; {embedding} + unknown type невідомий тип + {type}; {uses} {type}; {uses} +@plural {n} use|{n} uses {n} використання|{n} використання|{n} використань substituted: shown in {family} {style} ({detail}) замінено: показано шрифтом {family} {style} ({detail}) missing: shown in {family} {style} відсутній: показано шрифтом {family} {style} missing відсутній @@ -2676,6 +2732,8 @@ file-filter Templates Шаблони Overprint and Transparency Flattener Options Параметри накладання та зведення прозорості Custom… Користувацькі… Custom Transparency Flattener Options Користувацькі параметри зведення прозорості + The PDF preset keeps the flattener preset but not the Custom… settings. Набір PDF зберігає набір зведення, але не параметри з «Користувацькі…». + PDF 1.3 files clip rasterized areas to their regions, and Overprint sets whether overprints are kept. Файли PDF 1.3 обрізають растеризовані області за їхніми контурами, а параметр «Накладення» визначає, чи зберігаються накладення. EPS has no alpha transparency, and Overprints sets whether overprints are kept. У EPS немає альфа-прозорості, а параметр «Накладення» визначає, чи зберігаються накладення. Overprint Black… Накладення чорного… Overprint Fill Накладання заливки @@ -3196,6 +3254,9 @@ digits Malayalam Малаялам Rotate View to Selection Повернути вид за виділенням Reset the rows to the artwork's colors Скинути рядки до кольорів малюнка Color Theme Picker Вибір колірної теми + Undo Changes Скасувати зміни + Redo Changes Повторити зміни +@msg Recolor Artwork is not open Вікно «Перефарбувати малюнок» не відкрито Click or drag across the art to pick its colors; Shift adds more Клацніть або проведіть по малюнку, щоб узяти його кольори; Shift додає ще Prominent Colors Переважні кольори Save All Colors Зберегти всі кольори @@ -3250,6 +3311,7 @@ digits Malayalam Малаялам A live rectangle's properties show one Corner Radius field for all four corners; off, each corner has its own field. Властивості динамічного прямокутника показують одне поле «Радіус кута» для всіх чотирьох кутів; якщо вимкнено, кожен кут має власне поле. What edits in the Transform panel transform: the object, its pattern tiles or both; Default follows Transform Pattern Tiles. Що трансформують зміни на панелі «Трансформувати»: об’єкт, плитки його візерунка або обидва; «За замовчуванням» слідує «Трансформувати плитки візерунка». With one symbol instance selected, the Transform panel uses the symbol's registration point as its reference point. Коли виділено один екземпляр символу, панель «Трансформувати» використовує точку реєстрації символу як опорну точку. + Drawing a rectangle, ellipse, polygon, star or line opens the Transform panel if it is closed. Малювання прямокутника, еліпса, багатокутника, зірки або лінії відкриває панель «Трансформувати», якщо вона закрита. Darkens the canvas outside the artboards while the Artboard tool is active. Затемнює полотно поза монтажними областями, поки активний інструмент «Монтажна область». With Fade Region Outside Artboard on, the area outside the artboards stays dark while you drag with the Artboard tool. Коли ввімкнено «Затемнювати ділянку поза монтажною областю», ділянка поза монтажними областями лишається темною, поки ви перетягуєте інструментом «Монтажна область». How near, in pixels, the pointer must be to an object, anchor or handle for a click to select it. Наскільки близько, у пікселях, вказівник має бути до об’єкта, опорної точки або маркера, щоб клацання виділило його. @@ -3430,6 +3492,7 @@ digits Malayalam Малаялам Save Document Preset Зберегти набір документа Preset {number} Набір {number} Save Preset… Зберегти набір… + Save Summary… Зберегти зведення… Save Print Preset Зберегти набір друку Save Recovery Data Зберегти дані відновлення Save Save for Web Preset Зберегти набір «Зберегти для Інтернету» @@ -3738,6 +3801,7 @@ digits Malayalam Малаялам Show Modified Показати змінені Show Note Показати примітку Show Options Показати параметри + Show on Shape Creation Показувати під час створення фігури Show Recent Colors Показати останні кольори Toggle RGB Percent Переключити RGB у відсотках Show Original Path Показати початковий контур @@ -3765,6 +3829,7 @@ digits Malayalam Малаялам Show Thumbnails Показати мініатюри Show Tile Edge Показати край плитки Show Tints/Shades Показати відтінки/тіні + Show Tool Cards Показувати картки інструментів Show Tool Tips Показувати підказки Show Transparency Grid Показати сітку прозорості Show Video Rulers Показати відео-лінійки @@ -3851,6 +3916,8 @@ effect Points Точки Outlines Контури Outlines with Source Image Контури з вихідним зображенням Source Image Вихідне зображення + Split View Розділений вигляд + Divider Роздільник Press and hold to view the source image Утримуйте, щоб побачити вихідне зображення Image Trace View Перегляд трасування зображення Snap Options Параметри прив’язки @@ -4304,6 +4371,8 @@ effect Points Точки Unembed… Витягти… Ungroup Розгрупувати Ungroup Color Group Розгрупувати колірну групу + Color Group Options Параметри колірної групи + Color Group Options… Параметри колірної групи… Unicode Unicode Unicode (UTF-16) Unicode (UTF-16) Unicode (UTF-8) Unicode (UTF-8) @@ -5086,6 +5155,7 @@ liquify-list-end {0}, {1} {0} і {1} @msg a freeform gradient keeps at least one point довільний градієнт зберігає як мінімум одну точку @msg a gradient needs at least two stops градієнту потрібні як мінімум дві точки переходу @msg a graphic style named `{to}` already exists графічний стиль з ім’ям `{to}` вже існує +@msg a swatch or color group named `{name}` already exists зразок або колірна група з ім’ям `{name}` вже існує @msg a key object sits on that point у цій точці розташований ключовий об’єкт @msg a page is missing сторінка відсутня @msg a page out of range сторінка поза діапазоном @@ -5227,6 +5297,11 @@ liquify-list-end {0}, {1} {0} і {1} @msg no anchor points selected опорні точки не виділені @msg `points` must be two or three [x, y] pairs of numbers `points` має містити дві або три пари чисел [x, y] @msg direct-select two or three anchor points, or give `points` виділіть дві або три опорні точки прямим виділенням або задайте `points` +@msg the path is straight there, so no circle matches its curvature контур у цьому місці прямий, тож його кривині не відповідає жодне коло +@msg the path has a cusp there, so it has no single curvature контур у цьому місці має точку звороту, тож не має єдиної кривини +@msg the path has a corner there, so it has no single curvature контур у цьому місці має кут, тож не має єдиної кривини +@msg a guide has no curvature circle напрямна не має кола кривини +@msg the circle that matches the path there would reach past the canvas коло, що відповідає контуру в цьому місці, вийшло б за межі полотна @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 немає монтажної області @@ -5483,6 +5558,7 @@ liquify-list-end {0}, {1} {0} і {1} @msg the PDF is password-protected: give its password PDF захищений паролем: вкажіть його пароль @msg the PDF password is wrong неправильний пароль PDF @msg the Save PDF dialog didn't open діалогове вікно «Зберегти PDF» не відкрилося +@msg the Save PDF dialog is not open діалогове вікно «Зберегти PDF» не відкрите @msg the WMF header is damaged заголовок WMF пошкоджений @msg the art could not be sampled не вдалося взяти зразок малюнка @msg the art has no bounds малюнок не має меж @@ -5706,6 +5782,7 @@ variable-list-end {0}, {1} {0} і {1} @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 +@msg give only one of `index`, `indices` and `t` вкажіть лише один із `index`, `indices` і `t` @msg column must be true or a number from 1 column має бути true або числом від 1 @msg x and y must both be numbers x і y мають бути числами @msg "{0}" is not a colour: write it as #rrggbb "{0}" не є кольором: запишіть його як #rrggbb @@ -5849,6 +5926,49 @@ variable-list-end {0}, {1} {0} і {1} @msg the PSD file's layer groups are nested too deeply групи шарів файлу PSD вкладено надто глибоко @msg a layer of the PSD file is too large to read шар файлу PSD завеликий для читання @msg the PSD file's layers take more memory to read than allowed для читання шарів файлу PSD потрібно більше пам’яті, ніж дозволено +@msg the file is no longer loaded файл більше не завантажено +@msg the layers can't be read ({e}): the file was placed as its merged image не вдається прочитати шари ({e}): файл поміщено як зведене зображення +@msg 1 type layer came in as pixels: the text isn't editable 1 текстовий шар імпортовано як пікселі: текст не можна редагувати +@msg {n} type layers came in as pixels: the text isn't editable текстових шарів, імпортованих як пікселі: {n}; текст не можна редагувати +@msg 1 adjustment layer was not applied 1 коригувальний шар не застосовано +@msg {n} adjustment layers were not applied не застосовано коригувальних шарів: {n} +@msg 1 fill layer was not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels) 1 шар заливки не намальовано (градієнтна чи візерункова заливка, колір, який не вдається прочитати, або фігура без збережених пікселів) +@msg {n} fill layers were not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels) не намальовано шарів заливки: {n} (градієнтна чи візерункова заливка, колір, який не вдається прочитати, або фігура без збережених пікселів) +@msg the layer effects of 1 layer weren't drawn ефекти шару для 1 шару не намальовано +@msg the layer effects of {n} layers weren't drawn ефекти шарів не намальовано; кількість шарів: {n} +@msg the vector masks of 1 layer weren't applied векторні маски 1 шару не застосовано +@msg the vector masks of {n} layers weren't applied векторні маски шарів не застосовано; кількість шарів: {n} +@msg the knockout of 1 layer wasn't applied вибивання 1 шару не застосовано +@msg the knockout of {n} layers wasn't applied вибивання шарів не застосовано; кількість шарів: {n} +@msg 1 layer was left out (hidden layers and the layers clipped to them) 1 шар пропущено (приховані шари й обрізані за ними шари) +@msg {n} layers were left out (hidden layers and the layers clipped to them) пропущено шарів: {n} (приховані шари й обрізані за ними шари) +@msg 1 layer clipped to a fill layer that wasn't drawn was left out 1 шар, обрізаний за ненамальованим шаром заливки, пропущено +@msg {n} layers clipped to fill layers that weren't drawn were left out пропущено шарів, обрізаних за ненамальованими шарами заливки: {n} +@msg layers in blend modes VectorCraft doesn't have ({modes}) were merged with the layers below them шари в режимах накладання, яких немає у VectorCraft ({modes}), зведено з шарами під ними +@msg 1 layer in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed 1 шар у режимі накладання, якого немає у VectorCraft, імпортовано як Звичайний: для зведення потрібно більше пам’яті, ніж дозволено +@msg {n} layers in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed шарів у режимах накладання, яких немає у VectorCraft, імпортовано як Звичайний: {n}; для зведення потрібно більше пам’яті, ніж дозволено +@msg 1 layer clipped to the layer below came in unclipped: the merge needs more memory than allowed 1 шар, обрізаний за нижнім шаром, імпортовано без обрізання: для зведення потрібно більше пам’яті, ніж дозволено +@msg {n} layers clipped to the layer below came in unclipped: the merge needs more memory than allowed шарів, обрізаних за нижнім шаром та імпортованих без обрізання: {n}; для зведення потрібно більше пам’яті, ніж дозволено +@msg hiddenLayers applies to a PSD file placed with layers: true hiddenLayers стосується PSD-файлу, який поміщається з layers: true +@msg importSlices: a linked PSD file is placed as its flat image; give link: false to embed it with its slices importSlices: зв’язаний PSD-файл поміщається як пласке зображення; вкажіть link: false, щоб вбудувати його з фрагментами +@msg layers: a linked PSD file is placed as its flat image; leave link out or give link: false layers: зв’язаний PSD-файл поміщається як пласке зображення; не вказуйте link або вкажіть link: false +@msg the slices can't be read ({e}) and were left out не вдається прочитати фрагменти ({e}), їх пропущено +@msg 1 slice lies outside the canvas or has no size and was left out 1 фрагмент лежить поза полотном або не має розміру й пропущений +@msg {n} slices lie outside the canvas or have no size and were left out пропущено фрагментів поза полотном або без розміру: {n} +@msg 1 slice would lie outside the canvas and was left out 1 фрагмент опинився б поза полотном і пропущений +@msg {n} slices would lie outside the canvas and were left out пропущено фрагментів, які опинилися б поза полотном: {n} +@msg the slices' descriptor holds too many values дескриптор фрагментів містить забагато значень +@msg the slices' descriptor has a version other than 16 версія дескриптора фрагментів відрізняється від 16 +@msg the slices are stored in version {v}, which isn't read фрагменти збережено у версії {v}, яка не читається +@msg the file has {count} slices, more than the {MAX_SLICES} read фрагментів у файлі: {count}, більше за {MAX_SLICES}, що читаються +@msg the slices' descriptor has no list of slices у дескрипторі фрагментів немає списку фрагментів +@msg the slices' descriptor lists something other than a slice дескриптор фрагментів перелічує щось, крім фрагмента +@msg a slice in the slices' descriptor has no bounds фрагмент у дескрипторі фрагментів не має меж +@msg a slice's bounds in the slices' descriptor aren't numbers межі фрагмента в дескрипторі фрагментів не є числами +@msg a text in the slices has more than the {MAX_TEXT} characters read текст у фрагментах довший за {MAX_TEXT} символів, що читаються +@msg the slices' descriptor nests too deep дескриптор фрагментів вкладено надто глибоко +@msg the slices' descriptor has a reference of an unknown kind ({_1}) у дескрипторі фрагментів є посилання невідомого виду ({_1}) +@msg the slices' descriptor has a value of an unknown type ({_1}) у дескрипторі фрагментів є значення невідомого типу ({_1}) @msg the layers can't be read ({e}): the file opened as its merged image не вдається прочитати шари ({e}): файл відкрито як зведене зображення @msg {depth}-bit PSD files in this colour mode can't be read {depth}-бітні файли PSD у цьому колірному режимі не читаються @msg the PSD file is cut short файл PSD обрізаний @@ -5876,6 +5996,25 @@ variable-list-end {0}, {1} {0} і {1} Preserve Embedded Profiles Зберігати вбудовані профілі Convert to Working Space Перетворювати в робочий простір Preserve Numbers Зберігати числа + Profile Mismatches: Невідповідність профілів: + Ask When Opening Питати під час відкриття + Ask When Pasting Питати під час вставлення + Missing Profiles: Відсутні профілі: + Embedded Profile Mismatch Невідповідність вбудованого профілю + Missing Profile Відсутній профіль + Paste Profile Mismatch Невідповідність профілю під час вставлення + “{name}” is not tagged with a {model} profile. «{name}» не має профілю {model}. + “{name}” is tagged with the {model} profile “{profile}”, which is not the {model} working space “{working}”. «{name}» має профіль {model} «{profile}», який не є робочим простором {model} «{working}». + Use the embedded profile Використати вбудований профіль + Convert the colors to the working space Перетворити кольори в робочий простір + Discard the embedded profile Відкинути вбудований профіль + Leave as is Залишити як є + Assign the working space Призначити робочий простір + Assign profile: Призначити профіль: + Preserve the color numbers Зберегти числові значення кольорів + Convert to keep the colors' appearance Перетворити, зберігши вигляд кольорів +@msg `{path}` goes with `{key}`: "assign" only `{path}` використовується лише з `{key}`: "assign" + The pasted colors come from a document whose {model} profile is “{from}”; this document's is “{to}”. Вставлені кольори взято з документа з профілем {model} «{from}»; профіль цього документа «{to}». Texture Текстура Craquelure… Кракелюри… Grain… Зерно… @@ -7743,6 +7882,8 @@ breakText Glyphs Гліфи # Path Precision Tools add-on: Tangent Circle. Tangent Circle… Дотичне коло… Tangent Circle Дотичне коло + Tangent Circle Tool Інструмент «Дотичне коло» + No tangent circle here Тут немає дотичного кола Circle: Коло: @msg `ids` names an object twice `ids` указує об’єкт двічі @msg select two or three paths or compound paths виділіть два або три контури чи складені контури @@ -7758,6 +7899,16 @@ breakText Glyphs Гліфи @msg `circle` is past the last circle found ({found}) `circle` більше за кількість знайдених кіл ({found}) @msg object {value} is not a path or compound path об’єкт {value} не є контуром чи складеним контуром @msg these shapes are too small to measure ці фігури замалі для вимірювання +# Path Precision Tools add-on: Add Bounding Rectangle and Add Bounding Circle. + Add Bounding Rectangle Додати описаний прямокутник + Add Bounding Circle Додати описане коло + Add Bounding Rectangle… Додати описаний прямокутник… + Add Bounding Circle… Додати описане коло… + One per Object По одній на об’єкт +@msg nothing to enclose нічого обводити +@msg `offset` must be 0 or more `offset` має бути 0 або більше +@msg the shape would have no size фігура не мала б розміру +@msg the shape would reach past the edge of the canvas фігура вийшла б за край полотна # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Інструменти документа Save a Timestamped Copy Зберегти копію з датою і часом @@ -10030,6 +10181,39 @@ breakText Glyphs Гліфи No objects are selected. Об’єкти не виділено. Open a document to mark its fold lines. Відкрийте документ, щоб позначити його лінії згину. Remove Fold Line Role Прибрати тип лінії +# Tool cards (General › Show Tool Cards): one sentence on what each tool does. + Shows a card with what a toolbar tool does and what its keys do instead of its tip; it needs Show Tool Tips. Замість підказки показує картку з тим, що роблять інструмент панелі та його клавіші; потрібно Показувати підказки. + Selects whole objects and groups to move, resize or rotate them. Виділяє об’єкти й групи цілком, щоб переміщувати, масштабувати або обертати їх. + Selects anchor points and path segments to reshape a path. Виділяє опорні точки й сегменти контуру, щоб змінити форму контуру. + Draws paths point by point, with straight segments and smooth curves. Малює контури точка за точкою, з прямими сегментами й плавними кривими. + Draws smooth curves through the points you click. Малює плавні криві через точки, на яких ви клацаєте. + Adds text at a point, or in a frame you drag. Додає текст у точці або в рамці, яку ви розтягуєте. + Draws rectangles and squares. Малює прямокутники й квадрати. + Draws rectangles with rounded corners. Малює прямокутники із заокругленими кутами. + Draws ellipses and circles. Малює еліпси й кола. + Draws polygons with sides of equal length. Малює багатокутники з рівними сторонами. + Draws stars. Малює зірки. + Turns objects around a reference point. Обертає об’єкти навколо опорної точки. + Flips objects across an axis through a reference point. Дзеркально відбиває об’єкти відносно осі, що проходить через опорну точку. + Resizes objects from a reference point. Масштабує об’єкти від опорної точки. + Slants objects from a reference point. Нахиляє об’єкти від опорної точки. + Moves the view of the document. Переміщує вигляд документа. + Magnifies or reduces the view. Збільшує або зменшує масштаб вигляду. + Copies the color and other attributes of one object to the selection. Копіює колір та інші атрибути одного об’єкта на виділення. + Sets the direction and length of a gradient. Задає напрямок і довжину градієнта. + Creates, selects and resizes artboards. Створює, виділяє й масштабує монтажні області. + Changes the width of a stroke along its length. Змінює ширину обведення вздовж його довжини. + Bends art by dragging pins placed on it. Згинає графіку перетягуванням шпильок, розставлених на ній. + Pushes the outlines of paths in the direction you drag. Зсуває обриси контурів у напрямку перетягування. + Twists the outlines of paths into swirls. Закручує обриси контурів у вихори. + Pulls the outlines of paths in toward the brush. Стягує обриси контурів до пензля. + Pushes the outlines of paths out from the brush. Роздуває обриси контурів від пензля назовні. + Adds curved details along the outlines of paths. Додає вигнуті деталі вздовж обрисів контурів. + Adds spiky details along the outlines of paths. Додає гострі деталі вздовж обрисів контурів. + Adds wrinkles along the outlines of paths. Додає складки вздовж обрисів контурів. + Moves, copies and resizes objects on the perspective grid. Переміщує, копіює й масштабує об’єкти на сітці перспективи. + Makes a series of steps between two or more objects. Створює ряд переходів між двома або більше об’єктами. + Places dimension lines that show measured lengths. Розміщує розмірні лінії з виміряними довжинами. Tap Коротке натискання Clear Hold Очистити утримання Hold Shortcuts Клавіші утримання @@ -10060,7 +10244,18 @@ breakText Glyphs Гліфи @msg A panel is not joined to the rest by a crease. Панель не з’єднана з рештою жодною лінією біговки. @msg A fold line is on a non-printing layer. Лінія згину лежить на шарі, що не друкується. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Панелі: {panels}, шарніри: {hinges}, помилки: {errors}, попередження: {warnings} + Paper Cutouts Паперові вирізки + Coral Layers Коралові шари + Mint Layers М’ятні шари + Midnight Layers Опівнічні шари + Sunflower Sheet Аркуш соняшника + Rose Layers Рожеві шари + Monochrome Stack Монохромний стос Dashed Arrow Пунктирна стрілка + Fine Stipple Тонке крапкове штрихування + Dense Stipple Щільне крапкове штрихування + Soft Stipple М’яке крапкове штрихування + Bold Stipple Грубе крапкове штрихування Pressure Sensitive Чутливі до натиску Flex Ribbon Гнучка стрічка Pulse Stroke Пульсуючий штрих @@ -10076,3 +10271,7 @@ breakText Glyphs Гліфи @msg Other blanks not shown: {count} Інші розгортки не показано: {count} @msg A joint does not close by {gap} pt. Стик не змикається на {gap} pt. @msg Two panels pass through each other. Дві панелі проходять одна крізь одну. + +# #5804 native-picked raster editor (draft translations; native review welcome). + Edit Original with: Редагувати оригінал у: +file-filter Applications Програми diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 246c5a881d..59bdd6b8d7 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -341,6 +341,7 @@ font-technology Variable Biến thiên Basic Latin Latin cơ bản Batch Hàng loạt Bearing Hướng + Stylus Wheel Bánh xe bút Begin Recording Bắt đầu ghi Exclude from playback Loại khỏi phát lại Include in playback Đưa vào phát lại @@ -577,6 +578,9 @@ font-technology Variable Biến thiên Choose… Chọn… Circle Hình tròn Circle Tool Công cụ Hình tròn + Curvature Circle Tool Công cụ Đường tròn mật tiếp + Cusp Điểm lùi + Straight segment Đoạn thẳng Circle too large Hình tròn quá lớn Classic Cổ điển Classic Defaults Mặc định cổ điển @@ -637,6 +641,25 @@ font-technology Variable Biến thiên Preserve Embedded Profiles Giữ cấu hình nhúng Convert to Working Space Chuyển sang không gian làm việc Preserve Numbers Giữ giá trị số + Profile Mismatches: Cấu hình không khớp: + Ask When Opening Hỏi khi mở + Ask When Pasting Hỏi khi dán + Missing Profiles: Cấu hình bị thiếu: + Embedded Profile Mismatch Cấu hình nhúng không khớp + Missing Profile Thiếu cấu hình + Paste Profile Mismatch Cấu hình không khớp khi dán + “{name}” is not tagged with a {model} profile. “{name}” không có cấu hình {model}. + “{name}” is tagged with the {model} profile “{profile}”, which is not the {model} working space “{working}”. “{name}” có cấu hình {model} “{profile}”, không phải không gian làm việc {model} “{working}”. + Use the embedded profile Dùng cấu hình nhúng + Convert the colors to the working space Chuyển màu sang không gian làm việc + Discard the embedded profile Bỏ cấu hình nhúng + Leave as is Giữ nguyên + Assign the working space Gán không gian làm việc + Assign profile: Gán cấu hình: + Preserve the color numbers Giữ giá trị số của màu + Convert to keep the colors' appearance Chuyển đổi để giữ diện mạo của màu +@msg `{path}` goes with `{key}`: "assign" only `{path}` chỉ dùng với `{key}`: "assign" + The pasted colors come from a document whose {model} profile is “{from}”; this document's is “{to}”. Màu đã dán đến từ tài liệu có cấu hình {model} “{from}”; cấu hình của tài liệu này là “{to}”. Coarse Dots Chấm thô Collapse Panels to Icons Thu gọn bảng thành biểu tượng Collapse to Icons Thu gọn thành biểu tượng @@ -700,6 +723,9 @@ font-technology Variable Biến thiên Box Channel Kênh của hộp Color box Hộp màu Color Wheel Options Tùy chọn bánh xe màu + Show Harmony Hiện hài hòa màu + Harmony Rule Quy tắc hài hòa màu + Harmony color Màu hài hòa Color Type: Loại màu: Color: Màu: Colorization Tô màu @@ -1210,10 +1236,25 @@ font-technology Variable Biến thiên Duplicate {kind} Style Nhân bản kiểu {kind} Duplication Nhân bản Dutch Tiếng Hà Lan + PSD Import Options Tùy chọn nhập PSD + Place PSD Đặt PSD + Convert Layers to Objects Chuyển các lớp thành đối tượng + Import Hidden Layers Nhập các lớp ẩn + Flatten Layers to a Single Image Làm phẳng các lớp thành một ảnh + Import Slices Nhập lát cắt DXF Import Options Tùy chọn nhập DXF DXF Info Thông tin DXF DXF Options Tùy chọn DXF DXF Options Dialog Hộp thoại tùy chọn DXF + HP-GL Options Tùy chọn HP-GL + HP-GL Options Dialog Hộp thoại tùy chọn HP-GL + Curve Tolerance: Dung sai đường cong: + Origin: Gốc tọa độ: + Pens: Bút: + One Pen per Color Một bút cho mỗi màu + Pen Table Bảng bút + Draw the Nearest Path Next Vẽ đường dẫn gần nhất tiếp theo + Draw Inner Paths First Vẽ các đường dẫn bên trong trước e.g. 1-3, 5 ví dụ: 1-3, 5 Each page prints as one image, at the document's raster effects resolution. Mỗi trang in như một ảnh, theo độ phân giải hiệu ứng raster của tài liệu. Earth Tones Tông màu đất @@ -1456,6 +1497,15 @@ font-technology Variable Biến thiên Shading Color Màu tô bóng Black Overprint Đen in chồng Draw Hidden Faces Vẽ các mặt ẩn + Map Art… Ánh xạ tác phẩm… + Map Art Ánh xạ tác phẩm + First Surface Bề mặt đầu tiên + Previous Surface Bề mặt trước + Next Surface Bề mặt tiếp theo + Last Surface Bề mặt cuối cùng + Scale to Fit Co giãn cho vừa + Shade Artwork Tô bóng tác phẩm + Invisible Geometry Hình học vô hình Eyedropper Ống hút màu Sample Color from Screen Lấy mẫu màu từ màn hình This system has no screen color sampler Hệ thống này không có công cụ lấy mẫu màu trên màn hình @@ -1918,6 +1968,8 @@ file-filter Templates Mẫu Hide Bounding Box Ẩn hộp giới hạn Hide Code Ẩn mã Hide Corner Widget Ẩn tiện ích góc + Hide Shape Widgets Ẩn tiện ích hình dạng + Show Shape Widgets Hiện tiện ích hình dạng Hide Corner Widget for angles greater than Ẩn tiện ích góc với góc lớn hơn Hide Edges Ẩn cạnh Hide Gradient Annotator Ẩn chú thích chuyển sắc @@ -2285,6 +2337,15 @@ digits Hindi Hindi Kind Loại Kinsoku Set Bộ Kinsoku Kinsoku Shori Type Kiểu Kinsoku Shori + Kinsoku Shori Settings… Cài đặt Kinsoku Shori… + Kinsoku Shori Settings Cài đặt Kinsoku Shori + Kinsoku Sets Các bộ Kinsoku + Kinsoku Set Base Cơ sở bộ Kinsoku + Based on: Dựa trên: + Cannot Start Line Không được bắt đầu dòng + Cannot End Line Không được kết thúc dòng + Hanging Punctuation Dấu câu treo + Inseparable Characters Ký tự không thể tách rời Knife Dao Knockout Group Nhóm Knockout Lab Lab @@ -2954,6 +3015,8 @@ digits Hindi Hindi Overprint and Transparency Flattener Options Tùy chọn in chồng và làm phẳng trong suốt Custom… Tùy chỉnh… Custom Transparency Flattener Options Tùy chọn làm phẳng trong suốt tùy chỉnh + The PDF preset keeps the flattener preset but not the Custom… settings. Thiết lập sẵn PDF giữ thiết lập sẵn làm phẳng, nhưng không giữ các cài đặt Tùy chỉnh…. + PDF 1.3 files clip rasterized areas to their regions, and Overprint sets whether overprints are kept. Tệp PDF 1.3 cắt các vùng được raster hóa theo vùng của chúng, và In chồng quyết định có giữ in chồng hay không. EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS không có trong suốt kênh Alpha, và In chồng quyết định có giữ in chồng hay không. Overprint Black… In chồng đen… Overprint Fill Tô in chồng @@ -3027,6 +3090,9 @@ digits Hindi Hindi embedding for preview and print nhúng để xem trước và in embedding allowed cho phép nhúng {file}; {embedding} {file}; {embedding} + unknown type loại không xác định + {type}; {uses} {type}; {uses} +@plural {n} use|{n} uses {n} lần dùng substituted: shown in {family} {style} ({detail}) đã thay thế: hiển thị bằng {family} {style} ({detail}) missing: shown in {family} {style} thiếu: hiển thị bằng {family} {style} missing thiếu @@ -3500,6 +3566,9 @@ mark-style Japanese Kiểu Nhật Reset Ruler Origin Đặt lại gốc thước Reset the rows to the artwork's colors Đặt lại các hàng về màu của tác phẩm Color Theme Picker Bộ chọn bộ màu + Undo Changes Hoàn tác thay đổi + Redo Changes Làm lại thay đổi +@msg Recolor Artwork is not open Tô màu lại tác phẩm chưa được mở Click or drag across the art to pick its colors; Shift adds more Nhấp hoặc kéo qua tác phẩm để lấy màu của nó; Shift để thêm Prominent Colors Màu nổi bật Save All Colors Lưu tất cả màu @@ -3566,6 +3635,7 @@ mark-style Japanese Kiểu Nhật A live rectangle's properties show one Corner Radius field for all four corners; off, each corner has its own field. Thuộc tính của một hình chữ nhật động hiển thị một trường Bán kính góc cho cả bốn góc; khi tắt, mỗi góc có trường riêng. What edits in the Transform panel transform: the object, its pattern tiles or both; Default follows Transform Pattern Tiles. Những gì thao tác trong bảng Biến đổi biến đổi: đối tượng, các ô họa tiết của nó hoặc cả hai; Mặc định theo Biến đổi ô họa tiết. With one symbol instance selected, the Transform panel uses the symbol's registration point as its reference point. Khi chọn một thể hiện biểu tượng, bảng Biến đổi dùng điểm đăng ký của biểu tượng làm điểm tham chiếu. + Drawing a rectangle, ellipse, polygon, star or line opens the Transform panel if it is closed. Vẽ hình chữ nhật, hình elip, đa giác, ngôi sao hoặc đường thẳng sẽ mở bảng Biến đổi nếu bảng đang đóng. Darkens the canvas outside the artboards while the Artboard tool is active. Làm tối khung vẽ bên ngoài các bảng vẽ khi công cụ Bảng vẽ đang hoạt động. With Fade Region Outside Artboard on, the area outside the artboards stays dark while you drag with the Artboard tool. Khi Làm tối vùng bên ngoài bảng vẽ đang bật, vùng bên ngoài các bảng vẽ vẫn tối trong khi bạn kéo bằng công cụ Bảng vẽ. How near, in pixels, the pointer must be to an object, anchor or handle for a click to select it. Con trỏ phải cách đối tượng, điểm neo hoặc tay nắm bao nhiêu pixel để một cú nhấp chọn được nó. @@ -3770,6 +3840,7 @@ mark-style Japanese Kiểu Nhật Save Document Preset Lưu thiết lập sẵn tài liệu Preset {number} Thiết lập sẵn {number} Save Preset… Lưu thiết lập sẵn… + Save Summary… Lưu tóm tắt… Save Print Preset Lưu thiết lập sẵn in Save Recovery Data Lưu dữ liệu khôi phục Save Save for Web Preset Lưu thiết lập sẵn Lưu cho Web @@ -4105,6 +4176,7 @@ mark-style Japanese Kiểu Nhật Show Modified Hiện đã sửa đổi Show Note Hiện ghi chú Show Options Hiện tùy chọn + Show on Shape Creation Hiện khi tạo hình dạng Show Recent Colors Hiện màu gần đây Toggle RGB Percent Chuyển đổi RGB theo phần trăm Show Original Path Hiện đường dẫn gốc @@ -4134,6 +4206,7 @@ mark-style Japanese Kiểu Nhật Show Tile Edge Hiện cạnh ô Show Tints/Shades Hiện tông/bóng màu Show Tool Group Labels Hiện nhãn nhóm công cụ + Show Tool Cards Hiện thẻ công cụ Show Tool Tips Hiện chú thích công cụ Show Transparency Grid Hiện lưới trong suốt Show Video Rulers Hiện thước video @@ -4232,6 +4305,8 @@ mark-style Japanese Kiểu Nhật Sort by Status Sắp xếp theo trạng thái Source code on GitHub Mã nguồn trên GitHub Source Image Ảnh nguồn + Split View Chế độ xem chia đôi + Divider Đường chia Source Sans 3 Source Sans 3 Space After Paragraph Khoảng cách sau đoạn văn Space Before Paragraph Khoảng cách trước đoạn văn @@ -4400,6 +4475,17 @@ mark-style Japanese Kiểu Nhật Symbol Libraries Thư viện ký hiệu Symbol Screener Tool Công cụ Lọc ký hiệu Symbol Scruncher Tool Công cụ Thu gọn ký hiệu + Tool: Công cụ: + Symbol Set Density Mật độ bộ ký hiệu + Symbol Sprayer Options Tùy chọn phun ký hiệu + Scrunch: Thu gọn: + Spin: Xoay: + Screen: Lọc: + Stain: Tô màu: + Symbol Sizer Options Tùy chọn kích thước ký hiệu + Proportional Resizing Đổi kích thước theo tỷ lệ + Resizing Affects Density Đổi kích thước ảnh hưởng đến mật độ + Show Brush Size and Intensity Hiện kích thước và cường độ cọ Symbol Set Density: Mật độ bộ ký hiệu: Symbol Shifter Tool Công cụ Dịch chuyển ký hiệu Symbol Sizer Tool Công cụ Kích thước ký hiệu @@ -4708,6 +4794,8 @@ mark-style Japanese Kiểu Nhật Unembed… Bỏ nhúng… Ungroup Bỏ nhóm Ungroup Color Group Bỏ nhóm màu + Color Group Options Tùy chọn nhóm màu + Color Group Options… Tùy chọn nhóm màu… Unicode Unicode Unicode (UTF-16) Unicode (UTF-16) Unicode (UTF-8) Unicode (UTF-8) @@ -5050,6 +5138,9 @@ theme Appearance Giao diện @msg a freeform gradient keeps at least one point chuyển sắc tự do cần giữ ít nhất một điểm @msg a gradient needs at least two stops chuyển sắc cần ít nhất hai điểm dừng @msg a graphic style named `{to}` already exists đã có kiểu đồ họa tên `{to}` +@msg a swatch or color group named `{name}` already exists đã có mẫu màu hoặc nhóm màu tên `{name}` +@msg missing `group` thiếu `group` +@msg no colour group `{group}` không có nhóm màu `{group}` @msg a key object sits on that point có đối tượng khóa nằm trên điểm đó @msg a layer couldn't be read một lớp không thể đọc được @msg a page is missing thiếu một trang @@ -5456,6 +5547,7 @@ liquify-list-end {0}, {1} {0} và {1} @msg give corners of the path: anchors where its sides meet at an angle hãy cung cấp các góc của đường dẫn: điểm neo nơi các cạnh gặp nhau tạo góc @msg give horizontal or vertical hãy chọn ngang hoặc dọc @msg give only one of onto, below and above chỉ cung cấp một trong onto, below và above +@msg give only one of `index`, `indices` and `t` chỉ cung cấp một trong `index`, `indices` và `t` @msg give the path `id` and the width point `index` hãy cung cấp `id` đường dẫn và `index` điểm chiều rộng @msg gradient “{name}” isn't defined in the file: a plain colour stands in for it chuyển sắc “{name}” không được định nghĩa trong tệp: một màu đơn thay thế @msg group must be true or false group phải là true hoặc false @@ -5552,6 +5644,7 @@ liquify-list-end {0}, {1} {0} và {1} @msg missing `folder` thiếu `folder` @msg missing `id` (see plugin.list) thiếu `id` (xem plugin.list) @msg missing `name` thiếu `name` +@msg missing `path` thiếu `path` @msg missing `tool` thiếu `tool` @msg missing id thiếu id @msg missing index thiếu chỉ mục @@ -5574,6 +5667,11 @@ liquify-list-end {0}, {1} {0} và {1} @msg no anchor points selected chưa chọn điểm neo @msg `points` must be two or three [x, y] pairs of numbers `points` phải là hai hoặc ba cặp số [x, y] @msg direct-select two or three anchor points, or give `points` hãy chọn trực tiếp hai hoặc ba điểm neo hoặc cung cấp `points` +@msg the path is straight there, so no circle matches its curvature đường dẫn thẳng tại đó, nên không có đường tròn nào khớp với độ cong của nó +@msg the path has a cusp there, so it has no single curvature đường dẫn có điểm lùi tại đó, nên không có một độ cong duy nhất +@msg the path has a corner there, so it has no single curvature đường dẫn có góc tại đó, nên không có một độ cong duy nhất +@msg a guide has no curvature circle đường căn không có đường tròn độ cong +@msg the circle that matches the path there would reach past the canvas đường tròn khớp với đường dẫn tại đó sẽ vượt quá giới hạn vùng vẽ @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ẽ @@ -6110,6 +6208,7 @@ liquify-list-end {0}, {1} {0} và {1} @msg HEIC and HEIF images can't be opened in this build không thể mở ảnh HEIC và HEIF trong bản dựng này @msg the PSD image is too large to read ({_1} × {_2} pixels) ảnh PSD quá lớn để đọc ({_1} × {_2} pixel) @msg the Save PDF dialog didn't open hộp thoại Lưu PDF không mở +@msg the Save PDF dialog is not open hộp thoại Lưu PDF chưa được mở @msg the scale is not a usable number tỷ lệ không phải là số dùng được @msg the search couldn't start: try again in a moment tìm kiếm không thể bắt đầu: hãy thử lại sau ít lâu @msg the selected stroke's profile is already listed as {_1} hồ sơ của nét đã chọn đã được liệt kê là {_1} @@ -6240,6 +6339,49 @@ variable-list-end {0}, {1} {0} và {1} @msg the PSD file's layer groups are nested too deeply các nhóm lớp của tệp PSD lồng nhau quá sâu @msg a layer of the PSD file is too large to read một lớp của tệp PSD quá lớn để đọc @msg the PSD file's layers take more memory to read than allowed các lớp của tệp PSD cần nhiều bộ nhớ để đọc hơn mức cho phép +@msg the file is no longer loaded tệp không còn được tải +@msg the layers can't be read ({e}): the file was placed as its merged image không thể đọc các lớp ({e}): tệp được đặt dưới dạng ảnh đã gộp +@msg 1 type layer came in as pixels: the text isn't editable 1 lớp văn bản được nhập dưới dạng điểm ảnh: không thể sửa văn bản +@msg {n} type layers came in as pixels: the text isn't editable {n} lớp văn bản được nhập dưới dạng điểm ảnh: không thể sửa văn bản +@msg 1 adjustment layer was not applied 1 lớp điều chỉnh không được áp dụng +@msg {n} adjustment layers were not applied {n} lớp điều chỉnh không được áp dụng +@msg 1 fill layer was not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels) 1 lớp tô không được vẽ (tô chuyển sắc hoặc mẫu, màu không đọc được, hoặc hình không lưu điểm ảnh nào) +@msg {n} fill layers were not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels) {n} lớp tô không được vẽ (tô chuyển sắc hoặc mẫu, màu không đọc được, hoặc hình không lưu điểm ảnh nào) +@msg the layer effects of 1 layer weren't drawn hiệu ứng lớp của 1 lớp không được vẽ +@msg the layer effects of {n} layers weren't drawn hiệu ứng lớp của {n} lớp không được vẽ +@msg the vector masks of 1 layer weren't applied mặt nạ vectơ của 1 lớp không được áp dụng +@msg the vector masks of {n} layers weren't applied mặt nạ vectơ của {n} lớp không được áp dụng +@msg the knockout of 1 layer wasn't applied phần đục lỗ của 1 lớp không được áp dụng +@msg the knockout of {n} layers wasn't applied phần đục lỗ của {n} lớp không được áp dụng +@msg 1 layer was left out (hidden layers and the layers clipped to them) 1 lớp bị bỏ qua (các lớp ẩn và các lớp được cắt theo chúng) +@msg {n} layers were left out (hidden layers and the layers clipped to them) {n} lớp bị bỏ qua (các lớp ẩn và các lớp được cắt theo chúng) +@msg 1 layer clipped to a fill layer that wasn't drawn was left out 1 lớp được cắt theo một lớp tô không được vẽ đã bị bỏ qua +@msg {n} layers clipped to fill layers that weren't drawn were left out {n} lớp được cắt theo các lớp tô không được vẽ đã bị bỏ qua +@msg layers in blend modes VectorCraft doesn't have ({modes}) were merged with the layers below them các lớp ở chế độ hòa trộn mà VectorCraft không có ({modes}) đã được gộp với các lớp bên dưới +@msg 1 layer in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed 1 lớp ở chế độ hòa trộn mà VectorCraft không có được nhập dưới dạng Thường: việc gộp cần nhiều bộ nhớ hơn mức cho phép +@msg {n} layers in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed {n} lớp ở các chế độ hòa trộn mà VectorCraft không có được nhập dưới dạng Thường: việc gộp cần nhiều bộ nhớ hơn mức cho phép +@msg 1 layer clipped to the layer below came in unclipped: the merge needs more memory than allowed 1 lớp được cắt theo lớp bên dưới được nhập mà không cắt: việc gộp cần nhiều bộ nhớ hơn mức cho phép +@msg {n} layers clipped to the layer below came in unclipped: the merge needs more memory than allowed {n} lớp được cắt theo lớp bên dưới được nhập mà không cắt: việc gộp cần nhiều bộ nhớ hơn mức cho phép +@msg hiddenLayers applies to a PSD file placed with layers: true hiddenLayers áp dụng cho tệp PSD được đặt với layers: true +@msg importSlices: a linked PSD file is placed as its flat image; give link: false to embed it with its slices importSlices: tệp PSD được liên kết được đặt dưới dạng ảnh phẳng; hãy đặt link: false để nhúng tệp cùng các lát cắt +@msg layers: a linked PSD file is placed as its flat image; leave link out or give link: false layers: tệp PSD được liên kết được đặt dưới dạng ảnh phẳng; hãy bỏ link hoặc đặt link: false +@msg the slices can't be read ({e}) and were left out không thể đọc các lát cắt ({e}) và chúng đã bị bỏ qua +@msg 1 slice lies outside the canvas or has no size and was left out 1 lát cắt nằm ngoài khung vẽ hoặc không có kích thước và đã bị bỏ qua +@msg {n} slices lie outside the canvas or have no size and were left out {n} lát cắt nằm ngoài khung vẽ hoặc không có kích thước và đã bị bỏ qua +@msg 1 slice would lie outside the canvas and was left out 1 lát cắt sẽ nằm ngoài khung vẽ và đã bị bỏ qua +@msg {n} slices would lie outside the canvas and were left out {n} lát cắt sẽ nằm ngoài khung vẽ và đã bị bỏ qua +@msg the slices' descriptor holds too many values bộ mô tả của các lát cắt chứa quá nhiều giá trị +@msg the slices' descriptor has a version other than 16 bộ mô tả của các lát cắt có phiên bản khác 16 +@msg the slices are stored in version {v}, which isn't read các lát cắt được lưu ở phiên bản {v}, phiên bản này không được đọc +@msg the file has {count} slices, more than the {MAX_SLICES} read tệp có {count} lát cắt, nhiều hơn {MAX_SLICES} lát cắt được đọc +@msg the slices' descriptor has no list of slices bộ mô tả của các lát cắt không có danh sách lát cắt +@msg the slices' descriptor lists something other than a slice bộ mô tả của các lát cắt liệt kê thứ khác ngoài lát cắt +@msg a slice in the slices' descriptor has no bounds một lát cắt trong bộ mô tả của các lát cắt không có giới hạn +@msg a slice's bounds in the slices' descriptor aren't numbers giới hạn của một lát cắt trong bộ mô tả của các lát cắt không phải là số +@msg a text in the slices has more than the {MAX_TEXT} characters read một văn bản trong các lát cắt dài hơn {MAX_TEXT} ký tự được đọc +@msg the slices' descriptor nests too deep bộ mô tả của các lát cắt lồng nhau quá sâu +@msg the slices' descriptor has a reference of an unknown kind ({_1}) bộ mô tả của các lát cắt có tham chiếu thuộc loại không xác định ({_1}) +@msg the slices' descriptor has a value of an unknown type ({_1}) bộ mô tả của các lát cắt có giá trị thuộc kiểu không xác định ({_1}) @msg the layers can't be read ({e}): the file opened as its merged image không thể đọc các lớp ({e}): tệp được mở dưới dạng ảnh đã gộp @msg zone must be a string zone phải là chuỗi @msg zone must be tab, center, left, right, top or bottom zone phải là tab, center, left, right, top hoặc bottom @@ -7787,6 +7929,8 @@ breakText Glyphs Glyph # Path Precision Tools add-on: Tangent Circle. Tangent Circle… Đường tròn tiếp xúc… Tangent Circle Đường tròn tiếp xúc + Tangent Circle Tool Công cụ Đường tròn tiếp xúc + No tangent circle here Không có đường tròn tiếp xúc ở đây Circle: Đường tròn: @msg `ids` names an object twice `ids` nêu một đối tượng hai lần @msg select two or three paths or compound paths chọn hai hoặc ba đường dẫn hoặc đường dẫn phức hợp @@ -7802,6 +7946,16 @@ breakText Glyphs Glyph @msg `circle` is past the last circle found ({found}) `circle` vượt quá đường tròn cuối cùng tìm được ({found}) @msg object {value} is not a path or compound path đối tượng {value} không phải đường dẫn hay đường dẫn phức hợp @msg these shapes are too small to measure các hình này quá nhỏ để đo +# Path Precision Tools add-on: Add Bounding Rectangle and Add Bounding Circle. + Add Bounding Rectangle Thêm hình chữ nhật bao quanh + Add Bounding Circle Thêm hình tròn bao quanh + Add Bounding Rectangle… Thêm hình chữ nhật bao quanh… + Add Bounding Circle… Thêm hình tròn bao quanh… + One per Object Một cho mỗi đối tượng +@msg nothing to enclose không có gì để bao quanh +@msg `offset` must be 0 or more `offset` phải từ 0 trở lên +@msg the shape would have no size hình sẽ không có kích thước +@msg the shape would reach past the edge of the canvas hình sẽ vượt quá mép vùng vẽ # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Công cụ tài liệu Save a Timestamped Copy Lưu bản sao có ngày giờ @@ -8288,6 +8442,50 @@ breakText Glyphs Glyph @msg {width} × {height} pixels is too large for Targa (at most 65535 pixels a side): lower the resolution {width} × {height} điểm ảnh quá lớn cho Targa (tối đa 65535 điểm ảnh mỗi cạnh): hãy giảm độ phân giải @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} điểm ảnh quá lớn cho PSD (tối đa {MAX_SIDE} điểm ảnh mỗi cạnh): hãy giảm độ phân giải @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer phải là "singleLine", "everyLine", "standardSingleLine" hoặc "standardEveryLine" + Fine Stipple Nét chấm mịn + Dense Stipple Nét chấm dày + Soft Stipple Nét chấm mềm + Bold Stipple Nét chấm đậm + Paper Cutouts Hình cắt giấy + Coral Layers Lớp san hô + Mint Layers Lớp bạc hà + Midnight Layers Lớp nửa đêm + Sunflower Sheet Tờ hướng dương + Rose Layers Lớp hoa hồng + Monochrome Stack Chồng đơn sắc +# Tool cards (General › Show Tool Cards): one sentence on what each tool does. + Shows a card with what a toolbar tool does and what its keys do instead of its tip; it needs Show Tool Tips. Hiện thẻ cho biết công cụ trên thanh công cụ và các phím của nó làm gì thay cho chú thích; cần bật Hiện chú thích công cụ. + Selects whole objects and groups to move, resize or rotate them. Chọn toàn bộ đối tượng và nhóm để di chuyển, đổi kích thước hoặc xoay chúng. + Selects anchor points and path segments to reshape a path. Chọn điểm neo và đoạn đường dẫn để thay đổi hình dạng một đường dẫn. + Draws paths point by point, with straight segments and smooth curves. Vẽ đường dẫn từng điểm một, với các đoạn thẳng và đường cong mượt. + Draws smooth curves through the points you click. Vẽ đường cong mượt đi qua các điểm bạn nhấp. + Adds text at a point, or in a frame you drag. Thêm văn bản tại một điểm hoặc trong một khung bạn kéo. + Draws rectangles and squares. Vẽ hình chữ nhật và hình vuông. + Draws rectangles with rounded corners. Vẽ hình chữ nhật bo góc. + Draws ellipses and circles. Vẽ hình elip và hình tròn. + Draws polygons with sides of equal length. Vẽ đa giác có các cạnh dài bằng nhau. + Draws stars. Vẽ ngôi sao. + Turns objects around a reference point. Xoay đối tượng quanh một điểm tham chiếu. + Flips objects across an axis through a reference point. Lật đối tượng qua một trục đi qua điểm tham chiếu. + Resizes objects from a reference point. Đổi kích thước đối tượng từ một điểm tham chiếu. + Slants objects from a reference point. Làm nghiêng đối tượng từ một điểm tham chiếu. + Moves the view of the document. Di chuyển khung nhìn của tài liệu. + Magnifies or reduces the view. Phóng to hoặc thu nhỏ khung nhìn. + Copies the color and other attributes of one object to the selection. Sao chép màu và các thuộc tính khác của một đối tượng sang vùng chọn. + Sets the direction and length of a gradient. Đặt hướng và độ dài của một dải chuyển sắc. + Creates, selects and resizes artboards. Tạo, chọn và đổi kích thước bảng vẽ. + Changes the width of a stroke along its length. Thay đổi độ rộng của nét dọc theo chiều dài của nó. + Bends art by dragging pins placed on it. Uốn hình vẽ bằng cách kéo các ghim đặt trên đó. + Pushes the outlines of paths in the direction you drag. Đẩy đường viền của đường dẫn theo hướng bạn kéo. + Twists the outlines of paths into swirls. Xoắn đường viền của đường dẫn thành các vòng xoáy. + Pulls the outlines of paths in toward the brush. Kéo đường viền của đường dẫn vào phía cọ. + Pushes the outlines of paths out from the brush. Đẩy đường viền của đường dẫn ra xa cọ. + Adds curved details along the outlines of paths. Thêm chi tiết cong dọc theo đường viền của đường dẫn. + Adds spiky details along the outlines of paths. Thêm chi tiết nhọn dọc theo đường viền của đường dẫn. + Adds wrinkles along the outlines of paths. Thêm nếp nhăn dọc theo đường viền của đường dẫn. + Moves, copies and resizes objects on the perspective grid. Di chuyển, sao chép và đổi kích thước đối tượng trên lưới phối cảnh. + Makes a series of steps between two or more objects. Tạo một loạt bước chuyển giữa hai hoặc nhiều đối tượng. + Places dimension lines that show measured lengths. Đặt các đường kích thước hiển thị độ dài đo được. Tap Nhấn nhanh Clear Hold Xóa nhấn giữ Hold Shortcuts Phím tắt nhấn giữ @@ -8306,3 +8504,7 @@ breakText Glyphs Glyph Round Flow Nét tròn Chisel Flow Nét vát @msg text.{key} `{v}`: use "{_1}" or "{_2}" text.{key} `{v}`: hãy dùng "{_1}" hoặc "{_2}" + +# #5804 native-picked raster editor (draft translations; native review welcome). + Edit Original with: Chỉnh sửa bản gốc bằng: +file-filter Applications Ứng dụng diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index d0220f4d20..be28bf81b3 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -447,6 +447,9 @@ antiAlias Sharp 锐利 Choose… 选择… Circle 圆形 Circle Tool 圆形工具 + Curvature Circle Tool 曲率圆工具 + Cusp 尖点 + Straight segment 直线段 Circle too large 圆形过大 Classic Defaults 经典默认 Clean Up… 清理… @@ -552,6 +555,9 @@ antiAlias Sharp 锐利 Box Channel 方块色版 Color box 颜色方块 Color Wheel Options 色轮选项 + Show Harmony 显示协调 + Harmony Rule 协调规则 + Harmony color 协调颜色 Color Type: 颜色类型: Color: 颜色: Colorize 上色 @@ -972,10 +978,25 @@ antiAlias Sharp 锐利 Duplicate Symbol 复制符号 Duplicate {kind} Style 制作{kind}样式的副本 Dutch 荷兰语 + PSD Import Options PSD 导入选项 + Place PSD 置入 PSD + Convert Layers to Objects 将图层转换为对象 + Import Hidden Layers 导入隐藏图层 + Flatten Layers to a Single Image 将图层拼合为单个图像 + Import Slices 导入切片 DXF Import Options DXF 导入选项 DXF Info DXF 信息 DXF Options DXF 选项 DXF Options Dialog DXF 选项对话框 + HP-GL Options HP-GL 选项 + HP-GL Options Dialog HP-GL 选项对话框 + Curve Tolerance: 曲线容差: + Origin: 原点: + Pens: 笔: + One Pen per Color 每种颜色一支笔 + Pen Table 笔表 + Draw the Nearest Path Next 接着绘制最近的路径 + Draw Inner Paths First 先绘制内部路径 e.g. 1-3, 5 例如 1-3, 5 Each page prints as one image, at the document's raster effects resolution. 每页会以文档的栅格效果分辨率打印为单一图像。 Earth Tones 大地色 @@ -1213,6 +1234,15 @@ antiAlias Sharp 锐利 Shading Color 底纹颜色 Black Overprint 黑色叠印 Draw Hidden Faces 绘制隐藏表面 + Map Art… 贴图… + Map Art 贴图 + First Surface 第一个表面 + Previous Surface 上一个表面 + Next Surface 下一个表面 + Last Surface 最后一个表面 + Scale to Fit 缩放以适合 + Shade Artwork 为图稿添加底纹 + Invisible Geometry 无形几何形状 Eyedropper 吸管 Sample Color from Screen 从屏幕取样颜色 This system has no screen color sampler 此系统没有屏幕取色工具 @@ -1342,6 +1372,17 @@ antiAlias Sharp 锐利 Largest: 最大: Direction: 方向: Symbolism Tools Options 符号工具选项 + Tool: 工具: + Symbol Set Density 符号组密度 + Symbol Sprayer Options 符号喷枪选项 + Scrunch: 紧缩: + Spin: 旋转: + Screen: 透明度: + Stain: 着色: + Symbol Sizer Options 符号缩放选项 + Proportional Resizing 等比缩放 + Resizing Affects Density 缩放影响密度 + Show Brush Size and Intensity 显示画笔大小和强度 Symbol Set Density: 符号组密度: Flat Image 平面图像 Flatness: 平滑度: @@ -1620,6 +1661,8 @@ file-filter Templates 模板 More Options 更多选项 Show Properties Panel 显示属性面板 Hide Corner Widget 隐藏角控件 + Hide Shape Widgets 隐藏形状控件 + Show Shape Widgets 显示形状控件 Hide Corner Widget for angles greater than 角度大于此值时隐藏圆角控件 Hide Edges 隐藏边缘 Hide Gradient Annotator 隐藏渐变批注器 @@ -2239,6 +2282,7 @@ file-filter Templates 模板 Pressure 压力 Tilt 倾斜 Bearing 方位 + Stylus Wheel 光笔滚轮 Shape: 形状: Bristle Length: 鬃毛长度: Bristle Density: 鬃毛密度: @@ -2269,6 +2313,9 @@ file-filter Templates 模板 embedding for preview and print 允许嵌入以供预览和打印 embedding allowed 允许嵌入 {file}; {embedding} {file};{embedding} + unknown type 未知类型 + {type}; {uses} {type};{uses} +@plural {n} use|{n} uses 使用 {n} 次 substituted: shown in {family} {style} ({detail}) 已替换:以 {family} {style} 显示 ({detail}) missing: shown in {family} {style} 缺失:以 {family} {style} 显示 missing 缺失 @@ -2538,6 +2585,8 @@ file-filter Templates 模板 Overprint and Transparency Flattener Options 叠印和透明度拼合器选项 Custom… 自定义… Custom Transparency Flattener Options 自定义透明度拼合器选项 + The PDF preset keeps the flattener preset but not the Custom… settings. PDF 预设会保留拼合预设,但不保留“自定义…”设置。 + PDF 1.3 files clip rasterized areas to their regions, and Overprint sets whether overprints are kept. PDF 1.3 文件会将栅格化区域剪切到其区域,“叠印”决定是否保留叠印。 EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS 没有 Alpha 透明度,“叠印”决定是否保留叠印。 Overprint Black… 黑色叠印… Overprint Fill 叠印填色 @@ -3055,6 +3104,9 @@ digits Malayalam 马拉雅拉姆数字 Rotate View to Selection 按所选对象旋转视图 Reset the rows to the artwork's colors 将各行重置为图稿的颜色 Color Theme Picker 色彩主题拾取器 + Undo Changes 撤销更改 + Redo Changes 重做更改 +@msg Recolor Artwork is not open 重新着色图稿未打开 Click or drag across the art to pick its colors; Shift adds more 单击或拖过图稿以拾取其颜色;按住 Shift 可添加更多 Prominent Colors 主要颜色 Save All Colors 存储所有颜色 @@ -3109,6 +3161,7 @@ digits Malayalam 马拉雅拉姆数字 A live rectangle's properties show one Corner Radius field for all four corners; off, each corner has its own field. 实时矩形的属性中为四个角显示一个圆角半径字段;关闭时,每个角都有自己的字段。 What edits in the Transform panel transform: the object, its pattern tiles or both; Default follows Transform Pattern Tiles. 变换面板中的编辑所变换的内容:对象、其图案拼贴或两者;默认跟随变换图案拼贴。 With one symbol instance selected, the Transform panel uses the symbol's registration point as its reference point. 选中一个符号实例时,变换面板使用符号的注册点作为参考点。 + Drawing a rectangle, ellipse, polygon, star or line opens the Transform panel if it is closed. 绘制矩形、椭圆、多边形、星形或直线时,如果变换面板已关闭,则会打开它。 Darkens the canvas outside the artboards while the Artboard tool is active. 使用画板工具时调暗画板以外的画布。 With Fade Region Outside Artboard on, the area outside the artboards stays dark while you drag with the Artboard tool. 调暗画板外的区域打开时,用画板工具拖动期间画板以外的区域保持变暗。 How near, in pixels, the pointer must be to an object, anchor or handle for a click to select it. 点击时指针需距离对象、锚点或手柄多少像素以内才能选中它。 @@ -3285,6 +3338,7 @@ digits Malayalam 马拉雅拉姆数字 Save Document Preset 保存文档预设 Preset {number} 预设 {number} Save Preset… 存储预设… + Save Summary… 存储摘要… Save Print Preset 保存打印预设 Save Recovery Data 保存恢复数据 Save Save for Web Preset 保存 Web 预设 @@ -3558,6 +3612,7 @@ digits Malayalam 马拉雅拉姆数字 Show Modified 显示已修改 Show Note 显示注解 Show Options 显示选项 + Show on Shape Creation 创建形状时显示 Show Recent Colors 显示最近使用的颜色 Toggle RGB Percent 切换 RGB 百分比显示 Show Original Path 显示原始路径 @@ -3585,6 +3640,7 @@ digits Malayalam 马拉雅拉姆数字 Show Thumbnails 显示缩略图 Show Tile Edge 显示拼贴边缘 Show Tints/Shades 显示浅色调/深色调 + Show Tool Cards 显示工具卡片 Show Tool Tips 显示工具提示 Show Transparency Grid 显示透明网格 Show Video Rulers 显示视频标尺 @@ -3670,6 +3726,8 @@ digits Malayalam 马拉雅拉姆数字 Outlines 轮廓 Outlines with Source Image 轮廓(带源图像) Source Image 源图像 + Split View 拆分视图 + Divider 分隔线 Press and hold to view the source image 按住以查看源图像 Image Trace View 图像描摹视图 Snap Options 对齐选项 @@ -4123,6 +4181,8 @@ digits Malayalam 马拉雅拉姆数字 Unembed… 取消嵌入… Ungroup 取消编组 Ungroup Color Group 取消编组颜色组 + Color Group Options 颜色组选项 + Color Group Options… 颜色组选项… Unicode Unicode Unicode (UTF-16) Unicode (UTF-16) Unicode (UTF-8) Unicode (UTF-8) @@ -4701,6 +4761,11 @@ imageTrace Outline 轮廓 @msg no anchor points selected 未选择锚点 @msg `points` must be two or three [x, y] pairs of numbers `points` 必须是两对或三对数字 [x, y] @msg direct-select two or three anchor points, or give `points` 请直接选择两个或三个锚点,或提供 `points` +@msg the path is straight there, so no circle matches its curvature 路径在该处是直的,因此没有圆与其曲率相符 +@msg the path has a cusp there, so it has no single curvature 路径在该处有尖点,因此没有唯一的曲率 +@msg the path has a corner there, so it has no single curvature 路径在该处有尖角,因此没有唯一的曲率 +@msg a guide has no curvature circle 参考线没有曲率圆 +@msg the circle that matches the path there would reach past the canvas 在该处与路径曲率相符的圆会超出画布 @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 请先退出隔离模式 @@ -4810,6 +4875,7 @@ imageTrace Outline 轮廓 @msg select a stroke with a variable width 请选择一个宽度可变的描边 @msg the selected stroke's profile is already listed as {_1} 所选描边的配置文件已列为 {_1} @msg a graphic style named `{to}` already exists 名为 `{to}` 的图形样式已存在 +@msg a swatch or color group named `{name}` already exists 名为 `{name}` 的色板或颜色组已存在 @msg no graphic style `{name}` 没有图形样式 `{name}` @msg node {_1} is not text 节点 {_1} 不是文字 @msg node {_1} is on a locked artboard 节点 {_1} 位于已锁定的画板上 @@ -5121,6 +5187,7 @@ imageTrace Outline 轮廓 @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 只能给出一个 +@msg give only one of `index`, `indices` and `t` `index`、`indices` 和 `t` 只能给出一个 @msg column must be true or a number from 1 column 必须是 true 或从 1 开始的数字 @msg unknown panel `{raw}` 未知面板 `{raw}` @msg `{panel}` has no display sizes to cycle `{panel}` 没有可切换的显示大小 @@ -5137,6 +5204,7 @@ imageTrace Outline 轮廓 @msg no file manager here 此处没有文件管理器 @msg no revert command 没有恢复命令 @msg the Save PDF dialog didn't open “保存 PDF”对话框未打开 +@msg the Save PDF dialog is not open “保存 PDF”对话框没有打开 @msg the document has never been saved 该文档从未保存过 @msg the export returned unreadable data 导出返回了无法读取的数据 @msg {status} ({e}) {status} ({e}) @@ -5576,6 +5644,49 @@ liquify-list-end {0}, {1} {0}和{1} @msg the PSD file's layer groups are nested too deeply PSD 文件的图层组嵌套过深 @msg a layer of the PSD file is too large to read PSD 文件的某个图层过大,无法读取 @msg the PSD file's layers take more memory to read than allowed 读取 PSD 文件的图层所需内存超过允许值 +@msg the file is no longer loaded 文件已不再载入 +@msg the layers can't be read ({e}): the file was placed as its merged image 无法读取图层 ({e}):文件已作为合并图像置入 +@msg 1 type layer came in as pixels: the text isn't editable 1 个文字图层以像素形式导入:文字不可编辑 +@msg {n} type layers came in as pixels: the text isn't editable {n} 个文字图层以像素形式导入:文字不可编辑 +@msg 1 adjustment layer was not applied 未应用 1 个调整图层 +@msg {n} adjustment layers were not applied 未应用 {n} 个调整图层 +@msg 1 fill layer was not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels) 未绘制 1 个填充图层(渐变或图案填充、无法读取的颜色,或不存储像素的形状) +@msg {n} fill layers were not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels) 未绘制 {n} 个填充图层(渐变或图案填充、无法读取的颜色,或不存储像素的形状) +@msg the layer effects of 1 layer weren't drawn 未绘制 1 个图层的图层效果 +@msg the layer effects of {n} layers weren't drawn 未绘制 {n} 个图层的图层效果 +@msg the vector masks of 1 layer weren't applied 未应用 1 个图层的矢量蒙版 +@msg the vector masks of {n} layers weren't applied 未应用 {n} 个图层的矢量蒙版 +@msg the knockout of 1 layer wasn't applied 未应用 1 个图层的挖空 +@msg the knockout of {n} layers wasn't applied 未应用 {n} 个图层的挖空 +@msg 1 layer was left out (hidden layers and the layers clipped to them) 已略去 1 个图层(隐藏的图层以及剪切到这些图层的图层) +@msg {n} layers were left out (hidden layers and the layers clipped to them) 已略去 {n} 个图层(隐藏的图层以及剪切到这些图层的图层) +@msg 1 layer clipped to a fill layer that wasn't drawn was left out 已略去 1 个剪切到未绘制填充图层的图层 +@msg {n} layers clipped to fill layers that weren't drawn were left out 已略去 {n} 个剪切到未绘制填充图层的图层 +@msg layers in blend modes VectorCraft doesn't have ({modes}) were merged with the layers below them 使用 VectorCraft 没有的混合模式 ({modes}) 的图层已与其下方的图层合并 +@msg 1 layer in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed 1 个使用 VectorCraft 没有的混合模式的图层以正常模式导入:合并需要的内存超出允许范围 +@msg {n} layers in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed {n} 个使用 VectorCraft 没有的混合模式的图层以正常模式导入:合并需要的内存超出允许范围 +@msg 1 layer clipped to the layer below came in unclipped: the merge needs more memory than allowed 1 个剪切到下方图层的图层未经剪切导入:合并需要的内存超出允许范围 +@msg {n} layers clipped to the layer below came in unclipped: the merge needs more memory than allowed {n} 个剪切到下方图层的图层未经剪切导入:合并需要的内存超出允许范围 +@msg hiddenLayers applies to a PSD file placed with layers: true hiddenLayers 适用于以 layers: true 置入的 PSD 文件 +@msg importSlices: a linked PSD file is placed as its flat image; give link: false to embed it with its slices importSlices:链接的 PSD 文件以拼合图像置入;指定 link: false 可将其连同切片一起嵌入 +@msg layers: a linked PSD file is placed as its flat image; leave link out or give link: false layers:链接的 PSD 文件以拼合图像置入;请省略 link 或指定 link: false +@msg the slices can't be read ({e}) and were left out 无法读取切片 ({e}),已略去 +@msg 1 slice lies outside the canvas or has no size and was left out 1 个切片位于画布之外或没有尺寸,已略去 +@msg {n} slices lie outside the canvas or have no size and were left out {n} 个切片位于画布之外或没有尺寸,已略去 +@msg 1 slice would lie outside the canvas and was left out 1 个切片会位于画布之外,已略去 +@msg {n} slices would lie outside the canvas and were left out {n} 个切片会位于画布之外,已略去 +@msg the slices' descriptor holds too many values 切片的描述符包含的值过多 +@msg the slices' descriptor has a version other than 16 切片的描述符版本不是 16 +@msg the slices are stored in version {v}, which isn't read 切片以不读取的版本 {v} 存储 +@msg the file has {count} slices, more than the {MAX_SLICES} read 文件有 {count} 个切片,超过读取的 {MAX_SLICES} 个 +@msg the slices' descriptor has no list of slices 切片的描述符没有切片列表 +@msg the slices' descriptor lists something other than a slice 切片的描述符列出了切片以外的内容 +@msg a slice in the slices' descriptor has no bounds 切片描述符中的一个切片没有边界 +@msg a slice's bounds in the slices' descriptor aren't numbers 切片描述符中一个切片的边界不是数字 +@msg a text in the slices has more than the {MAX_TEXT} characters read 切片中的一段文字超过读取的 {MAX_TEXT} 个字符 +@msg the slices' descriptor nests too deep 切片的描述符嵌套过深 +@msg the slices' descriptor has a reference of an unknown kind ({_1}) 切片的描述符含有未知种类的引用 ({_1}) +@msg the slices' descriptor has a value of an unknown type ({_1}) 切片的描述符含有未知类型的值 ({_1}) @msg the layers can't be read ({e}): the file opened as its merged image 无法读取图层 ({e}):文件已作为合并图像打开 @msg {depth}-bit PSD files in this colour mode can't be read 无法读取此颜色模式下的 {depth} 位 PSD 文件 @msg the PSD file is cut short PSD 文件不完整 @@ -5773,6 +5884,25 @@ liquify-list-end {0}, {1} {0}和{1} Preserve Embedded Profiles 保留嵌入的配置文件 Convert to Working Space 转换为工作空间 Preserve Numbers 保留数值 + Profile Mismatches: 配置文件不匹配: + Ask When Opening 打开时询问 + Ask When Pasting 粘贴时询问 + Missing Profiles: 缺少配置文件: + Embedded Profile Mismatch 嵌入的配置文件不匹配 + Missing Profile 缺少配置文件 + Paste Profile Mismatch 粘贴时配置文件不匹配 + “{name}” is not tagged with a {model} profile. “{name}”没有 {model} 配置文件。 + “{name}” is tagged with the {model} profile “{profile}”, which is not the {model} working space “{working}”. “{name}”的 {model} 配置文件为“{profile}”,不是 {model} 工作空间“{working}”。 + Use the embedded profile 使用嵌入的配置文件 + Convert the colors to the working space 将颜色转换为工作空间 + Discard the embedded profile 放弃嵌入的配置文件 + Leave as is 保持原样 + Assign the working space 指定工作空间 + Assign profile: 指定配置文件: + Preserve the color numbers 保留颜色数值 + Convert to keep the colors' appearance 转换以保持颜色外观 +@msg `{path}` goes with `{key}`: "assign" only `{path}` 只能与 `{key}`: "assign" 一起给出 + The pasted colors come from a document whose {model} profile is “{from}”; this document's is “{to}”. 粘贴的颜色来自 {model} 配置文件为“{from}”的文档;此文档的配置文件为“{to}”。 Art & Illustration 艺术和插画 Branding 品牌 Film & Video 影片和视频 @@ -5986,6 +6116,15 @@ font-technology Variable 可变 YakumonoZenkaku YakumonoZenkaku Kinsoku Set Kinsoku 集 Kinsoku Shori Type Kinsoku 处理方式 + Kinsoku Shori Settings… Kinsoku 处理设置… + Kinsoku Shori Settings Kinsoku 处理设置 + Kinsoku Sets Kinsoku 集列表 + Kinsoku Set Base Kinsoku 集基准 + Based on: 基于: + Cannot Start Line 不能位于行首 + Cannot End Line 不能位于行尾 + Hanging Punctuation 悬挂标点 + Inseparable Characters 不可分割字符 Push In First 先推入 Push Out First 先推出 Push Out Only 只推出 @@ -7969,6 +8108,8 @@ breakText Glyphs 字形 # Path Precision Tools add-on: Tangent Circle. Tangent Circle… 相切圆… Tangent Circle 相切圆 + Tangent Circle Tool 相切圆工具 + No tangent circle here 此处没有相切圆 Circle: 圆: @msg `ids` names an object twice `ids` 重复指定了同一个对象 @msg select two or three paths or compound paths 请选择两个或三个路径或复合路径 @@ -7984,6 +8125,16 @@ breakText Glyphs 字形 @msg `circle` is past the last circle found ({found}) `circle` 超出了找到的最后一个圆({found}) @msg object {value} is not a path or compound path 对象 {value} 不是路径或复合路径 @msg these shapes are too small to measure 这些形状太小,无法测量 +# Path Precision Tools add-on: Add Bounding Rectangle and Add Bounding Circle. + Add Bounding Rectangle 添加外接矩形 + Add Bounding Circle 添加外接圆 + Add Bounding Rectangle… 添加外接矩形… + Add Bounding Circle… 添加外接圆… + One per Object 每个对象一个 +@msg nothing to enclose 没有可包围的内容 +@msg `offset` must be 0 or more `offset` 必须大于或等于 0 +@msg the shape would have no size 形状将没有大小 +@msg the shape would reach past the edge of the canvas 形状将超出画布边缘 # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools 文档工具 Save a Timestamped Copy 保存带时间戳的副本 @@ -10286,6 +10437,50 @@ breakText Glyphs 字形 @msg A joint does not close by {gap} pt. 有一处接缝相差 {gap} pt 未闭合。 @msg Two panels pass through each other. 两个面板相互穿插。 @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} 像素对 PSD 而言过大 (每边最多 {MAX_SIDE} 像素):请降低分辨率 + Fine Stipple 细密点描 + Dense Stipple 浓密点描 + Soft Stipple 柔和点描 + Bold Stipple 粗重点描 + Paper Cutouts 剪纸 + Coral Layers 珊瑚色图层 + Mint Layers 薄荷色图层 + Midnight Layers 午夜色图层 + Sunflower Sheet 向日葵纸片 + Rose Layers 玫瑰色图层 + Monochrome Stack 单色叠层 +# Tool cards (General › Show Tool Cards): one sentence on what each tool does. + Shows a card with what a toolbar tool does and what its keys do instead of its tip; it needs Show Tool Tips. 以卡片代替提示,显示工具栏工具及其按键的作用;需要开启显示工具提示。 + Selects whole objects and groups to move, resize or rotate them. 选择整个对象和编组,以移动、缩放或旋转它们。 + Selects anchor points and path segments to reshape a path. 选择锚点和路径段,以改变路径的形状。 + Draws paths point by point, with straight segments and smooth curves. 逐点绘制路径,包括直线段和平滑曲线。 + Draws smooth curves through the points you click. 绘制经过所点击各点的平滑曲线。 + Adds text at a point, or in a frame you drag. 在某一点或拖出的文本框中添加文字。 + Draws rectangles and squares. 绘制矩形和正方形。 + Draws rectangles with rounded corners. 绘制圆角矩形。 + Draws ellipses and circles. 绘制椭圆和圆形。 + Draws polygons with sides of equal length. 绘制各边等长的多边形。 + Draws stars. 绘制星形。 + Turns objects around a reference point. 围绕参考点旋转对象。 + Flips objects across an axis through a reference point. 沿经过参考点的轴镜像对象。 + Resizes objects from a reference point. 从参考点缩放对象。 + Slants objects from a reference point. 从参考点倾斜对象。 + Moves the view of the document. 移动文档的视图。 + Magnifies or reduces the view. 放大或缩小视图。 + Copies the color and other attributes of one object to the selection. 将一个对象的颜色和其他属性复制到所选对象。 + Sets the direction and length of a gradient. 设置渐变的方向和长度。 + Creates, selects and resizes artboards. 创建、选择画板并调整其大小。 + Changes the width of a stroke along its length. 沿描边的长度改变其宽度。 + Bends art by dragging pins placed on it. 拖动放在图稿上的图钉来弯曲图稿。 + Pushes the outlines of paths in the direction you drag. 沿拖动方向推动路径的轮廓。 + Twists the outlines of paths into swirls. 将路径的轮廓扭转成漩涡。 + Pulls the outlines of paths in toward the brush. 将路径的轮廓向画笔收缩。 + Pushes the outlines of paths out from the brush. 将路径的轮廓从画笔向外膨胀。 + Adds curved details along the outlines of paths. 沿路径的轮廓添加弧形细节。 + Adds spiky details along the outlines of paths. 沿路径的轮廓添加尖刺细节。 + Adds wrinkles along the outlines of paths. 沿路径的轮廓添加皱褶。 + Moves, copies and resizes objects on the perspective grid. 在透视网格上移动、复制和缩放对象。 + Makes a series of steps between two or more objects. 在两个或多个对象之间生成一系列步骤。 + Places dimension lines that show measured lengths. 放置显示测量长度的尺寸线。 Tap 短按 Clear Hold 清除按住 Hold Shortcuts 按住快捷键 @@ -10302,3 +10497,7 @@ breakText Glyphs 字形 Pulse Stroke 脉动笔触 Round Flow 圆头流线 Chisel Flow 斜头流线 + +# #5804 native-picked raster editor (draft translations; native review welcome). + Edit Original with: 编辑原稿所用应用: +file-filter Applications 应用程序 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 8fab1fe968..85ff10fb43 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -462,6 +462,9 @@ font-technology Variable 可變 Choose… 選擇… Circle 圓形 Circle Tool 圓形工具 + Curvature Circle Tool 曲率圓工具 + Cusp 尖點 + Straight segment 直線段 Circle too large 圓形過大 Classic Defaults 經典預設值 Clean Up… 清除… @@ -569,6 +572,9 @@ font-technology Variable 可變 Box Channel 方塊色版 Color box 顏色方塊 Color Wheel Options 色輪選項 + Show Harmony 顯示色彩調和 + Harmony Rule 色彩調和規則 + Harmony color 調和色彩 Color Type: 顏色類型: Color: 顏色: Colorize 上色 @@ -1002,10 +1008,25 @@ font-technology Variable 可變 Duplicate Symbol 製作符號複本 Duplicate {kind} Style 製作{kind}樣式的複本 Dutch 荷蘭文 + PSD Import Options PSD 匯入選項 + Place PSD 置入 PSD + Convert Layers to Objects 將圖層轉換為物件 + Import Hidden Layers 匯入隱藏圖層 + Flatten Layers to a Single Image 將圖層平面化為單一影像 + Import Slices 匯入切片 DXF Import Options DXF 匯入選項 DXF Info DXF 資訊 DXF Options DXF 選項 DXF Options Dialog DXF 選項對話框 + HP-GL Options HP-GL 選項 + HP-GL Options Dialog HP-GL 選項對話框 + Curve Tolerance: 曲線容許度: + Origin: 原點: + Pens: 筆: + One Pen per Color 每種顏色一支筆 + Pen Table 筆表 + Draw the Nearest Path Next 接著繪製最近的路徑 + Draw Inner Paths First 先繪製內部路徑 e.g. 1-3, 5 例如 1-3, 5 Each page prints as one image, at the document's raster effects resolution. 每頁會以文件的點陣效果解析度列印為單一影像。 Earth Tones 大地色系 @@ -1246,6 +1267,15 @@ font-technology Variable 可變 Shading Color 網底顏色 Black Overprint 黑色疊印 Draw Hidden Faces 繪製隱藏表面 + Map Art… 貼圖… + Map Art 貼圖 + First Surface 第一個表面 + Previous Surface 上一個表面 + Next Surface 下一個表面 + Last Surface 最後一個表面 + Scale to Fit 縮放以符合 + Shade Artwork 為圖稿加上網底 + Invisible Geometry 隱形幾何形狀 Eyedropper 滴管 Sample Color from Screen 從螢幕取樣顏色 This system has no screen color sampler 此系統沒有螢幕取色工具 @@ -1376,6 +1406,17 @@ font-technology Variable 可變 Largest: 最大: Direction: 方向: Symbolism Tools Options 符號工具選項 + Tool: 工具: + Symbol Set Density 符號組密度 + Symbol Sprayer Options 符號噴灑器選項 + Scrunch: 緊縮: + Spin: 旋轉: + Screen: 濾色: + Stain: 染色: + Symbol Sizer Options 符號縮放器選項 + Proportional Resizing 等比例縮放 + Resizing Affects Density 縮放影響密度 + Show Brush Size and Intensity 顯示筆刷大小和強度 Symbol Set Density: 符號組密度: Flat Image 平面影像 Flatness: 平滑度: @@ -1657,6 +1698,8 @@ file-filter Templates 範本 More Options 更多選項 Show Properties Panel 顯示內容面板 Hide Corner Widget 隱藏轉角 Widget + Hide Shape Widgets 隱藏形狀 Widget + Show Shape Widgets 顯示形狀 Widget Hide Corner Widget for angles greater than 角度大於以下數值時隱藏轉角 Widget Hide Edges 隱藏邊緣 Hide Gradient Annotator 隱藏漸層註解者 @@ -2150,6 +2193,11 @@ file-filter Templates 範本 @msg no anchor points selected 未選取錨點 @msg `points` must be two or three [x, y] pairs of numbers `points` 必須是兩組或三組數字 [x, y] @msg direct-select two or three anchor points, or give `points` 請以直接選取方式選取兩個或三個錨點,或提供 `points` +@msg the path is straight there, so no circle matches its curvature 路徑在該處是直的,因此沒有圓與其曲率相符 +@msg the path has a cusp there, so it has no single curvature 路徑在該處有尖點,因此沒有唯一的曲率 +@msg the path has a corner there, so it has no single curvature 路徑在該處有角點,因此沒有唯一的曲率 +@msg a guide has no curvature circle 參考線沒有曲率圓 +@msg the circle that matches the path there would reach past the canvas 在該處與路徑曲率相符的圓會超出畫布 @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 請先結束隔離模式 @@ -2259,6 +2307,7 @@ file-filter Templates 範本 @msg select a stroke with a variable width 請選取寬度可變的筆畫 @msg the selected stroke's profile is already listed as {_1} 所選筆畫的描述檔已列為 {_1} @msg a graphic style named `{to}` already exists 名為 `{to}` 的繪圖樣式已存在 +@msg a swatch or color group named `{name}` already exists 名為 `{name}` 的色票或顏色群組已存在 @msg no graphic style `{name}` 沒有繪圖樣式 `{name}` @msg node {_1} is not text 節點 {_1} 不是文字 @msg node {_1} is on a locked artboard 節點 {_1} 位於已鎖定的工作區域上 @@ -2573,6 +2622,7 @@ file-filter Templates 範本 @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 只能提供其中一個 +@msg give only one of `index`, `indices` and `t` `index`、`indices` 和 `t` 只能提供其中一個 @msg column must be true or a number from 1 column 必須是 true 或從 1 起算的數字 @msg unknown panel `{raw}` 未知的面板 `{raw}` @msg `{panel}` has no display sizes to cycle `{panel}` 沒有可切換的顯示大小 @@ -2589,6 +2639,7 @@ file-filter Templates 範本 @msg no file manager here 此處沒有檔案管理員 @msg no revert command 沒有回復指令 @msg the Save PDF dialog didn't open 「儲存 PDF」對話框未開啟 +@msg the Save PDF dialog is not open 「儲存 PDF」對話框沒有開啟 @msg the document has never been saved 文件從未儲存過 @msg the export returned unreadable data 匯出傳回了無法讀取的資料 @msg {status} ({e}) {status} ({e}) @@ -3029,6 +3080,49 @@ liquify-list-end {0}, {1} {0}和{1} @msg the PSD file's layer groups are nested too deeply PSD 檔案的圖層群組巢狀過深 @msg a layer of the PSD file is too large to read PSD 檔案的某個圖層過大,無法讀取 @msg the PSD file's layers take more memory to read than allowed 讀取 PSD 檔案的圖層所需記憶體超過允許值 +@msg the file is no longer loaded 檔案已不再載入 +@msg the layers can't be read ({e}): the file was placed as its merged image 無法讀取圖層 ({e}):檔案已以合併影像置入 +@msg 1 type layer came in as pixels: the text isn't editable 1 個文字圖層以像素形式匯入:文字無法編輯 +@msg {n} type layers came in as pixels: the text isn't editable {n} 個文字圖層以像素形式匯入:文字無法編輯 +@msg 1 adjustment layer was not applied 未套用 1 個調整圖層 +@msg {n} adjustment layers were not applied 未套用 {n} 個調整圖層 +@msg 1 fill layer was not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels) 未繪製 1 個填色圖層(漸層或圖樣填色、無法讀取的顏色,或不儲存像素的形狀) +@msg {n} fill layers were not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels) 未繪製 {n} 個填色圖層(漸層或圖樣填色、無法讀取的顏色,或不儲存像素的形狀) +@msg the layer effects of 1 layer weren't drawn 未繪製 1 個圖層的圖層效果 +@msg the layer effects of {n} layers weren't drawn 未繪製 {n} 個圖層的圖層效果 +@msg the vector masks of 1 layer weren't applied 未套用 1 個圖層的向量遮色片 +@msg the vector masks of {n} layers weren't applied 未套用 {n} 個圖層的向量遮色片 +@msg the knockout of 1 layer wasn't applied 未套用 1 個圖層的去底色 +@msg the knockout of {n} layers wasn't applied 未套用 {n} 個圖層的去底色 +@msg 1 layer was left out (hidden layers and the layers clipped to them) 已略過 1 個圖層(隱藏的圖層以及剪裁至這些圖層的圖層) +@msg {n} layers were left out (hidden layers and the layers clipped to them) 已略過 {n} 個圖層(隱藏的圖層以及剪裁至這些圖層的圖層) +@msg 1 layer clipped to a fill layer that wasn't drawn was left out 已略過 1 個剪裁至未繪製填色圖層的圖層 +@msg {n} layers clipped to fill layers that weren't drawn were left out 已略過 {n} 個剪裁至未繪製填色圖層的圖層 +@msg layers in blend modes VectorCraft doesn't have ({modes}) were merged with the layers below them 使用 VectorCraft 沒有的混合模式 ({modes}) 的圖層已與其下方的圖層合併 +@msg 1 layer in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed 1 個使用 VectorCraft 沒有的混合模式的圖層以正常模式匯入:合併所需的記憶體超出允許範圍 +@msg {n} layers in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed {n} 個使用 VectorCraft 沒有的混合模式的圖層以正常模式匯入:合併所需的記憶體超出允許範圍 +@msg 1 layer clipped to the layer below came in unclipped: the merge needs more memory than allowed 1 個剪裁至下方圖層的圖層未經剪裁匯入:合併所需的記憶體超出允許範圍 +@msg {n} layers clipped to the layer below came in unclipped: the merge needs more memory than allowed {n} 個剪裁至下方圖層的圖層未經剪裁匯入:合併所需的記憶體超出允許範圍 +@msg hiddenLayers applies to a PSD file placed with layers: true hiddenLayers 適用於以 layers: true 置入的 PSD 檔案 +@msg importSlices: a linked PSD file is placed as its flat image; give link: false to embed it with its slices importSlices:連結的 PSD 檔案會以平面影像置入;指定 link: false 即可連同切片一起嵌入 +@msg layers: a linked PSD file is placed as its flat image; leave link out or give link: false layers:連結的 PSD 檔案會以平面影像置入;請不要指定 link,或指定 link: false +@msg the slices can't be read ({e}) and were left out 無法讀取切片 ({e}),已略過 +@msg 1 slice lies outside the canvas or has no size and was left out 1 個切片位於畫布之外或沒有尺寸,已略過 +@msg {n} slices lie outside the canvas or have no size and were left out {n} 個切片位於畫布之外或沒有尺寸,已略過 +@msg 1 slice would lie outside the canvas and was left out 1 個切片會位於畫布之外,已略過 +@msg {n} slices would lie outside the canvas and were left out {n} 個切片會位於畫布之外,已略過 +@msg the slices' descriptor holds too many values 切片的描述元包含的值過多 +@msg the slices' descriptor has a version other than 16 切片的描述元版本不是 16 +@msg the slices are stored in version {v}, which isn't read 切片以不讀取的版本 {v} 儲存 +@msg the file has {count} slices, more than the {MAX_SLICES} read 檔案有 {count} 個切片,超過讀取的 {MAX_SLICES} 個 +@msg the slices' descriptor has no list of slices 切片的描述元沒有切片清單 +@msg the slices' descriptor lists something other than a slice 切片的描述元列出了切片以外的內容 +@msg a slice in the slices' descriptor has no bounds 切片描述元中的一個切片沒有邊界 +@msg a slice's bounds in the slices' descriptor aren't numbers 切片描述元中一個切片的邊界不是數字 +@msg a text in the slices has more than the {MAX_TEXT} characters read 切片中的一段文字超過讀取的 {MAX_TEXT} 個字元 +@msg the slices' descriptor nests too deep 切片的描述元巢狀過深 +@msg the slices' descriptor has a reference of an unknown kind ({_1}) 切片的描述元含有未知種類的參照 ({_1}) +@msg the slices' descriptor has a value of an unknown type ({_1}) 切片的描述元含有未知類型的值 ({_1}) @msg the layers can't be read ({e}): the file opened as its merged image 無法讀取圖層 ({e}):檔案已以合併影像開啟 @msg {depth}-bit PSD files in this colour mode can't be read 無法讀取此色彩模式的 {depth} 位元 PSD 檔案 @msg the PSD file is cut short PSD 檔案不完整 @@ -3446,6 +3540,15 @@ liquify-list-end {0}, {1} {0}和{1} YakumonoZenkaku YakumonoZenkaku Kinsoku Set Kinsoku 集 Kinsoku Shori Type Kinsoku 處理方式 + Kinsoku Shori Settings… Kinsoku 處理設定… + Kinsoku Shori Settings Kinsoku 處理設定 + Kinsoku Sets Kinsoku 集清單 + Kinsoku Set Base Kinsoku 集基準 + Based on: 依據: + Cannot Start Line 不能位於行首 + Cannot End Line 不能位於行尾 + Hanging Punctuation 懸掛標點 + Inseparable Characters 不可分割字元 Push In First 先推入 Push Out First 先推出 Push Out Only 只推出 @@ -3581,6 +3684,7 @@ liquify-list-end {0}, {1} {0}和{1} Pressure 壓力 Tilt 傾斜 Bearing 方位 + Stylus Wheel 光筆滾輪 Shape: 形狀: Bristle Length: 鬃毛長度: Bristle Density: 鬃毛密度: @@ -3611,6 +3715,9 @@ liquify-list-end {0}, {1} {0}和{1} embedding for preview and print 允許內嵌以供預覽和列印 embedding allowed 允許內嵌 {file}; {embedding} {file};{embedding} + unknown type 未知類型 + {type}; {uses} {type};{uses} +@plural {n} use|{n} uses 使用 {n} 次 substituted: shown in {family} {style} ({detail}) 已替代:以 {family} {style} 顯示 ({detail}) missing: shown in {family} {style} 遺失:以 {family} {style} 顯示 missing 遺失 @@ -3884,6 +3991,8 @@ liquify-list-end {0}, {1} {0}和{1} Overprint and Transparency Flattener Options 疊印與透明度平面化選項 Custom… 自訂… Custom Transparency Flattener Options 自訂透明度平面化選項 + The PDF preset keeps the flattener preset but not the Custom… settings. PDF 預設集會保留平面化預設集,但不保留「自訂…」設定。 + PDF 1.3 files clip rasterized areas to their regions, and Overprint sets whether overprints are kept. PDF 1.3 檔案會將點陣化區域剪裁至其區域,「疊印」決定是否保留疊印。 EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS 沒有 Alpha 透明度,「疊印」決定是否保留疊印。 Overprint Black… 疊印黑色… Overprint Fill 疊印填色 @@ -4408,6 +4517,9 @@ digits Malayalam 馬來亞拉姆數字 Rotate View to Selection 依選取範圍旋轉檢視 Reset the rows to the artwork's colors 將各列重設為圖稿的顏色 Color Theme Picker 色彩主題選取器 + Undo Changes 復原變更 + Redo Changes 重做變更 +@msg Recolor Artwork is not open 「重新上色圖稿」未開啟 Click or drag across the art to pick its colors; Shift adds more 按一下或拖過圖稿以選取其顏色;按住 Shift 可加入更多 Prominent Colors 主要顏色 Save All Colors 儲存所有顏色 @@ -4462,6 +4574,7 @@ digits Malayalam 馬來亞拉姆數字 A live rectangle's properties show one Corner Radius field for all four corners; off, each corner has its own field. 即時矩形的屬性中為四個角顯示一個圓角半徑欄位;關閉時,每個角都有自己的欄位。 What edits in the Transform panel transform: the object, its pattern tiles or both; Default follows Transform Pattern Tiles. 變形面板中的編輯所變形的內容:物件、其圖樣拼貼或兩者;預設依照變形圖樣拼貼。 With one symbol instance selected, the Transform panel uses the symbol's registration point as its reference point. 選取一個符號實體時,變形面板使用符號的註冊點作為參考點。 + Drawing a rectangle, ellipse, polygon, star or line opens the Transform panel if it is closed. 繪製矩形、橢圓形、多邊形、星形或直線時,如果變形面板已關閉,就會開啟它。 Darkens the canvas outside the artboards while the Artboard tool is active. 使用工作區域工具時調暗工作區域以外的畫布。 With Fade Region Outside Artboard on, the area outside the artboards stays dark while you drag with the Artboard tool. 調暗工作區域外的區域開啟時,用工作區域工具拖曳期間工作區域以外的區域保持變暗。 How near, in pixels, the pointer must be to an object, anchor or handle for a click to select it. 按一下時,指標需距離物件、錨點或控制把手多少像素以內才能選取它。 @@ -4642,6 +4755,7 @@ digits Malayalam 馬來亞拉姆數字 Save Document Preset 儲存文件預設集 Preset {number} 預設集 {number} Save Preset… 儲存預設集… + Save Summary… 儲存摘要… Save Print Preset 儲存列印預設集 Save Recovery Data 儲存救援資料 Save Save for Web Preset 儲存「儲存為網頁用」預設集 @@ -4948,6 +5062,7 @@ digits Malayalam 馬來亞拉姆數字 Show Modified 顯示已修改 Show Note 顯示註解 Show Options 顯示選項 + Show on Shape Creation 建立形狀時顯示 Show Recent Colors 顯示最近使用的顏色 Toggle RGB Percent 切換 RGB 百分比顯示 Show Original Path 顯示原始路徑 @@ -4975,6 +5090,7 @@ digits Malayalam 馬來亞拉姆數字 Show Thumbnails 顯示縮圖 Show Tile Edge 顯示拼貼邊緣 Show Tints/Shades 顯示淺色調/深色調 + Show Tool Cards 顯示工具卡片 Show Tool Tips 顯示工具提示 Show Transparency Grid 顯示透明度格點 Show Video Rulers 顯示視訊尺標 @@ -5060,6 +5176,8 @@ digits Malayalam 馬來亞拉姆數字 Outlines 外框 Outlines with Source Image 外框(含來源影像) Source Image 來源影像 + Split View 分割檢視 + Divider 分隔線 Press and hold to view the source image 按住以檢視來源影像 Image Trace View 影像描圖檢視 Snap Options 靠齊選項 @@ -5517,6 +5635,8 @@ digits Malayalam 馬來亞拉姆數字 Unembed… 取消嵌入… Ungroup 解散群組 Ungroup Color Group 解散顏色群組 + Color Group Options 顏色群組選項 + Color Group Options… 顏色群組選項… Unicode Unicode Unicode (UTF-16) Unicode (UTF-16) Unicode (UTF-8) Unicode (UTF-8) @@ -6019,6 +6139,25 @@ axis Both 兩者 Preserve Embedded Profiles 保留內嵌描述檔 Convert to Working Space 轉換為工作空間 Preserve Numbers 保留數值 + Profile Mismatches: 描述檔不符: + Ask When Opening 開啟時詢問 + Ask When Pasting 貼上時詢問 + Missing Profiles: 遺失的描述檔: + Embedded Profile Mismatch 內嵌描述檔不符 + Missing Profile 遺失描述檔 + Paste Profile Mismatch 貼上時描述檔不符 + “{name}” is not tagged with a {model} profile. 「{name}」沒有 {model} 描述檔。 + “{name}” is tagged with the {model} profile “{profile}”, which is not the {model} working space “{working}”. 「{name}」的 {model} 描述檔為「{profile}」,不是 {model} 工作空間「{working}」。 + Use the embedded profile 使用內嵌描述檔 + Convert the colors to the working space 將色彩轉換為工作空間 + Discard the embedded profile 捨棄內嵌描述檔 + Leave as is 保持原狀 + Assign the working space 指定工作空間 + Assign profile: 指定描述檔: + Preserve the color numbers 保留色彩數值 + Convert to keep the colors' appearance 轉換以保持色彩外觀 +@msg `{path}` goes with `{key}`: "assign" only `{path}` 只能與 `{key}`: "assign" 一起提供 + The pasted colors come from a document whose {model} profile is “{from}”; this document's is “{to}”. 貼上的色彩來自 {model} 描述檔為「{from}」的文件;此文件的描述檔為「{to}」。 Texture 紋理 Craquelure… 龜裂紋… Grain… 顆粒… @@ -7792,6 +7931,8 @@ breakText Glyphs 字符 # Path Precision Tools add-on: Tangent Circle. Tangent Circle… 相切圓… Tangent Circle 相切圓 + Tangent Circle Tool 相切圓工具 + No tangent circle here 此處沒有相切圓 Circle: 圓: @msg `ids` names an object twice `ids` 將同一個物件指定了兩次 @msg select two or three paths or compound paths 請選取兩個或三個路徑或複合路徑 @@ -7807,6 +7948,16 @@ breakText Glyphs 字符 @msg `circle` is past the last circle found ({found}) `circle` 超出了找到的最後一個圓({found}) @msg object {value} is not a path or compound path 物件 {value} 不是路徑或複合路徑 @msg these shapes are too small to measure 這些形狀太小,無法測量 +# Path Precision Tools add-on: Add Bounding Rectangle and Add Bounding Circle. + Add Bounding Rectangle 新增外接矩形 + Add Bounding Circle 新增外接圓形 + Add Bounding Rectangle… 新增外接矩形… + Add Bounding Circle… 新增外接圓形… + One per Object 每個物件一個 +@msg nothing to enclose 沒有可包圍的內容 +@msg `offset` must be 0 or more `offset` 必須大於或等於 0 +@msg the shape would have no size 形狀將沒有大小 +@msg the shape would reach past the edge of the canvas 形狀會超出畫布邊緣 # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools 文件工具 Save a Timestamped Copy 儲存附時間戳記的拷貝 @@ -10101,6 +10252,50 @@ breakText Glyphs 字符 @msg A joint does not close by {gap} pt. 有一處接縫相差 {gap} pt 未閉合。 @msg Two panels pass through each other. 兩個面板相互穿插。 @msg {what} would print on more than {MAX_TILES} tiles: scale it down {what} 會列印在超過 {MAX_TILES} 個拼貼上:請縮小 + Fine Stipple 細密點描 + Dense Stipple 濃密點描 + Soft Stipple 柔和點描 + Bold Stipple 粗重點描 + Paper Cutouts 剪紙 + Coral Layers 珊瑚色圖層 + Mint Layers 薄荷色圖層 + Midnight Layers 午夜色圖層 + Sunflower Sheet 向日葵紙片 + Rose Layers 玫瑰色圖層 + Monochrome Stack 單色疊層 +# Tool cards (General › Show Tool Cards): one sentence on what each tool does. + Shows a card with what a toolbar tool does and what its keys do instead of its tip; it needs Show Tool Tips. 以卡片取代提示,顯示工具列工具及其按鍵的作用;需要開啟顯示工具提示。 + Selects whole objects and groups to move, resize or rotate them. 選取整個物件和群組,以移動、縮放或旋轉它們。 + Selects anchor points and path segments to reshape a path. 選取錨點和路徑區段,以改變路徑的形狀。 + Draws paths point by point, with straight segments and smooth curves. 逐點繪製路徑,包括直線區段和平滑曲線。 + Draws smooth curves through the points you click. 繪製通過所按各點的平滑曲線。 + Adds text at a point, or in a frame you drag. 在某一點或拖曳出的框架中加入文字。 + Draws rectangles and squares. 繪製矩形和正方形。 + Draws rectangles with rounded corners. 繪製圓角矩形。 + Draws ellipses and circles. 繪製橢圓形和圓形。 + Draws polygons with sides of equal length. 繪製各邊等長的多邊形。 + Draws stars. 繪製星形。 + Turns objects around a reference point. 繞著參考點旋轉物件。 + Flips objects across an axis through a reference point. 沿通過參考點的軸鏡射物件。 + Resizes objects from a reference point. 從參考點縮放物件。 + Slants objects from a reference point. 從參考點傾斜物件。 + Moves the view of the document. 移動文件的檢視。 + Magnifies or reduces the view. 放大或縮小檢視。 + Copies the color and other attributes of one object to the selection. 將一個物件的顏色和其他屬性複製到選取的物件。 + Sets the direction and length of a gradient. 設定漸層的方向和長度。 + Creates, selects and resizes artboards. 建立、選取工作區域並調整其大小。 + Changes the width of a stroke along its length. 沿筆畫的長度改變其寬度。 + Bends art by dragging pins placed on it. 拖曳放在圖稿上的圖釘來彎曲圖稿。 + Pushes the outlines of paths in the direction you drag. 沿拖曳方向推動路徑的輪廓。 + Twists the outlines of paths into swirls. 將路徑的輪廓扭轉成漩渦。 + Pulls the outlines of paths in toward the brush. 將路徑的輪廓向筆刷收縮。 + Pushes the outlines of paths out from the brush. 將路徑的輪廓從筆刷向外膨脹。 + Adds curved details along the outlines of paths. 沿路徑的輪廓加入弧形細節。 + Adds spiky details along the outlines of paths. 沿路徑的輪廓加入尖刺細節。 + Adds wrinkles along the outlines of paths. 沿路徑的輪廓加入皺褶。 + Moves, copies and resizes objects on the perspective grid. 在透視格點上移動、複製和縮放物件。 + Makes a series of steps between two or more objects. 在兩個或多個物件之間產生一系列步驟。 + Places dimension lines that show measured lengths. 放置顯示測量長度的尺寸線。 Tap 短按 Clear Hold 清除按住 Hold Shortcuts 按住快速鍵 @@ -10117,3 +10312,7 @@ breakText Glyphs 字符 Pulse Stroke 脈動筆觸 Round Flow 圓頭流線 Chisel Flow 斜頭流線 + +# #5804 native-picked raster editor (draft translations; native review welcome). + Edit Original with: 編輯原稿所用應用程式: +file-filter Applications 應用程式 diff --git a/crates/ui-egui/src/icon_data.rs b/crates/ui-egui/src/icon_data.rs index bc0cfe3510..61a2e87a37 100644 --- a/crates/ui-egui/src/icon_data.rs +++ b/crates/ui-egui/src/icon_data.rs @@ -64,6 +64,7 @@ pub static ICONS: &[(&str, &[u8])] = &[ ("dc-contour", include_bytes!("../../../assets/icons/dc-contour.svg")), ("dc-crystallize", include_bytes!("../../../assets/icons/dc-crystallize.svg")), ("dc-cube", include_bytes!("../../../assets/icons/dc-cube.svg")), + ("dc-curvature-circle", include_bytes!("../../../assets/icons/dc-curvature-circle.svg")), ("dc-dash-align", include_bytes!("../../../assets/icons/dc-dash-align.svg")), ("dc-dash-exact", include_bytes!("../../../assets/icons/dc-dash-exact.svg")), ("dc-dimension", include_bytes!("../../../assets/icons/dc-dimension.svg")), diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs index c4a67fdef6..eb4aac540e 100644 --- a/crates/ui-egui/src/icons.rs +++ b/crates/ui-egui/src/icons.rs @@ -45,6 +45,7 @@ pub fn tool_icon(name: &str) -> &'static str { "tool-rounded-rect" => "dc-rounded-rect", "tool-ellipse" => "dc-ellipse", "tool-circle" => "dc-circle-points", + "tool-curvature-circle" => "dc-curvature-circle", "tool-polygon" => "dc-polygon", "tool-star" => "star", "tool-flare" => "dc-flare", diff --git a/crates/ui-egui/src/io.rs b/crates/ui-egui/src/io.rs index fb8d655feb..73dd82dd02 100644 --- a/crates/ui-egui/src/io.rs +++ b/crates/ui-egui/src/io.rs @@ -26,6 +26,7 @@ pub(crate) use export::{ EXPORT_SELECTION, export_files, exported_with_notes, file_url, open_in_app, open_original, reveal_path, run_to_file, save_command_output_named, selection_path, take_selection, }; +pub(crate) use open::asks_first; pub(crate) use open::report_installed; pub(crate) use open::{EXPORT_PRESETS, import_presets, open_notes, open_with_on, opened, opened_after_notice, show_opened}; pub use open::{ diff --git a/crates/ui-egui/src/io/export.rs b/crates/ui-egui/src/io/export.rs index 02f01e227d..bacfd0f554 100644 --- a/crates/ui-egui/src/io/export.rs +++ b/crates/ui-egui/src/io/export.rs @@ -341,11 +341,14 @@ pub(crate) fn open_in_app(app: &mut VectorcraftApp, path: &str) -> Result<(), St } /// Edit Original: open `path` in the system's default app for it, or with Preferences › File -/// Handling › Use System Defaults for Edit Original off, in the app that made it (#5236): PhotoCraft -/// for a raster image where it is installed. Any other file, or no PhotoCraft, uses the system's app. +/// Handling › Use System Defaults for Edit Original off, in a native-picked raster editor (#5804), +/// then PhotoCraft where installed (#5236). Other files, or no installed editor, use the system's app. pub(crate) fn open_original(app: &mut VectorcraftApp, path: &str) -> Result<(), String> { let ext = std::path::Path::new(path).extension().map(|e| e.to_string_lossy().into_owned()).unwrap_or_default(); let raster = vectorcraft_engine::cmd::fileio::readable_format(&ext).is_some_and(|f| f.raster); + if !app.session.prefs.edit_original_system_defaults && raster && crate::original_editor::try_open(app, path)? { + return Ok(()); + } if !app.session.prefs.edit_original_system_defaults && raster && let Some(open) = app.services.open_in_photocraft.as_mut() diff --git a/crates/ui-egui/src/io/open.rs b/crates/ui-egui/src/io/open.rs index 11c02ca139..b0a037804f 100644 --- a/crates/ui-egui/src/io/open.rs +++ b/crates/ui-egui/src/io/open.rs @@ -131,11 +131,19 @@ pub fn opens_as(name: &str) -> Option { } /// Open a document through the engine loader with the `document.open` options in `p` → -/// `document.open`'s result. +/// `document.open`'s result, or `{dialog}` when Edit › Color Settings asks about its profile first +/// ([`dialogs::profile_mismatch::open_or_ask`]): the document then opens, and goes on the recent +/// files, once the question is answered. pub fn open_document(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option, p: &Value) -> Result { - let r = fileio::open_bytes_with(&mut app.session, name, bytes, path, p).map_err(|e| e.to_string())?; - opened(app, &r); - Ok(r) + let update_links = app.session.prefs.update_links == "automatically"; + let low_res_proxy_eps = app.session.prefs.low_res_proxy_eps; + let file = fileio::read_for_open_asking(name, bytes, path.clone(), p, update_links, low_res_proxy_eps, true).map_err(|e| e.to_string())?; + dialogs::profile_mismatch::open_or_ask(app, file, path, false) +} + +/// Did an open answer that it asks a question first (`{dialog}`), so the file isn't open yet? +pub(crate) fn asks_first(r: &Value) -> bool { + r.get("dialog").is_some() } /// A document just opened (`r`: `document.open`'s result): the views follow, the status bar says @@ -402,9 +410,8 @@ pub(crate) fn open_with_on(app: &mut VectorcraftApp, p: &Value, background: bool Err(back) => bytes = back, } } - let r = open_document(app, &path, &bytes, Some(path.clone()), &o)?; - note_recent(app, &path); - Ok(r) + // The open notes it on the recent files, after any question it asks first. + open_document(app, &path, &bytes, Some(path.clone()), &o) }); if let Err(e) = &opened { report_open_error(app, &fileio::file_name(&path), e); @@ -570,7 +577,10 @@ fn open_file_with(app: &mut VectorcraftApp, path: &str, background: bool, p: &Va } } let r = open_bytes_with(app, path, &bytes, Some(path.to_string()), p)?; - note_recent(app, path); + // A document that asks a question first goes on the recent files once it opens. + if !asks_first(&r) { + note_recent(app, path); + } Ok(r) } diff --git a/crates/ui-egui/src/keymap.rs b/crates/ui-egui/src/keymap.rs index 79e53edfdd..54a551ad1c 100644 --- a/crates/ui-egui/src/keymap.rs +++ b/crates/ui-egui/src/keymap.rs @@ -21,6 +21,7 @@ pub const TOGGLES: &[&str] = &[ "view.edges", "view.template", "view.cornerWidget", + "view.shapeWidgets", "view.textThreads", "type.hiddenCharacters", "view.gradientAnnotator", diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 73337d1352..dd7bc40c4a 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -55,6 +55,9 @@ pub mod layout_migration; pub mod menus; pub mod native_menu; pub mod opening; +mod original_editor; +#[doc(hidden)] +pub use original_editor::Choice as OriginalEditorChoice; pub mod palette; mod panel_docking; pub mod panels; @@ -270,6 +273,7 @@ pub struct VectorcraftApp { system_paste_at: f64, /// File dialogs shown off the UI thread and what runs again with their answers. pub(crate) picks: picks::Picks, + pub(crate) original_editor: original_editor::Draft, /// The screen color sampler shown and not answered yet, and where its color goes. pub(crate) screen_sampler: Option, /// The look for fonts installed or removed meanwhile, running @@ -308,6 +312,13 @@ pub struct VectorcraftApp { /// This host iteration's input carries forwarded keys: they are the main window's although /// its OS window doesn't have the keyboard (see `shortcuts::handle`). pub(crate) forwarded_frame: bool, + /// The forwarded keys of this host iteration hold a Copy or Cut: it copies the art, not text + /// selected in this window's labels (see `shortcuts::handle_clipboard`). + pub(crate) forwarded_clipboard: bool, + /// The key presses among this host iteration's forwarded keys: a Copy or Cut one of them runs + /// (F3 and F2 off macOS) copies the art, not text selected in this window's labels (see + /// `shortcuts::clipboard_key_to_labels`). + pub(crate) forwarded_presses: Vec, /// Synthetic input set the modifiers egui holds (see [`Self::raw_input_hook`]). synthetic_modifiers: bool, /// The marked text the system IME last sent (`None` once it commits or clears). When the Type @@ -349,6 +360,12 @@ pub struct VectorcraftApp { /// The plug-in install the approval dialog asks about, kept out of the dialog's fields, which /// `ui.dialog.set` writes. pub(crate) pending_plugin_install: Option, + /// The file File › Open read that waits for the answer to its profile question + /// ([`dialogs::profile_mismatch`]), kept out of the dialog's fields. + pub(crate) pending_profile_open: Option, + /// Files File › Open read while another one's profile question was open, each asking its own + /// question in turn. + pub(crate) queued_profile_opens: std::collections::VecDeque, /// The paths Choose… picked in a script's file dialog, kept out of the dialog's fields, which /// `ui.dialog.set` writes. pub(crate) script_picked: Vec, diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index 42c6da3a10..830a8d3008 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -111,10 +111,24 @@ pub(super) fn field_event(app: &mut VectorcraftApp, id: &str) -> Option Some(("edit.copy", egui::Event::Copy)), + "edit.cut" => Some(("edit.cut", egui::Event::Cut)), + _ => None, + }; match focused_text_field(ctx).and_then(|f| Some((f, field_event(app, id)?))) { Some((field, e)) => to_field(ctx, field, e), + None if label_event.as_ref().is_some_and(|(id, _)| crate::shortcuts::leave_to_labels(app, ctx, id)) => { + if let Some((_, e)) = label_event { + ctx.input_mut(|i| i.events.push(e)); + } + // The labels' text replaces the formats of an earlier Copy or Cut not written yet, even + // in a frame whose keys are not this window's. + app.drop_unwritten_formats(); + } None if id == "select.all" && crate::panels::artboards::selects_all(app, ctx) => crate::panels::artboards::select_all(app), None => invoke(app, id, p), } @@ -302,6 +316,13 @@ fn open_view_dialog(app: &mut VectorcraftApp, id: &str, p: &Value) -> bool { } return true; } + // Kinsoku Shori Settings…: the document's custom Kinsoku sets, to edit before OK sets them. + if id == crate::dialogs::kinsoku_sets::COMMAND && p.as_object().is_none_or(|o| o.is_empty()) { + if let Err(e) = crate::dialogs::kinsoku_sets::open(app) { + app.status(e); + } + return true; + } // Edit Custom Dictionary…: the custom dictionary's words in a list, to add, delete or change. if id == crate::dialogs::custom_dictionary::COMMAND && p.as_object().is_none_or(|o| o.is_empty()) { if let Err(e) = crate::dialogs::custom_dictionary::open(app) { diff --git a/crates/ui-egui/src/menus/labels.rs b/crates/ui-egui/src/menus/labels.rs index 3fe80167bd..0f8c92ebb4 100644 --- a/crates/ui-egui/src/menus/labels.rs +++ b/crates/ui-egui/src/menus/labels.rs @@ -22,6 +22,7 @@ fn view_toggle_label(app: &VectorcraftApp, id: &str) -> Option { "view.edges" => if v.edges { "Hide Edges" } else { "Show Edges" }.into(), "view.template" => if v.templates { "Hide Template" } else { "Show Template" }.into(), "view.cornerWidget" => if v.corner_widgets { "Hide Corner Widget" } else { "Show Corner Widget" }.into(), + "view.shapeWidgets" => if v.shape_widgets { "Hide Shape Widgets" } else { "Show Shape Widgets" }.into(), "view.textThreads" => if v.text_threads { "Hide Text Threads" } else { "Show Text Threads" }.into(), "type.hiddenCharacters" => if v.hidden_chars { "Hide Hidden Characters" } else { "Show Hidden Characters" }.into(), "view.gradientAnnotator" => if v.gradient_annotator { "Hide Gradient Annotator" } else { "Show Gradient Annotator" }.into(), @@ -283,6 +284,8 @@ pub const DYNAMIC_LABELS: &[&str] = &[ "Show Edges", "Hide Corner Widget", "Show Corner Widget", + "Hide Shape Widgets", + "Show Shape Widgets", "Hide Text Threads", "Show Text Threads", "Hide Hidden Characters", diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 909d03b3d2..1d3cfef629 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -292,6 +292,12 @@ fn run_ui_part3(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option flag(&mut app.ui.view.pixel_preview), "view.trimView" => flag(&mut app.ui.view.trim_view), "view.cornerWidget" => flag(&mut app.ui.view.corner_widgets), + // Hide/Show Shape Widgets: `on` sets the state, and without it the state flips. + "view.shapeWidgets" => opt_bool(p, "on").map(|on| { + let v = &mut app.ui.view.shape_widgets; + *v = on.unwrap_or(!*v); + json!(*v) + }), // New View: the engine stores the current zoom, centre and rotation under the given name. "view.saved.new" if p.get("zoom").is_none() => { let Some(v) = app.view().copied() else { return Some(Err("no document".into())) }; @@ -788,6 +794,7 @@ fn run_ui_part7(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option crate::dialogs::color_group_options::open(app, p), "ui.colorPicker" => crate::dialogs::open_color_picker(app, p), "ui.sampleScreenColor" => crate::screen_color::start(app, p), "ui.graphicStyleOptions" => crate::dialogs::graphic_style_options::open(app, s("name").as_deref()), @@ -951,6 +958,8 @@ fn run_ui_part10(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option crate::dialogs::simplify_slider::auto(app), "ui.simplifyMoreOptions" => crate::dialogs::simplify_slider::more_options(app), "ui.smoothAuto" => crate::dialogs::smooth_slider::auto(app), + "ui.recolorUndo" => crate::dialogs::recolor::step(app, true), + "ui.recolorRedo" => crate::dialogs::recolor::step(app, false), "ui.dialogReset" => crate::dialogs::reset(app), "attributes.openUrl" => crate::panels::attributes::open_url(app, p), "ui.javascriptFilesDialog" => crate::panels::svg_interactivity::files_dialog(app, p), @@ -983,6 +992,7 @@ fn run_ui_part10(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option crate::panels::color::rgb_percent_command(app, p), "ui.colorWheel" => crate::panels::color_wheel::command(app, p), "ui.savePdfDialog" => crate::dialogs::open_save_pdf(app, p), + crate::dialogs::SAVE_PDF_SUMMARY => crate::dialogs::save_pdf_summary(app, p), "file.exportAs" if s("path").is_none() => { crate::dialogs::open_export_as(app, s("format").as_deref(), p); Ok(Value::Null) @@ -1070,6 +1080,11 @@ fn run_ui_part12(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option Err("no document".into()), + "ui.hpglOptionsDialog" => { + crate::dialogs::hpgl_options::open(app, p); + Ok(Value::Null) + } // Save for Web: its dialog; with settings, write the files. "file.saveForWeb" if p.as_object().is_none_or(|o| o.is_empty()) => crate::dialogs::save_for_web::open(app), "file.saveForWeb" => crate::dialogs::save_for_web::save(app, p.clone()), diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index a424d98714..ee11fb2153 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -148,9 +148,9 @@ fn swapped_out(app: &VectorcraftApp, id: &str) -> bool { } /// Menu items shown only with Preferences › Type › Show East Asian Options on: Type › Composite -/// Fonts…. +/// Fonts… and Type › Kinsoku Shori Settings…. fn east_asian_hidden(app: &VectorcraftApp, id: &str) -> bool { - id == crate::dialogs::composite_fonts::COMMAND && !app.session.prefs.show_east_asian_options + [crate::dialogs::composite_fonts::COMMAND, crate::dialogs::kinsoku_sets::COMMAND].contains(&id) && !app.session.prefs.show_east_asian_options } /// How the menus show item `id` (params `p`) now: (enabled, checked: `Some` for an item that is on @@ -275,12 +275,13 @@ pub fn enabled(app: &VectorcraftApp, id: &str) -> bool { "file.export.pdf" | "ui.savePdfDialog" | "ui.fileInfoDialog" | "ui.rasterEffectsSettingsDialog" | "ui.svgFilterDialog" => { app.session.active().is_some() } + crate::dialogs::SAVE_PDF_SUMMARY => crate::dialogs::pdf_summary_open(app), "ui.importSvgFilter" => { app.session.active().is_some() && crate::picks::can(app, &crate::picks::PickRequest::Open(crate::dialogs::svg_filter::pick())) } "ui.missingFontsDialog" => !cfg!(target_arch = "wasm32") && app.session.active().is_some(), "ui.findFontsInFolder" => crate::picks::can(app, &crate::picks::PickRequest::Folder) && app.session.active().is_some(), - "ui.swatchOptions" | "ui.newSwatch" | "ui.newColorGroup" => app.session.active().is_some(), + "ui.swatchOptions" | "ui.newSwatch" | "ui.newColorGroup" | "ui.colorGroupOptions" => app.session.active().is_some(), "ui.graphicStyleOptions" | "ui.charStyleOptions" | "ui.paraStyleOptions" | "ui.newCharStyle" | "ui.newParaStyle" => { app.session.active().is_some() } @@ -319,6 +320,8 @@ pub fn enabled(app: &VectorcraftApp, id: &str) -> bool { "ui.menuDialog" => app.session.active().is_some_and(|d| !d.selection.is_empty()), "ui.simplifyAuto" | "ui.simplifyMoreOptions" => crate::dialogs::simplify_slider::showing(app), "ui.smoothAuto" => crate::dialogs::smooth_slider::showing(app), + "ui.recolorUndo" => crate::dialogs::recolor::can_step(app, true), + "ui.recolorRedo" => crate::dialogs::recolor::can_step(app, false), "ui.dialogReset" => crate::dialogs::can_reset(app), "ui.dxfOptionsDialog" => app.session.active().is_some(), "links.editOriginal" | "links.reveal" => selected_image(app, |im| im.link.is_some()) || selected_placed(app), @@ -328,7 +331,7 @@ pub fn enabled(app: &VectorcraftApp, id: &str) -> bool { "ui.findLinksInFolder" => crate::picks::can(app, &crate::picks::PickRequest::Folder) && app.session.active().is_some(), "ui.packageDialog" | "docInfo.save" => app.session.active().is_some(), "ui.batchDialog" => !app.ui.action_sets.is_empty() && app.ui.action_sets.iter().any(|s| !s.actions.is_empty()), - "ui.epsOptionsDialog" => app.session.active().is_some(), + "ui.epsOptionsDialog" | "ui.hpglOptionsDialog" => app.session.active().is_some(), "file.saveForWeb" | "file.saveForWeb.browser" | "file.export.svg.browser" => app.session.active().is_some(), "file.exportSelection" => app.session.active().is_some_and(|d| !d.selection.is_empty()), "css.copy" | "css.exportFile" => app.session.active().is_some(), diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index 4cc93d02ca..4b441eb594 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -1210,6 +1210,32 @@ fn recent_fonts_and_corner_widget_toggle() { assert_eq!(dynamic_label(&app, "view.cornerWidget", ""), "Show Corner Widget"); } +/// Hide Shape Widgets (`view.shapeWidgets`, the shape tools' Control bar button) flips its label and +/// the setting, `on` sets it, a non-boolean `on` is an error that leaves it, the setting is saved +/// with the interface state, and state saved before the setting existed loads with the widgets on. +#[test] +fn shape_widgets_command_toggles_and_takes_on() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + assert!(app.ui.view.shape_widgets, "on by default"); + assert_eq!(dynamic_label(&app, "view.shapeWidgets", ""), "Hide Shape Widgets"); + assert_eq!(app.run("view.shapeWidgets", json!({})).unwrap(), json!(false)); + assert_eq!(dynamic_label(&app, "view.shapeWidgets", ""), "Show Shape Widgets"); + assert!(!app.view_info().shape_widgets); + assert_eq!(app.run("view.shapeWidgets", json!({"on": false})).unwrap(), json!(false)); + assert!(app.run("view.shapeWidgets", json!({"on": "yes"})).is_err()); + assert!(!app.ui.view.shape_widgets, "a bad `on` changes nothing"); + assert_eq!(app.run("view.shapeWidgets", json!({"on": true})).unwrap(), json!(true)); + assert!(app.view_info().shape_widgets); + app.ui.view.shape_widgets = false; + let mut saved = serde_json::to_value(&app.ui).unwrap(); + let loaded: crate::UiState = serde_json::from_value(saved.clone()).unwrap(); + assert!(!loaded.view.shape_widgets, "the setting is saved"); + saved["view"].as_object_mut().unwrap().remove("shape_widgets"); + let older: crate::UiState = serde_json::from_value(saved).unwrap(); + assert!(older.view.shape_widgets, "older saved state shows the widgets"); + assert!(UI_COMMANDS.iter().any(|c| c.0 == "view.shapeWidgets" && c.2.is_empty()), "no default key"); +} + /// View › Precise Cursors has no menu item or default key, but the command (assignable in Keyboard Shortcuts) /// writes General › Use Precise Cursors, the value the dialog and the saved preferences read. #[test] diff --git a/crates/ui-egui/src/menus/tree.rs b/crates/ui-egui/src/menus/tree.rs index b601528df3..12549232bf 100644 --- a/crates/ui-egui/src/menus/tree.rs +++ b/crates/ui-egui/src/menus/tree.rs @@ -457,6 +457,7 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec)> { Sep, c("Find Font…", "type.findFont"), c("Composite Fonts…", crate::dialogs::composite_fonts::COMMAND), + c("Kinsoku Shori Settings…", crate::dialogs::kinsoku_sets::COMMAND), sub( "Change Case", vec![ diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index fbfd12b24e..8f1caeb15f 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -224,6 +224,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ ("view.pixelPreview", "Pixel Preview", "Cmd+Alt+Y", "{}"), ("view.trimView", "Trim View", "", "{} toggle: hide everything outside the artboards"), ("view.cornerWidget", "Hide Corner Widget", "", "{} toggle the live corner widgets"), + ( + "view.shapeWidgets", + "Hide Shape Widgets", + "", + "{on?: bool} hide or show selected live shapes' corner, pie and side widgets for the Selection tool and the shape tools (the shape tools' Control bar button); without `on` it toggles; returns the new state. Direct Selection's corner widgets follow view.cornerWidget alone", + ), ( "view.snapToPixel", "Snap to Pixel", @@ -925,6 +931,18 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{colors?: n (an n-colour job: n rows, Scale Tints) | [colour] (new colours to assign, in order; with no art selected and no group they are the rows, and OK saves them as a new colour group, field `groupName`: the Color Guide's Edit or Apply Colors), library?: id or name; or \"document\" (Limit to Library; \"\" the first library), group?: colour group (Edit or Apply Color Group: OK rewrites the group with the new colours and recolours the selected art, if any)} open Recolor Artwork (dialog `recolor`; engine: recolor.reduce / recolor.apply)", ), + ( + "ui.recolorUndo", + "Undo Changes", + "", + "{} the open Recolor Artwork dialog goes back one of its own color edits (rows, Colors, Method, the Preserve options, Limit to Library, the harmony rule, Global Adjust, the Color Theme Picker's picks, the Prominent Colors weights): its fields and the preview return to their values before that edit; the document's undo history is unchanged, and OK still records one undo step → {changed, canUndo, canRedo}; an error when the dialog isn't open. Each opening starts with nothing to undo, and selecting another color group or Save Changes leaves nothing to undo or redo", + ), + ( + "ui.recolorRedo", + "Redo Changes", + "", + "{} the open Recolor Artwork dialog restores the color edit ui.recolorUndo went back from last; a new edit after ui.recolorUndo leaves nothing to redo → {changed, canUndo, canRedo}; an error when the dialog isn't open", + ), ( "ui.cropImage", "Crop Image", @@ -997,6 +1015,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{swatches?: [names]} open New Color Group, from those swatches or the selected artwork (dialog `newColorGroup`, engine: swatch.newGroup)", ), + ( + "ui.colorGroupOptions", + "Color Group Options…", + "", + "{group?} open Color Group Options for that color group, or without group for the color group selected alone in the Swatches panel (dialog `colorGroupOptions`, field `name`): OK renames the group (engine: swatch.renameGroup); a name that is empty or that another color group or a swatch has keeps the dialog open; when another document is active, or the color group at the group's place in the list no longer has the name and swatches it opened with, OK closes the dialog and renames nothing", + ), ( "ui.colorPicker", "Color Picker…", @@ -1079,7 +1103,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "tool.options", "Tool Options…", "", - "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool, diameter (pt), intensity and density (1–10), shared by the eight tools; OK runs tool.setOption {tool, values}), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", + "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", ), ( "ui.colorGuideOptions", @@ -1161,19 +1185,19 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.layerDelete", "Delete Selection", "", - "{ids?|id?, doc?, confirmed?: bool} Delete Selection as the Layers panel runs it (its trash button, rows dropped on the trash, its menu, Delete and Backspace), on the rows layer.delete takes (default: the highlighted rows, else the current layer). When a layer or sublayer among them holds art (an object other than a guide; hidden, locked and nested objects count) it asks first: dialog `confirm` with `message`; OK deletes those rows by id with layer.delete (one undo step), Cancel keeps them. OK runs ui.layerDelete again with the rows, `doc` (the document's uid) and `confirmed: true`: with another document active then, nothing is deleted. Other rows (an empty layer, groups and objects alone) and rows layer.delete refuses go to layer.delete at once → layer.delete's {deleted}, or null while the question is open", + "{ids?|id?, doc?, confirmed?: bool} Delete Selection as the Layers panel runs it (its trash button, rows dropped on the trash, its menu, Delete and Backspace), on the rows layer.delete takes (default: the highlighted rows, else the current layer; in isolation mode, with no row highlighted, a current layer outside the isolated art is an error and nothing is deleted). When a layer or sublayer among them holds art (an object other than a guide; hidden, locked and nested objects count) it asks first: dialog `confirm` with `message`; OK deletes those rows by id with layer.delete (one undo step), Cancel keeps them. OK runs ui.layerDelete again with the rows, `doc` (the document's uid) and `confirmed: true`: with another document active then, nothing is deleted. In isolation mode a row outside the isolated art is an error and nothing is deleted. Other rows (an empty layer, groups and objects alone) and rows layer.delete refuses go to layer.delete at once → layer.delete's {deleted}, or null while the question is open", ), ( "ui.rename", "Rename", "", - "{id?} open the Layers panel's name field on the row of layer, group or object id, as double-clicking the row's name does (the panel is shown and the layers around the row open): Enter renames it with layer.setProps (one undo step), Escape keeps the name. Without id: the highlighted row when a Layers panel row was clicked last, else the one selected object or group, else the one highlighted row, else the current layer. Several rows or objects, or a row the panel's search, filter or Show Layers Only hides, is an error and nothing opens → {id, name}", + "{id?} open the Layers panel's name field on the row of layer, group or object id, as double-clicking the row's name does (the panel is shown and the layers around the row open): Enter renames it with layer.setProps (one undo step), Escape keeps the name. Without id: the highlighted row when a Layers panel row was clicked last, else the one selected object or group, else the one highlighted row, else the current layer. Several rows or objects, a row the panel's search, filter or Show Layers Only hides, or in isolation mode an object outside the isolated art, is an error and nothing opens → {id, name}", ), ( "ui.newLayer", "New Layer Options…", "Cmd+Alt+L", - "{sublayer?: bool} open Layer Options for a new layer (or a sublayer of the current layer), named and coloured as it would be: dialog `layerOptions` with mode new|newSublayer; OK runs layer.new or layer.newSublayer with the fields", + "{sublayer?: bool} open Layer Options for a new layer (or a sublayer of the current layer), named and coloured as it would be: dialog `layerOptions` with mode new|newSublayer; OK runs layer.new or layer.newSublayer with the fields. In isolation mode, a layer that would be outside the isolated art is an error and nothing opens; OK checks again, and with isolation mode started since, it returns the same error and makes no layer", ), ( "ui.newArtboard", @@ -1418,7 +1442,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.widthPointEdit", "Width Point Edit…", "", - "{id, index?: existing width point, t?: 0..1 for a new point, adjustAdjoining?: bool (false)} open Width Point Edit on path `id` (dialog `widthPoint`: side1, side2 (pt), linked, adjustAdjoining; double-clicking the stroke opens it too, Shift on a width point enabling adjoining adjustment): OK runs stroke.widthPoint.set; discard: true (Delete) removes an existing point or discards a prospective point", + "{id, index?: existing width point, indices?: [i…] several existing width points, t?: 0..1 for a new point (give only one of index, indices and t), adjustAdjoining?: bool (false)} open Width Point Edit on path `id` (dialog `widthPoint`: side1, side2 (pt), linked, adjustAdjoining; for several points also totalWidth, and side1, side2 and totalWidth are null where the points differ; double-clicking the stroke opens it too, on one of several Shift-selected width points for all of them, Shift on a width point enabling adjoining adjustment): OK runs stroke.widthPoint.set, for several points one stroke.widthProfile.set (none when nothing changed); discard: true (Delete) removes the existing points or discards a prospective point", ), ( "ui.corners", @@ -1496,13 +1520,19 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.colorWheel", "Color Wheel Options", "", - "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, vision?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, and pick the box's channel, as Box Channel does: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, vision}", + "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, vision?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, and pick the box's channel, as Box Channel does: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, harmony, harmonyRule, vision}", ), ( "ui.savePdfDialog", "Save PDF Dialog", "", - "{path?, preset?, range?, useArtboards?, …document.exportPdf options} open the Save PDF dialog with these options (fields = the options, sections are objects; OK writes path, else asks); useArtboards: false: one page of the visible art's bounds, with no Artboards section", + "{path?, preset?, range?, useArtboards?, …document.exportPdf options} open the Save PDF dialog with these options (fields = the options, sections are objects; Custom… sets `flattener`, which setting flattenerPreset drops; OK writes path, else asks); useArtboards: false: one page of the visible art's bounds, with no Artboards section", + ), + ( + "ui.pdfSummary.save", + "Save Summary…", + "", + "{path} write the Summary of the open Save PDF dialog (or PDF preset editor) to path as UTF-8 text without a byte order mark, with LF line endings, line for line as the Summary section shows it: Options and each option that differs from the preset (or the line saying none does), a blank line, then Warnings and each warning (or None.). The Summary the section last drew for the same fields, document, saved PDF and flattener presets, loaded color profiles and available fonts is used without computing the settings again. The web downloads the file under path's file name. The Summary section's Save Summary… button writes the same text to a file picked in a save panel that suggests ` PDF Summary.txt` in the document's folder. The dialog stays open and the document does not change. No such dialog open, a path that is missing, empty or not a string, a path outside the automation write roots and a failed document.pdfSettings are errors that write nothing; a failed write is an error → {path, bytes}", ), ( "file.exportAs", @@ -1808,6 +1838,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{path?, useArtboards?, range?, …document.exportEps options} open EPS Options (dialog `epsOptions`: fields = these options over the ones used last; Custom… sets `flattener`, which a flattenerPreset given without it drops); OK checks them, remembers them and writes path (else asks). Export As… → EPS opens it too", ), + ( + "ui.hpglOptionsDialog", + "HP-GL Options Dialog", + "", + "{path?, useArtboards?, range?, hpglVersion?, curveTolerance?, origin?, pens?, sortPaths?, insideFirst?} open HP-GL Options (dialog `hpglOptions`: fields = these document.export options over the ones used last; pens null is One Pen per Color); OK checks them, remembers them and writes path (else asks). Export As… → HP-GL opens it too", + ), ( "file.saveForWeb", "Save for Web (Legacy)…", diff --git a/crates/ui-egui/src/opening.rs b/crates/ui-egui/src/opening.rs index 99e0e9d6b6..5b4c8619ee 100644 --- a/crates/ui-egui/src/opening.rs +++ b/crates/ui-egui/src/opening.rs @@ -89,7 +89,9 @@ pub fn start_with(app: &mut VectorcraftApp, path: &str, bytes: Vec, params: .run(|| { vectorcraft_engine::guard::catch_panic(|| { cancel::scope(&raised, None, || { - fileio::read_for_open(&name, &file, Some(name.clone()), ¶ms, update_links, low_res_proxy_eps).map_err(|e| e.to_string()) + // A profile question Edit › Color Settings asks waits for the UI thread. + fileio::read_for_open_asking(&name, &file, Some(name.clone()), ¶ms, update_links, low_res_proxy_eps, true) + .map_err(|e| e.to_string()) }) }) }) @@ -111,6 +113,37 @@ pub fn start_with(app: &mut VectorcraftApp, path: &str, bytes: Vec, params: Ok(json!({ "background": true, "status": status })) } +/// Do the rest of the read of `file`, read for File › Open from `path` once its profile question +/// is answered or gone (its linked files and type, [`ReadFile::finish_read`]), on a thread of its +/// own under `scope`; it then opens as a file read off the UI thread does → `{background: true, +/// status}`, or the file back when no thread could start (the caller opens it at once). +pub(crate) fn finish_answered(app: &mut VectorcraftApp, path: &str, file: ReadFile, scope: ScopeHandle) -> Result>> { + let (tx, done) = channel(); + let slot = Arc::new(std::sync::Mutex::new(Some(file))); + let taken = slot.clone(); + let run = scope.clone(); + let spawned = std::thread::Builder::new().name("vectorcraft-open".into()).spawn(move || { + let Some(mut file) = taken.lock().ok().and_then(|mut f| f.take()) else { return }; + let r = run + .run(|| vectorcraft_engine::guard::catch_panic(|| file.finish_read().map_err(|e| e.to_string()))) + .unwrap_or_else(|msg| Err(format!("internal error: {msg} (please report this bug)"))); + let r = r.map(|()| file); + // The app may have quit meanwhile: nothing to hand it to. + let _ = tx.send(r); + }); + if spawned.is_err() { + return Err(slot.lock().ok().and_then(|mut f| f.take()).map(Box::new)); + } + let label = format!("Opening {}", fileio::file_name(path)); + app.opening.next_id += 1; + let id = app.opening.next_id; + let token = CancelToken::new(); + app.opening.pending.push(Pending { id, path: path.to_string(), label: label.clone(), done, scope, token, hidden: false }); + let status = format!("{label}…"); + app.status(status.clone()); + Ok(json!({ "background": true, "status": status })) +} + /// May the active document change now ([`poll`])? pub(crate) fn may_switch(app: &VectorcraftApp) -> bool { let s = &app.session; @@ -234,15 +267,13 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { } } -/// Open a file read off the UI thread, as [`crate::io::open_reporting`] opens one read at once. +/// Open a file read off the UI thread, as [`crate::io::open_reporting`] opens one read at once, +/// after the profile question Edit › Color Settings asks about it, if any +/// ([`crate::dialogs::profile_mismatch::open_or_ask`]). fn finish(app: &mut VectorcraftApp, path: &str, r: Result) { - let opened = r.and_then(|file| fileio::open_read(&mut app.session, file).map_err(|e| e.to_string())); - match opened { - Ok(r) => { - crate::io::opened(app, &r); - crate::io::note_recent(app, path); - } - Err(e) => crate::io::report_open_error(app, &fileio::file_name(path), &e), + let opened = r.and_then(|file| crate::dialogs::profile_mismatch::open_or_ask(app, file, Some(path.to_string()), true)); + if let Err(e) = opened { + crate::io::report_open_error(app, &fileio::file_name(path), &e); } } diff --git a/crates/ui-egui/src/original_editor.rs b/crates/ui-egui/src/original_editor.rs new file mode 100644 index 0000000000..ebdfcc4233 --- /dev/null +++ b/crates/ui-egui/src/original_editor.rs @@ -0,0 +1,296 @@ +//! The raster editor is selected by a person in a native picker, never by a preference command +//! or a generic dialog field. Keep both the saved choice and the dialog's draft opaque. + +use serde::{Deserialize, Serialize}; + +use crate::{FilePick, VectorcraftApp, state::Dialog}; + +/// Opaque saved choice. Public so hosts can construct `UiState` with a struct update; its path +/// has no public setter and is never read from the generic preference or dialog-field maps. +#[derive(Clone, Debug, Default, Serialize, Deserialize)] +pub struct Choice { + path: Option, +} + +#[derive(Default)] +pub(crate) struct Draft { + choice: Choice, + generation: u64, +} + +pub(crate) fn open(app: &mut VectorcraftApp) { + app.original_editor.generation = app.original_editor.generation.wrapping_add(1); + app.original_editor.choice = app.ui.original_editor.clone(); +} + +pub(crate) fn commit(app: &mut VectorcraftApp) { + app.ui.original_editor = app.original_editor.choice.clone(); +} + +pub(crate) fn reset(app: &mut VectorcraftApp) { + app.original_editor.choice = Choice::default(); + // Discard an outstanding pick when Reset was pressed while its dialog was open. + app.original_editor.generation = app.original_editor.generation.wrapping_add(1); +} + +pub(crate) fn cancel(app: &mut VectorcraftApp) { + open(app); +} + +/// A chosen app may have been removed since Preferences saved it. Only absence falls through; +/// validation and launch failures are errors, as they are for PhotoCraft. +pub(crate) fn try_open(app: &mut VectorcraftApp, path: &str) -> Result { + let Some(editor) = app.ui.original_editor.path.as_deref() else { return Ok(false) }; + let Some(open) = app.services.open_in_application.as_mut() else { return Ok(false) }; + open(editor, path) +} + +fn pick(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { + app.refuse_automation("preferences.chooseOriginalEditor")?; + let generation = app.original_editor.generation; + crate::picks::in_app_dialog(app, d, move |app, _| { + if generation != app.original_editor.generation { + return Ok(()); + } + let filters = if cfg!(target_os = "macos") { + vec![FilePick::filter("Applications", &["app"])] + } else if cfg!(windows) { + vec![FilePick::filter("Applications", &["exe"])] + } else { + Vec::new() + }; + let Some(path) = crate::picks::open(app, &FilePick { filters, ..Default::default() }) else { return Ok(()) }; + app.services.check_application.as_ref().ok_or("no application chooser here")?(&path)?; + app.original_editor.choice.path = Some(path); + Ok(()) + }) +} + +pub(crate) fn show(ui: &mut egui::Ui, app: &mut VectorcraftApp, d: &mut Dialog) { + if app.services.check_application.is_none() || app.services.open_in_application.is_none() { + return; + } + ui.add_enabled_ui(!d.bool("editOriginalSystemDefaults"), |ui| { + ui.horizontal_wrapped(|ui| { + ui.label(tl!("Edit Original with:")); + let name = app.original_editor.choice.path.as_deref().and_then(|p| std::path::Path::new(p).file_name()); + ui.label(name.map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "PhotoCraft".into())); + if ui.button(tl!("Choose…")).clicked() + && let Err(e) = pick(app, d) + { + app.status(e); + } + if app.original_editor.choice.path.is_some() && ui.button("PhotoCraft").clicked() { + reset(app); + } + }); + }); +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{ + Services, + control::{ControlRequest, Outcome}, + prefs_dialog, + }; + use serde_json::{Value, json}; + use std::{cell::RefCell, rc::Rc}; + + fn app() -> VectorcraftApp { + let services = Services { + check_application: Some(Box::new(|p| if p == "/Apps/Bad" { Err("not an application".into()) } else { Ok(()) })), + open_in_application: Some(Box::new(|_, _| Ok(true))), + ..Default::default() + }; + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), services); + prefs_dialog::open(&mut app, Some("File Handling")); + app + } + + fn choose(app: &mut VectorcraftApp, path: Option<&str>) -> Result<(), String> { + let path = path.map(str::to_owned); + app.services.pick_open = Some(Box::new(move |_| path.clone())); + let mut d = app.ui.dialog.take().unwrap(); + let r = pick(app, &mut d); + app.ui.dialog = Some(d); + r + } + + fn request(app: &mut VectorcraftApp, method: &str, params: Value) -> Value { + let (req, _) = ControlRequest::new(method, params); + let Outcome::Done(r) = crate::control::handle(app, &egui::Context::default(), &req) else { panic!("deferred") }; + r + } + + #[test] + fn native_choice_commits_persists_cancels_and_resets() { + let mut app = app(); + choose(&mut app, Some("/Apps/My Editor.app")).unwrap(); + assert!(app.ui.original_editor.path.is_none(), "a draft until OK"); + prefs_dialog::confirm(&mut app).unwrap(); + let saved = serde_json::to_vec(&app.ui).unwrap(); + let restored: crate::UiState = serde_json::from_slice(&saved).unwrap(); + assert_eq!(restored.original_editor.path.as_deref(), Some("/Apps/My Editor.app")); + assert!(app.session.prefs.to_json().get("original_editor").is_none()); + assert!(app.take_prefs_changed(), "OK asks the host to persist the choice"); + prefs_dialog::open(&mut app, Some("File Handling")); + choose(&mut app, None).unwrap(); + assert_eq!(app.original_editor.choice.path, restored.original_editor.path); + choose(&mut app, Some("/Apps/Other Editor.app")).unwrap(); + crate::dialogs::cancel(&mut app); + prefs_dialog::open(&mut app, Some("File Handling")); + assert_eq!(app.original_editor.choice.path, restored.original_editor.path); + assert!(choose(&mut app, Some("/Apps/Bad")).is_err()); + assert_eq!(app.original_editor.choice.path, restored.original_editor.path); + reset(&mut app); + prefs_dialog::confirm(&mut app).unwrap(); + assert!(app.ui.original_editor.path.is_none()); + let legacy: crate::UiState = serde_json::from_str("{}").unwrap(); + assert!(legacy.original_editor.path.is_none()); + } + + #[test] + fn original_editor_reset_confirmation_preserves_cancel_and_defers_persistence() { + let mut app = app(); + choose(&mut app, Some("/Apps/My Editor.app")).unwrap(); + prefs_dialog::confirm(&mut app).unwrap(); + prefs_dialog::open(&mut app, Some("File Handling")); + crate::dialogs::confirm::ask_reset_prefs(&mut app); + crate::dialogs::cancel(&mut app); + assert_eq!(app.original_editor.choice.path.as_deref(), Some("/Apps/My Editor.app")); + crate::dialogs::confirm::ask_reset_prefs(&mut app); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.original_editor.choice.path.is_none()); + assert_eq!(app.ui.original_editor.path.as_deref(), Some("/Apps/My Editor.app")); + crate::dialogs::cancel(&mut app); + prefs_dialog::open(&mut app, Some("File Handling")); + assert_eq!(app.original_editor.choice.path.as_deref(), Some("/Apps/My Editor.app")); + crate::dialogs::confirm::ask_reset_prefs(&mut app); + crate::dialogs::confirm(&mut app).unwrap(); + prefs_dialog::confirm(&mut app).unwrap(); + assert!(app.ui.original_editor.path.is_none()); + } + + #[test] + fn original_editor_routing_and_errors() { + let mut app = app(); + choose(&mut app, Some("/Apps/My Editor.app")).unwrap(); + prefs_dialog::confirm(&mut app).unwrap(); + let calls = Rc::new(RefCell::new(Vec::new())); + let c = calls.clone(); + app.services.open_file = Some(Box::new(move |_| { + c.borrow_mut().push("system"); + Ok(()) + })); + let c = calls.clone(); + app.services.open_in_photocraft = Some(Box::new(move |_| { + c.borrow_mut().push("photocraft"); + Ok(true) + })); + let c = calls.clone(); + app.services.open_in_application = Some(Box::new(move |editor, path| { + assert_eq!(editor, "/Apps/My Editor.app"); + assert_eq!(path, "/Art/a b.png"); + c.borrow_mut().push("chosen"); + Ok(true) + })); + crate::io::open_original(&mut app, "/Art/a b.png").unwrap(); + app.session.prefs.edit_original_system_defaults = false; + crate::io::open_original(&mut app, "/Art/a b.png").unwrap(); + crate::io::open_original(&mut app, "/Art/plan.emf").unwrap(); + app.services.open_in_application = Some(Box::new(|_, _| Ok(false))); + crate::io::open_original(&mut app, "/Art/a b.png").unwrap(); + app.services.open_in_photocraft = Some(Box::new(|_| Ok(false))); + crate::io::open_original(&mut app, "/Art/a b.png").unwrap(); + app.services.open_in_application = Some(Box::new(|_, _| Err("launch failed".into()))); + assert_eq!(crate::io::open_original(&mut app, "/Art/a b.png").unwrap_err(), "launch failed"); + assert_eq!(*calls.borrow(), ["system", "chosen", "system", "photocraft", "system"]); + } + + #[test] + fn automation_cannot_inject_an_original_editor() { + let mut app = app(); + for key in ["editOriginalApp", "original_editor", "__originalEditor", "__chosenApp"] { + let r = request(&mut app, "engine.execute", json!({"command": "prefs.set", "params": {"key": key, "value": "/Apps/Bad"}})); + assert_eq!(r["ok"], false, "{r}"); + let r = request(&mut app, "engine.execute", json!({"command": "prefs.set", "params": {"values": {key: "/Apps/Bad"}}})); + assert_eq!(r["ok"], false, "{r}"); + // __ fields are accepted by generic dialogs, but they cannot become a trusted choice. + let _ = request(&mut app, "ui.dialog.set", json!({"field": key, "value": "/Apps/Bad"})); + } + let r = request(&mut app, "engine.execute", json!({"command": "prefs.setValues", "params": {"values": {"editOriginalApp": "/Apps/Bad"}}})); + assert_eq!(r["ok"], false, "{r}"); + let _ = request(&mut app, "ui.set", json!({"original_editor": {"path": "/Apps/Bad"}})); + let r = request(&mut app, "ui.dialog.confirm", json!({})); + assert_eq!(r["ok"], true, "{r}"); + assert!(app.ui.original_editor.path.is_none()); + prefs_dialog::open(&mut app, Some("File Handling")); + app.ui.answering_control = true; + assert!(choose(&mut app, Some("/Apps/Bad")).is_err()); + app.ui.answering_control = false; + app.synthetic_frame = true; + assert!(choose(&mut app, Some("/Apps/Bad")).is_err()); + assert!(app.original_editor.choice.path.is_none()); + } + + #[test] + fn original_editor_async_picker_validates_and_commits_only_on_ok() { + let mut app = app(); + let (tx, rx) = std::sync::mpsc::channel(); + let mut rx = Some(rx); + app.services.start_pick = Some(Box::new(move |_| rx.take())); + choose(&mut app, None).unwrap(); + tx.send(vec!["/Apps/Async Editor.app".into()]).unwrap(); + crate::picks::poll(&mut app, &egui::Context::default()); + assert_eq!(app.original_editor.choice.path.as_deref(), Some("/Apps/Async Editor.app")); + assert!(app.ui.original_editor.path.is_none()); + prefs_dialog::confirm(&mut app).unwrap(); + assert_eq!(app.ui.original_editor.path.as_deref(), Some("/Apps/Async Editor.app")); + } + + #[test] + fn original_editor_picker_answer_does_not_survive_reopening_preferences() { + let mut app = app(); + let (tx, rx) = std::sync::mpsc::channel(); + let mut rx = Some(rx); + app.services.start_pick = Some(Box::new(move |_| rx.take())); + choose(&mut app, None).unwrap(); + crate::dialogs::cancel(&mut app); + prefs_dialog::open(&mut app, Some("File Handling")); + tx.send(vec!["/Apps/Stale.app".into()]).unwrap(); + crate::picks::poll(&mut app, &egui::Context::default()); + assert!(app.original_editor.choice.path.is_none()); + } + + #[test] + fn original_editor_controls_are_desktop_only_and_draw_the_choice() { + let mut app = app(); + let paint = |app: &mut VectorcraftApp| { + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("__found".into(), json!("editOriginalSystemDefaults")); + d.fields.insert("__scrollTo".into(), json!(true)); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut text = String::new(); + // The fixed-height Preferences list scrolls after its sizing pass. + for frame in 0..4 { + let input = egui::RawInput { + time: Some(f64::from(frame)), + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 1000.0))), + ..Default::default() + }; + let mut out = ctx.run_ui(input, |ui| prefs_dialog::show(app, ui.ctx())); + out.textures_delta.clear(); + text = crate::tests_labels::shapes_text(&out); + } + text + }; + let text = paint(&mut app); + assert!(text.contains("Edit Original with:") && text.contains("PhotoCraft"), "{text}"); + app.services.check_application = None; + let text = paint(&mut app); + assert!(!text.contains("Edit Original with:"), "{text}"); + } +} diff --git a/crates/ui-egui/src/palette/search.rs b/crates/ui-egui/src/palette/search.rs index 1e4f794a8f..312c77e73a 100644 --- a/crates/ui-egui/src/palette/search.rs +++ b/crates/ui-egui/src/palette/search.rs @@ -289,7 +289,8 @@ 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 +/// not inside a `{`, `[` or `(` group (brackets inside double quotes or backticks are text, as in +/// the engine's params object), 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 @@ -298,7 +299,7 @@ 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) { + for (i, ch, depth) in crate::shortcut_editor::outside_quotes_and_backticks(params) { let before = params.get(copied..i).unwrap_or_default(); match ch { '{' | '[' | '(' if depth == 0 && (ch == '{' || before.trim_end().ends_with('→')) => { @@ -501,14 +502,17 @@ impl Index { // The word meets a stem form of a word of the result ("scale" and Scaling) when it is itself // 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 | DESCRIPTION)) - { - mark(self.postings_of(t), &|field| match field { - LABEL_STEMMED => Some(LABEL_STEM), - PATH_STEMMED => Some(PATH_WORD), - DESCRIPTION_STEMMED => Some(DESCRIPTION_WORD), + // cut at the end of a word ([`description`]), so it holds no partly typed word. A word that + // only descriptions hold meets the stem forms of descriptions only, so it does not change + // how labels and menu paths rank. + if let Some(t) = self.find(word) { + let postings = self.postings_of(t); + let named = postings.iter().any(|p| matches!(p.field, LABEL | PATH | ID)); + let described = named || postings.iter().any(|p| p.field == DESCRIPTION); + mark(postings, &|field| match field { + LABEL_STEMMED if named => Some(LABEL_STEM), + PATH_STEMMED if named => Some(PATH_WORD), + DESCRIPTION_STEMMED if described => Some(DESCRIPTION_WORD), _ => None, }); } @@ -538,7 +542,8 @@ impl Index { } /// 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 + /// it, is in ("bg" and background, "flipped" and reflect, "setting" and preferences), with the + /// stem forms of the group's words ("prefs" and setting), 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()); @@ -601,6 +606,15 @@ impl Index { self.terms.get(*t).map(|at| self.text(at)) } + /// The texts of the words of `near` that are words of result `i` in one of `fields`, in the + /// order of `near`. + fn words_of(&self, near: &[usize], i: usize, fields: &[u8]) -> Vec<&str> { + near.iter() + .filter(|&&t| self.postings_of(t).iter().any(|p| usize::from(p.entry) == i && fields.contains(&p.field))) + .filter_map(|&t| self.terms.get(t).map(|at| self.text(at))) + .collect() + } + /// 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 }; @@ -672,7 +686,8 @@ type RankKey = (bool, bool, u8, u8, u32, u8, u8, usize); /// 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"), +/// word matched through a word of the same meaning replaced by that word ("colour" as "color"; of +/// several such words the result holds, the ones that match the whole query best), /// 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 { @@ -737,7 +752,8 @@ pub(crate) fn rank(entries: &[Entry], index: &Index, query: &str) -> Vec { // 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); + // The words each such word may be read as, by its place in the query. + let (mut synonym, mut meant): (bool, Vec<(usize, Vec<&str>)>) = (false, vec![]); 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) @@ -773,9 +789,12 @@ pub(crate) fn rank(entries: &[Entry], index: &Index, query: &str) -> Vec { 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); + meant.push((k, vec![near])); } } + // The word may be read as each word of its group the label or menu path holds, and then + // as each stem form of one, so "prefs" reads Preferences as preferences before its stem + // form preference; the reading that matches the whole query best counts. let fields: &[u8] = match g { LABEL_SYNONYM => &[LABEL, LABEL_STEMMED], PATH_SYNONYM => &[PATH, PATH_STEMMED], @@ -783,8 +802,16 @@ pub(crate) fn rank(entries: &[Entry], index: &Index, query: &str) -> Vec { }; 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 mut same: Vec<&str> = vec![]; + for &f in fields { + for w in meanings.get(k).map(|near| index.words_of(near, i, &[f])).unwrap_or_default() { + if !same.contains(&w) { + same.push(w); + } + } + } + if !same.is_empty() { + meant.push((k, same)); } } worst = worst.max(g); @@ -799,12 +826,7 @@ pub(crate) fn rank(entries: &[Entry], index: &Index, query: &str) -> Vec { } 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 meant_tier = if synonym { best_reading(&query, &starts, &tokens, &meant, |read| phrase(e, read, false)) } else { tier }; let length = split_name(&e.shown).0.chars().count(); ranked.push(((described, typo, tier, worst, sum, meant_tier, e.kind, length), place)); } @@ -812,6 +834,39 @@ pub(crate) fn rank(entries: &[Entry], index: &Index, query: &str) -> Vec { ranked.into_iter().map(|(_, place)| place).collect() } +/// The most readings of a query [`best_reading`] compares for one result. +const MAX_READINGS: usize = 16; + +/// The best whole-query match `tier` gives `query` read with each word `k` of `swaps` (the word at +/// `starts[k]`, as long as `tokens[k]`) replaced by one of its words. At most [`MAX_READINGS`] +/// readings are compared, the first one with each word's first choice. +fn best_reading(query: &str, starts: &[usize], tokens: &[&str], swaps: &[(usize, Vec<&str>)], tier: impl Fn(&str) -> u8) -> u8 { + let readings = swaps.iter().fold(1usize, |n, (_, words)| n.saturating_mul(words.len().max(1))).min(MAX_READINGS); + let (mut best, mut read) = (NO_PHRASE, String::new()); + for r in 0..readings { + read.clear(); + let (mut copied, mut rest) = (0, r); + for (k, words) in swaps { + let len = words.len().max(1); + let pick = words.get(rest % len); + rest /= len; + if let (Some(word), Some(&start), Some(token)) = (pick, starts.get(*k), tokens.get(*k)) + && let Some(between) = query.get(copied..start) + { + read.push_str(between); + read.push_str(word); + copied = start + token.len(); + } + } + read.push_str(query.get(copied..).unwrap_or_default()); + best = best.min(tier(&read)); + if best == EXACT_ID { + break; + } + } + best +} + /// The first place in the menu bar of each item a result runs, as an English `›`-separated path /// of the menus that hold it: by command id, `panel:` for a Window menu panel (Learn too), /// `effect:` for an Effect menu item and `plugin:` for an Object › Plug-ins filter. With @@ -1248,6 +1303,50 @@ mod tests { assert_eq!(ranked(&c, "colour"), ["c.three", "panel:color", "tool:zz"]); } + /// A query word that is an English stem form of a word of a group ("setting" of settings, + /// "preference" of preferences) finds the group, and a stem form of a word of the group meets a + /// result's word ("prefs" and Zz Setting). A result whose label holds the query word itself + /// still ranks first. The whole query is read with the group word a label holds before a stem + /// form of it, so "prefs" reads Preferences as its exact label. + #[test] + fn a_stem_form_of_a_group_word_meets_the_group() { + let c = synthetic(vec![entry("Preferences Tool", "tool:zz"), entry("Preferences", "a.one")]); + assert_eq!(ranked(&c, "prefs"), ["a.one", "tool:zz"]); + let c = synthetic(vec![entry("Zz Preferences", "a.one"), entry("Zz Setting", "b.two"), entry("Zz Settings", "c.three")]); + let setting = ranked(&c, "setting"); + assert_eq!(setting.first().map(String::as_str), Some("b.two"), "{setting:?}"); + assert!(setting.iter().any(|id| id == "a.one"), "{setting:?}"); + assert!(ranked(&c, "preference").iter().any(|id| id == "c.three"), "a singular query word finds the group"); + let prefs = ranked(&c, "prefs"); + for id in ["a.one", "b.two", "c.three"] { + assert!(prefs.iter().any(|r| r == id), "{id} in {prefs:?}"); + } + assert!(ranked(&c, "set").iter().all(|id| id != "a.one"), "a stem form of a query word that is no group word finds no group"); + } + + /// A query word that only a description holds meets the stem forms of descriptions, not those + /// of labels: "rat" in another command's description does not lift Zz Rating above Zz Ratio. + #[test] + fn a_description_word_does_not_lift_a_label_stem() { + let entries = || vec![entry("Zz Ratio", "a.one"), entry("Zz Rating", "b.two"), entry("Animal Outline", "c.three")]; + assert_eq!(ranked(&synthetic(entries()), "rat zz"), ["a.one", "b.two"]); + let c = described(entries(), &["", "", "Trace a rat silhouette"]); + assert_eq!(ranked(&c, "rat zz"), ["a.one", "b.two"]); + let c = described(vec![entry("Zz Outline", "a.one"), entry("Zz Trace", "b.two")], &["Scaling the art", "Scale it"]); + assert!(ranked(&c, "scale").iter().any(|id| id == "a.one"), "a description word still meets a description's stem form"); + } + + /// When a label holds two words of the group a query word means, the whole query is read with + /// the one that matches it best: "prefs preferences" reads Settings Preferences as its exact + /// label, which ranks it before a tool whose label holds only one of the words. + #[test] + fn a_synonym_is_read_as_the_group_word_that_matches_the_whole_query() { + let c = synthetic(vec![entry("Preferences Tool", "tool:zz"), entry("Settings Preferences", "a.one")]); + assert_eq!(ranked(&c, "prefs preferences").first().map(String::as_str), Some("a.one")); + let c = synthetic(vec![entry("Preferences Tool", "tool:zz"), entry("Preferences", "a.one")]); + assert_eq!(ranked(&c, "prefs"), ["a.one", "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] @@ -1288,6 +1387,11 @@ mod tests { // 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"), + // A bracket or a double quote inside a backtick span is text, as in the engine's params + // object, and so is a group inside a backtick span outside a group. + ("{pattern?: `(`} transparent background", "transparent background"), + ("{sep: `}`, quote: `\"`} split the text", "split the text"), + ("uses `{x}` as text", "uses `{x}` as text"), // No group at all. ("plain words\n here", "plain words here"), ("", ""), @@ -1664,8 +1768,8 @@ mod tests { let started = std::time::Instant::now(); let c = catalog(Lang::EN, false); let built = started.elapsed(); - let started = std::time::Instant::now(); let params = super::super::params_texts(&c.list); + let started = std::time::Instant::now(); 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(); diff --git a/crates/ui-egui/src/panel_docking.rs b/crates/ui-egui/src/panel_docking.rs index c4269e6190..24dc900a0f 100644 --- a/crates/ui-egui/src/panel_docking.rs +++ b/crates/ui-egui/src/panel_docking.rs @@ -1454,8 +1454,13 @@ pub(crate) fn close_overlays_for_modal(app: &mut VectorcraftApp, ctx: &egui::Con /// 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 /// window loses it, as a click elsewhere in one window would take it. A floating document's OS -/// window forwards its keys here too ([`crate::doc_windows`]). -pub(crate) fn forward_keys(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec, modifiers: Option) { +/// window forwards its keys here too ([`crate::doc_windows`]). A Copy or Cut whose text a label of +/// that window copied stays there. +pub(crate) fn forward_keys(app: &mut VectorcraftApp, ctx: &egui::Context, mut events: Vec, modifiers: Option) { + if crate::shortcuts::take_copied_in_window(ctx) { + events.retain(|e| !matches!(e, egui::Event::Copy | egui::Event::Cut)); + app.drop_unwritten_formats(); + } if events.is_empty() { return; } diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index f0005662c7..b59e44949e 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -810,6 +810,8 @@ mod tests_color_wheel; #[cfg(test)] mod tests_color_wheel_box; #[cfg(test)] +mod tests_color_wheel_harmony; +#[cfg(test)] mod tests_color_wheel_vision; #[cfg(test)] mod tests_constrain; diff --git a/crates/ui-egui/src/panels/appearance.rs b/crates/ui-egui/src/panels/appearance.rs index db11c16915..938a805c83 100644 --- a/crates/ui-egui/src/panels/appearance.rs +++ b/crates/ui-egui/src/panels/appearance.rs @@ -16,7 +16,7 @@ //! fills/strokes for Duplicate and Delete. Delete on a selected Opacity row sets it back to //! Default (100%, Normal). -use std::sync::OnceLock; +use std::sync::{Arc, OnceLock}; use egui::{Rect, Sense, Stroke, StrokeKind, Ui, pos2, vec2}; use serde_json::{Value, json}; @@ -476,9 +476,10 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { select_row(app, ui.ctx(), Sel::None); } ui.painter().line_segment([r.left_bottom(), r.right_bottom()], Stroke::new(1.0, t.input_border)); - let mix = mixed(app); + let summary = summary(app, ui.ctx()); + let mix = summary.as_ref().and_then(|s| s.mixed(app)); let mixed = mix.is_some(); - let label = tl!(object_label(app)); + let label = tl!(summary.as_ref().map_or("No Selection", |s| s.label)); // A linked object names its graphic style ("Rectangle: Sunshine"), and so does new art // with nothing selected. let style = match app.session.selection_graphic_style() { @@ -497,7 +498,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { Some(n) => n.appearance.fill_paint(), None => app.session.paint.fill.clone(), }; - chip(ui, th, &fill, mix.as_ref().is_some_and(|m| m.fills_differ)); + chip(ui, th, &fill, mix.is_some_and(|m| m.fills_differ)); if let Some(n) = node.as_ref().filter(|_| !mixed) { thumbnail_drag(ui, th, n.id); } @@ -505,7 +506,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { text(ui, r.left_center() + vec2(if hide_thumb { 8.0 } else { 46.0 }, 0.0), &label, true); match &node { // Objects that differ list what they share, under a note that they differ. - Some(n) if let Some(m) = &mix => { + Some(n) if let Some(m) = mix => { let (mr, _) = ui.allocate_exact_size(vec2(ui.available_width(), ROW), Sense::hover()); let mut job = egui::text::LayoutJob::default(); let format = egui::TextFormat { font_id: egui::FontId::proportional(12.0), color: t.text_dim, italics: true, ..Default::default() }; @@ -606,6 +607,44 @@ struct Mixed { fills_differ: bool, } +/// The selection's [`object_label`] and [`mixed`] summary for the active document as of one +/// revision and one list of appearance subjects ([`vectorcraft_doc::Selection::subjects`]), shared by +/// the Control bar and the Appearance panel ([`summary`]). +pub(crate) struct Summary { + uid: u64, + revision: u64, + subjects: Vec, + /// [`object_label`] of these subjects. + pub(crate) label: &'static str, + /// [`mixed`] of these subjects, worked out the first time the Appearance panel asks for it. + mixed: OnceLock>, +} + +impl Summary { + /// [`mixed`] of the subjects this summary was made for. + fn mixed<'a>(&'a self, app: &VectorcraftApp) -> Option<&'a Mixed> { + self.mixed.get_or_init(|| mixed(app)).as_ref() + } +} + +/// The active document's [`Summary`], made again only when the document changes (its id or its +/// revision) or the appearance subjects do, compared id by id. `None` with no document open. +pub(crate) fn summary(app: &VectorcraftApp, ctx: &egui::Context) -> Option> { + let st = app.session.active()?; + let subjects = st.selection.subjects(); + let id = egui::Id::unique("ap-summary"); + if let Some(s) = ctx.data(|d| d.get_temp::>(id)) + && s.uid == st.uid + && s.revision == st.revision + && s.subjects == subjects + { + return Some(s); + } + let s = Arc::new(Summary { uid: st.uid, revision: st.revision, subjects: subjects.to_vec(), label: object_label(app), mixed: OnceLock::new() }); + ctx.data_mut(|d| d.insert_temp(id, s.clone())); + Some(s) +} + /// `params` of an item or effect command the panel runs, with `aligned` when the selected objects' /// stacks differ: its indices are then rows of the first object's stack, which each other object /// edits where it has them (the panel lists only the rows they share). diff --git a/crates/ui-egui/src/panels/appearance/tests.rs b/crates/ui-egui/src/panels/appearance/tests.rs index 2d3350443b..67bea32636 100644 --- a/crates/ui-egui/src/panels/appearance/tests.rs +++ b/crates/ui-egui/src/panels/appearance/tests.rs @@ -1017,6 +1017,184 @@ fn a_mixed_selection_lists_what_its_objects_share() { assert_eq!(frame(&mut app).iter().find(|t| *t != "?").map(String::as_str), Some("Mixed Objects")); } +/// The [`summary`] `ctx` holds for the active document, checked field by field against what +/// [`object_label`] and [`mixed`] work out from scratch. +fn fresh_summary(app: &VectorcraftApp, ctx: &egui::Context) -> Arc { + let s = summary(app, ctx).unwrap(); + assert_eq!(s.label, object_label(app), "the kind label"); + let parts = |m: &Mixed| (m.shared.clone(), m.transparency, m.fills_differ); + assert_eq!(s.mixed(app).map(parts), mixed(app).as_ref().map(parts), "the mixed summary"); + s +} + +/// The object row's kind and the Mixed Appearances summary are worked out once per document +/// revision and list of subjects: a repaint with nothing changed reuses them, and they follow an +/// edit, Undo and Redo, a selection that changes only in the middle, a target circle and another +/// document at the same revision. +#[test] +fn the_selection_summary_is_reused_until_the_document_or_its_subjects_change() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + let id = |v: Value| NodeId(v["id"].as_u64().unwrap()); + let art = |app: &mut VectorcraftApp| -> (Vec, NodeId) { + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let r = (0..3).map(|i| id(app.run("shape.rectangle", json!({"x": i * 30, "y": 0, "width": 20, "height": 20})).unwrap())).collect(); + (r, id(app.run("text.create", json!({"x": 0, "y": 100, "text": "Hi"})).unwrap())) + }; + let (r, t) = art(&mut app); + app.run("select.set", json!({"ids": r})).unwrap(); + let s = fresh_summary(&app, &ctx); + assert!(s.mixed(&app).is_none(), "alike rectangles"); + assert!(Arc::ptr_eq(&s, &fresh_summary(&app, &ctx)), "a repaint with nothing changed reuses the summary"); + // An edit of the middle object, then Undo and Redo. + app.run("transparency.set", json!({"ids": [r[1]], "opacity": 50})).unwrap(); + assert!(fresh_summary(&app, &ctx).mixed(&app).is_some_and(|m| m.transparency), "the middle one's opacity differs"); + app.run("edit.undo", json!({})).unwrap(); + assert!(fresh_summary(&app, &ctx).mixed(&app).is_none(), "undone"); + app.run("edit.redo", json!({})).unwrap(); + assert!(fresh_summary(&app, &ctx).mixed(&app).is_some(), "redone"); + // The middle id changes at the same revision, length, first and last id. + app.session.active_mut().unwrap().selection.objects[1] = t; + assert_eq!(fresh_summary(&app, &ctx).label, "Mixed Objects"); + // A target circle with the selected objects unchanged, and back. + let layer = app.session.active().unwrap().doc.default_layer().unwrap(); + app.session.active_mut().unwrap().selection.target = Some(layer); + assert_eq!(fresh_summary(&app, &ctx).label, "Layer"); + app.session.active_mut().unwrap().selection.target = None; + assert_eq!(fresh_summary(&app, &ctx).label, "Mixed Objects"); + // Another document with the same ids selected at the same revision, where the first object's + // opacity differs instead. + let revision = app.session.active().unwrap().revision; + assert!(fresh_summary(&app, &ctx).mixed(&app).is_some_and(|m| !m.transparency)); + let (r2, t2) = art(&mut app); + assert_eq!((&r2, t2), (&r, t), "the second document numbers its objects alike"); + app.run("transparency.set", json!({"ids": [r[0]], "opacity": 50})).unwrap(); + let st = app.session.active_mut().unwrap(); + st.selection.objects = vec![r[0], t, r[2]]; + st.selection.target = None; + st.revision = revision; + assert!(fresh_summary(&app, &ctx).mixed(&app).is_some_and(|m| m.transparency), "the second document's own summary"); + app.run("document.activate", json!({"index": 0})).unwrap(); + assert!(fresh_summary(&app, &ctx).mixed(&app).is_some_and(|m| !m.transparency), "the first document's again"); +} + +/// 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 milliseconds `f` takes: 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 +} + +/// A document of `n` small rectangles, all selected; with `mixed`, every second one at 50% opacity. +fn many_rectangles(n: usize, mixed: bool) -> VectorcraftApp { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 800, "height": 600})).unwrap(); + let r = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 4, "height": 4})).unwrap()["id"].as_u64().unwrap(); + let mut d = vectorcraft_doc::Document::clone(&app.session.active().unwrap().doc); + let template = d.node(NodeId(r)).unwrap().clone(); + let layer = d.layers[0].id; + d.children_mut(Some(layer)).unwrap().clear(); + let mut ids = Vec::with_capacity(n); + for i in 0..n { + let mut node = template.clone(); + node.id = d.alloc_id(); + if mixed && i % 2 == 1 { + node.opacity = 0.5; + } + ids.push(d.insert(Some(layer), usize::MAX, node).unwrap()); + } + app.session.add_document(d, None); + app.session.active_mut().unwrap().selection.objects = ids; + app +} + +/// Timings of the selection summary the Control bar and the Appearance panel show on each repaint, +/// on 5,000, 20,000 and 200,000 selected rectangles, alike and with every second one's opacity +/// different, in milliseconds per repaint: worked out from scratch (`object_label` for the Control +/// bar, then `mixed` and `object_label` for the panel); through [`summary`], whose first repaint +/// works it out and the rest reuse it; and through [`summary`] with its stored entry removed before +/// every repaint, as when the document or the selection changes each time. They run in turn on the same document, +/// 7 runs each, and the results are checked equal. Ignored by default; it prints the median, fastest and slowest run +/// and sets no bound on them: +/// `cargo test --release -p vectorcraft-ui-egui --lib selection_summary_perf -- --ignored --nocapture`. +#[test] +#[ignore = "a benchmark: run with --ignored --nocapture"] +fn selection_summary_perf() { + const RUNS: usize = 7; + const REPAINTS: usize = 20; + let stats = |mut v: Vec| { + v.sort_by(f64::total_cmp); + format!("{:.3} ({:.3}-{:.3})", v[v.len() / 2], v[0], v[v.len() - 1]) + }; + eprintln!("selection_summary_perf: {}", if thread_cpu().is_some() { "thread CPU time" } else { "wall clock" }); + eprintln!( + "selection_summary_perf: {:>8} {:<6} {:>28} {:>28} {:>28}", + "selected", "kind", "from scratch ms (min-max)", "summary ms (min-max)", "summary, changed ms (min-max)" + ); + for n in [5_000, 20_000, 200_000] { + for mixed_case in [false, true] { + let app = many_rectangles(n, mixed_case); + let (mut old, mut new, mut changed) = (vec![], vec![], vec![]); + for _ in 0..RUNS { + let mut seen = None; + old.push( + time_ms(|| { + for _ in 0..REPAINTS { + let bar = object_label(&app); + let mix = mixed(&app); + let row = object_label(&app); + seen = Some((bar, row, mix.map(|m| (m.shared, m.transparency, m.fills_differ)))); + } + }) / REPAINTS as f64, + ); + let ctx = egui::Context::default(); + let mut cached = None; + new.push( + time_ms(|| { + for _ in 0..REPAINTS { + let bar = summary(&app, &ctx).map_or("No Selection", |s| s.label); + let s = summary(&app, &ctx).unwrap(); + let mix = s.mixed(&app).map(|m| (m.shared.clone(), m.transparency, m.fills_differ)); + cached = Some((bar, s.label, mix)); + } + }) / REPAINTS as f64, + ); + assert_eq!(cached, seen, "{n} {mixed_case}"); + let mut fresh = None; + changed.push( + time_ms(|| { + for _ in 0..REPAINTS { + ctx.data_mut(|d| d.remove::>(egui::Id::unique("ap-summary"))); + let bar = summary(&app, &ctx).map_or("No Selection", |s| s.label); + let s = summary(&app, &ctx).unwrap(); + let mix = s.mixed(&app).map(|m| (m.shared.clone(), m.transparency, m.fills_differ)); + fresh = Some((bar, s.label, mix)); + } + }) / REPAINTS as f64, + ); + assert_eq!(fresh, seen, "{n} {mixed_case}"); + } + let kind = if mixed_case { "mixed" } else { "alike" }; + eprintln!("selection_summary_perf: {:>8} {:<6} {:>28} {:>28} {:>28}", n, kind, stats(old), stats(new), stats(changed)); + } + } +} + /// The panel's subject is the `Arc` the document holds for the selected object, a targeted group /// or a targeted layer, not a copy of it; nothing with nothing selected. #[test] diff --git a/crates/ui-egui/src/panels/brushes.rs b/crates/ui-egui/src/panels/brushes.rs index d64c7a3a50..7bc9ebad21 100644 --- a/crates/ui-egui/src/panels/brushes.rs +++ b/crates/ui-egui/src/panels/brushes.rs @@ -109,8 +109,9 @@ fn preview(ui: &Ui, doc: &Document, def: &Value, key: u64, size: egui::Vec2) -> /// What a stroke preview of brush definition `def`, `w` × `h` pt, renders: a copy of `resources` /// (a document whose patterns, symbols, swatches and images the brush art may use) without its art, /// and a stroke painted with the brush across it. The stroke goes from light to heavy pen pressure -/// and back, from an upright pen to one lying flat and back, and once round every bearing and barrel -/// rotation, so brushes that vary with the pen show how they vary. +/// and back, from an upright pen to one lying flat and back, once round every bearing and barrel +/// rotation, and from one end of an airbrush pen's finger wheel to the other and back, so brushes +/// that vary with the pen show how they vary. fn preview_doc(resources: &Document, def: &Value, w: f64, h: f64) -> Option { let mut doc = resources.clone(); let layer = doc.alloc_id(); @@ -124,6 +125,7 @@ fn preview_doc(resources: &Document, def: &Value, w: f64, h: f64) -> Option) -> Option { let ours = |v: &Value| v == name.as_str(); let in_group = |key: &str| group.as_deref().is_some_and(|g| p[key] == g); @@ -346,6 +346,7 @@ fn follow_step(id: &str, p: &Value, reply: &Value, name: String, group: &mut Opt let moved = match id { "swatch.newGroup" | "swatch.editGroup" if members("swatches") => Some(reply["name"].as_str().map(str::to_string)), "swatch.ungroup" if in_group("name") => Some(None), + "swatch.renameGroup" if in_group("group") => Some(reply["name"].as_str().map(str::to_string)), "swatch.move" if ours(&p["name"]) || p["names"].as_array().is_some_and(|a| a.iter().any(ours)) => { Some(p["group"].as_str().map(str::to_string)) } @@ -1566,8 +1567,8 @@ mod tests { assert!(linked(&app, &ctx)); } - /// Deleting the color group that holds the spot color base's swatch ends the link; an Edit - /// Color Group that keeps it does not. + /// Deleting the color group that holds the spot color base's swatch ends the link, also under + /// a name Color Group Options gave it; an Edit Color Group that keeps it does not. #[test] fn a_deleted_color_group_ends_the_link() { let mut app = spot_app(1.0); @@ -1599,6 +1600,16 @@ mod tests { ]); app.run("command.batch", json!({"commands": steps})).unwrap(); assert!(!linked(&app, &ctx), "moved into a group that was deleted"); + // Its group renamed by Color Group Options and deleted under the new name in the same batch. + relink(&mut app); + let steps = json!([ + {"command": "swatch.newGroup", "params": {"name": "Spots", "swatches": ["Ink"]}}, + {"command": "swatch.renameGroup", "params": {"group": "Spots", "name": "Spot Inks"}}, + {"command": "swatch.delete", "params": {"names": ["Spot Inks"]}}, + {"command": "swatch.new", "params": {"name": "Ink", "color": "#669933", "spot": true}}, + ]); + app.run("command.batch", json!({"commands": steps})).unwrap(); + assert!(!linked(&app, &ctx), "its group renamed, then deleted"); // Edit Color Group that keeps it, with a new group name, keeps the link. relink(&mut app); app.run("swatch.newGroup", json!({"name": "Spots", "swatches": ["Ink"]})).unwrap(); diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index bbc2b588c5..028652c9bb 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -12,18 +12,24 @@ //! Brightness, Red, Green or Blue). The field shows the other two components on the Color //! Picker's axes. //! +//! Show Harmony puts a marker on the ring for each other color of the harmony rule picked under +//! Harmony Rule (the Color Guide's rules whose colors each have a hue of their own), filled with +//! that color. The markers follow the current color, and a click on one applies its color as a +//! pick does. +//! //! Panel menu › Show Color Vision Preview adds a row under the wheel or the box with the color as //! simulated for protanopia, deuteranopia and tritanopia, through the simulations View › Proof //! Setup uses, and for achromatopsia as the gray with the color's CIE L*. The chips only show the //! simulation. //! -//! The view, the channel and Show Color Vision Preview are kept with the preferences -//! (`ui.colorWheel`). +//! The view, the channel, Show Harmony, Harmony Rule and Show Color Vision Preview are kept with +//! the preferences (`ui.colorWheel`). use egui::{Rect, Sense, Stroke, StrokeKind, Ui, UiBuilder, vec2}; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use vectorcraft_color::cms::{self, Cms, ProofSetup, ProofTarget}; +use vectorcraft_color::harmony::Harmony; use vectorcraft_color::{Color, Paint, hsb_to_rgb, rgb_to_hsb}; use vectorcraft_doc::{ColorMode, NodeId}; @@ -69,19 +75,56 @@ impl View { /// The panel's settings, kept with the preferences (`UiState::color_wheel`, `ui.colorWheel`). /// Each key reads on its own, and a value this build does not know reads as the key's default. -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", default)] pub struct Settings { #[serde(deserialize_with = "deserialize_view")] pub view: View, #[serde(serialize_with = "serialize_channel", deserialize_with = "deserialize_channel")] pub channel: Channel, + /// Show Harmony: markers on the ring for the other colors of `harmony_rule`. + #[serde(deserialize_with = "deserialize_flag")] + pub harmony: bool, + /// The rule of Show Harmony, one of [`harmony_rules`]. + #[serde(serialize_with = "serialize_rule", deserialize_with = "deserialize_rule")] + pub harmony_rule: Harmony, /// Show Color Vision Preview: the row of simulated colors under the wheel or the box. A saved /// `true` shows the row and any other value hides it. #[serde(deserialize_with = "crate::panels::color::deserialize_rgb_percent")] pub vision: bool, } +impl Default for Settings { + fn default() -> Self { + Self { view: View::default(), channel: Channel::default(), harmony: false, harmony_rule: Harmony::Complementary, vision: false } + } +} + +/// The harmony rules the wheel shows: those whose colors each have a hue of their own, so that no +/// two markers sit at the same place on the ring. +pub fn harmony_rules() -> impl Iterator { + Harmony::ALL.into_iter().filter(|h| h.hues_differ()) +} + +/// The wheel's harmony rule named by `s`, its id or its label. +fn parse_rule(s: &str) -> Option { + Harmony::parse(s).filter(|h| h.hues_differ()) +} + +fn deserialize_flag<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + let v = ::deserialize(d)?; + Ok(v.as_bool().unwrap_or_default()) +} + +fn serialize_rule(h: &Harmony, s: S) -> Result { + s.serialize_str(&h.id()) +} + +fn deserialize_rule<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + let v = ::deserialize(d)?; + Ok(v.as_str().and_then(parse_rule).unwrap_or(Harmony::Complementary)) +} + fn deserialize_view<'de, D: serde::Deserializer<'de>>(d: D) -> Result { let v = ::deserialize(d)?; Ok(v.as_str().and_then(View::parse).unwrap_or_default()) @@ -103,12 +146,12 @@ pub fn deserialize_settings<'de, D: serde::Deserializer<'de>>(d: D) -> Result Result { - const KEYS: [&str; 3] = ["view", "channel", "vision"]; + const KEYS: [&str; 5] = ["view", "channel", "harmony", "harmonyRule", "vision"]; match p { Value::Null => {} Value::Object(o) => { @@ -127,6 +170,21 @@ pub(crate) fn command(app: &mut VectorcraftApp, p: &Value) -> Result {} Some(v) => set.channel = v.as_str().and_then(Channel::parse).ok_or("`channel` must be hue, saturation, brightness, red, green or blue")?, } + let key = "harmony"; + match p.get(key) { + None | Some(Value::Null) => {} + Some(v) => set.harmony = v.as_bool().ok_or_else(|| format!("`{key}` must be true or false"))?, + } + let key = "harmonyRule"; + match p.get(key) { + None | Some(Value::Null) => {} + Some(v) => { + set.harmony_rule = v.as_str().and_then(parse_rule).ok_or_else(|| { + let ids: Vec = harmony_rules().map(Harmony::id).collect(); + format!("`{key}` must be one of {}", ids.join(", ")) + })? + } + } if let Some(on) = crate::menus::opt_bool(p, "vision")? { set.vision = on; } @@ -134,8 +192,8 @@ pub(crate) fn command(app: &mut VectorcraftApp, p: &Value) -> Result = set.harmony_rule.apply_hsb(hsb).into_iter().skip(1).collect(); + let markers = widgets::ring_markers(ui, "color-wheel-harmony", ring.rect, &others, tl!("Harmony color")); + held = markers.held; + if let Some(i) = markers.picked + && let Some(&c) = others.get(i) + { + pick = Some((c, Live::Released)); + } + } + if let Some((h, phase)) = ring.hue + && !held + && pick.is_none() + { pick = Some(([h, hsb[1], hsb[2]], phase)); } // A press between the square and the ring picks the closest point of the square, which diff --git a/crates/ui-egui/src/panels/doc_info.rs b/crates/ui-egui/src/panels/doc_info.rs index ff978ebb4f..ed6bdcdaab 100644 --- a/crates/ui-egui/src/panels/doc_info.rs +++ b/crates/ui-egui/src/panels/doc_info.rs @@ -107,7 +107,7 @@ fn brush_value(value: &str) -> &str { /// Row `k` of Document Info section `id` (`label` and `value` as `document.info` gives them, the /// label a name when `named`) with its value in the interface language, built from what /// `document.info` (`info`) gives as values: the -/// units, the raster effects resolution, each brush's type, each font's file, match and +/// units, the raster effects resolution, each brush's type, each font's type and uses, each font's file, match and /// embedding permission, each image's size and file, each Repeat object's kind and counts, and the /// kinds of the gradients no swatch names. Names (fonts, files, faces, swatches) stay as they are. /// None when the row's value is shown as `document.info` gives it, or the values do not match the @@ -130,6 +130,7 @@ fn shown_value(info: &Value, id: &str, k: usize, (label, value): (&str, &str), n _ => None, }, "brushes" => Some(brush_value(value).to_string()), + "fonts" => font_use_value(entry("fontUses")?), "fontDetails" => font_detail_value(entry("fontDetails")?), "linkedImages" | "embeddedImages" => { let linked = id == "linkedImages"; @@ -181,6 +182,19 @@ fn fill(template: &str, args: &[(&str, &str)]) -> String { crate::i18n::fill_once(template, args) } +/// A `fontUses` entry as Fonts shows it: the font's type (the format names TrueType and OpenType +/// stay as they are) and its number of uses in the language's plural forms. +fn font_use_value(e: &Value) -> Option { + let kind = match e["type"].as_str()? { + "truetype" => "TrueType", + "opentype" => "OpenType", + "unknown" => tl!("unknown type"), + _ => return None, + }; + let uses = crate::i18n::tn(e["uses"].as_u64()?, "{n} use", "{n} uses"); + Some(fill(tl!("{type}; {uses}"), &[("type", kind), ("uses", &uses)])) +} + /// A `fontDetails` entry as Font Details shows it: the font's file (or that it is built in) and /// what its license allows, the face shown in place of a style the family lacks, the face shown in /// place of a font that is not installed, or that it is missing. @@ -456,7 +470,7 @@ mod tests { assert!(objects.contains("\nOBJECTS\n") && objects.contains("Paths: 1") && objects.contains("Text Objects: 1"), "{objects}"); assert!(!objects.contains("\nDOCUMENT\n") && !objects.contains("\nFONTS\n"), "only Objects: {objects}"); let fonts = saved_from_menu(&mut app, "fonts", false); - assert!(fonts.contains("\nFONTS\n") && fonts.contains("Source Sans 3"), "{fonts}"); + assert!(fonts.contains("\nFONTS\nSource Sans 3 Regular: TrueType; 1 use\n"), "{fonts}"); assert!(!fonts.contains("\nOBJECTS\n") && !fonts.contains("\nFONT DETAILS\n"), "only Fonts: {fonts}"); let all = saved_from_menu(&mut app, "", false); assert!( @@ -593,6 +607,49 @@ mod tests { assert!(report.contains("Units: Millimeters\n") && report.contains("Radial Repeat, 6 instances"), "{report}"); } + /// Fonts shows each font's type and number of uses in the interface language, in the + /// language's plural forms; the format names TrueType and OpenType and the font names stay as + /// they are, and `document.info` and the saved report keep the English values. + #[test] + fn font_types_and_uses_show_in_the_interface_language() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + app.session.execute("text.create", &json!({"x": 10, "y": 20, "text": "Hi"})).unwrap(); + app.session.execute("text.create", &json!({"x": 10, "y": 50, "text": "Hi"})).unwrap(); + app.session.execute("text.create", &json!({"x": 10, "y": 80, "text": "Gone", "font": "Qx Absent Family"})).unwrap(); + let info = app.session.execute("document.info", &json!({})).unwrap(); + let rows = |info: &Value| shown_rows(info, "fonts"); + let english = vec![ + ("Qx Absent Family Regular".to_string(), "unknown type; 1 use".to_string()), + ("Source Sans 3 Regular".into(), "TrueType; 2 uses".into()), + ]; + assert_eq!(rows(&info), english); + let fonts = |app: &mut VectorcraftApp| { + crate::tests_labels::painted_text(app, |app, ui| { + set_pstate(ui.ctx(), "docinfo-category", "fonts".to_string()); + show(app, ui); + }) + }; + let Some(de) = crate::i18n::Lang::from_code("de") else { panic!("no German catalog") }; + crate::i18n::set_current(de); + let (german, painted) = (rows(&info), fonts(&mut app)); + let one_opentype = font_use_value(&json!({"type": "opentype", "uses": 1})); + let Some(ru) = crate::i18n::Lang::from_code("ru") else { panic!("no Russian catalog") }; + crate::i18n::set_current(ru); + let russian = [1, 3, 5].map(|n| font_use_value(&json!({"type": "truetype", "uses": n}))); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert_eq!(german[0], ("Qx Absent Family Regular".to_string(), "unbekannter Typ; 1 Verwendung".to_string())); + assert_eq!(german[1], ("Source Sans 3 Regular".to_string(), "TrueType; 2 Verwendungen".to_string())); + assert!(painted.contains("Source Sans 3 Regular") && painted.contains("TrueType; 2 Verwendungen"), "{painted}"); + assert_eq!(one_opentype.as_deref(), Some("OpenType; 1 Verwendung")); + assert_eq!(russian.map(Option::unwrap_or_default), ["TrueType; 1 использование", "TrueType; 3 использования", "TrueType; 5 использований"]); + // An unknown type id is shown as `document.info` gives the row. + assert_eq!(font_use_value(&json!({"type": "bitmap", "uses": 1})), None); + let report = + app.session.execute("document.info", &json!({"category": "fonts", "format": "text"})).unwrap()["text"].as_str().unwrap().to_string(); + assert!(report.contains("Source Sans 3 Regular: TrueType; 2 uses\n"), "{report}"); + } + /// Document shows the transparency settings with their values in the interface language (two /// custom grid colors as they are), and while the Artboard tool is the current tool the /// artboards it has selected, following its selection without an edit to the document. diff --git a/crates/ui-egui/src/panels/image_trace.rs b/crates/ui-egui/src/panels/image_trace.rs index 28c9fe9a78..0d4d326b76 100644 --- a/crates/ui-egui/src/panels/image_trace.rs +++ b/crates/ui-egui/src/panels/image_trace.rs @@ -241,9 +241,52 @@ fn view_label(v: TraceView) -> &'static str { TraceView::Outlines => tl!("Outlines"), TraceView::OutlinesWithSource => tl!("Outlines with Source Image"), TraceView::Source => tl!("Source Image"), + TraceView::Split => tl!("Split View"), } } +/// The Split view's divider of the one selected Image Trace object, when it shows that view. +fn selected_split(app: &VectorcraftApp) -> Option { + let st = app.session.active()?; + let [id] = st.selection.objects[..] else { return None }; + st.doc.node(id).filter(|n| is_trace(n) && n.trace_view() == TraceView::Split).map(Node::trace_split) +} + +/// The Divider row of the one selected Image Trace object in the Split view: how much of the +/// source image's width, from its left edge, shows the image. A drag is one undo step, and the +/// arrow keys move it a percent at a time. Nothing without such an object. +pub(crate) fn split_row(app: &mut VectorcraftApp, ui: &mut Ui) { + let Some(split) = selected_split(app) else { return }; + ui.horizontal(|ui| { + let label = widgets::dim_label(ui, tl!("Divider")); + // The canvas sets the divider to a ten-thousandth: a hundredth of a percent. + let mut pct = (split * 10_000.0).round() / 100.0; + // Clamping only edits keeps a divider between whole percents (a canvas drag, an agent's + // value) as it is while the panel shows: clamping always rounds it to the step each frame + // and reports a change. + let slider = egui::Slider::new(&mut pct, 0.0..=100.0).suffix("%").step_by(1.0).clamping(egui::SliderClamping::Edits); + let r = widgets::slider(ui, slider).labelled_by(label.id); + r.widget_info(|| egui::WidgetInfo::slider(ui.is_enabled(), pct, tl!("Divider"))); + if cfg!(test) { + ui.ctx().data_mut(|d| { + d.insert_temp(egui::Id::unique("trace-split-slider-id"), r.id); + d.insert_temp(egui::Id::unique("trace-split-slider-rect"), r.rect); + }); + } + let phase = if r.dragged() && !r.drag_stopped() { + widgets::Live::Dragging + } else if r.drag_stopped() || r.changed() { + widgets::Live::Released + } else { + widgets::Live::Idle + }; + if phase != widgets::Live::Idle { + let split = (pct / 100.0).clamp(0.0, 1.0); + crate::panels::live_run(app, "Image Trace View", "imageTrace.setView", json!({ "view": TraceView::Split.id(), "split": split }), phase); + } + }); +} + /// The View dropdown showing `current` → the view chosen. fn view_dropdown(ui: &mut Ui, current: TraceView, width: f32) -> Option { let labels = TraceView::ALL.map(view_label); @@ -684,6 +727,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } hold_source(app, ui.ctx(), any_trace && r.is_pointer_button_down_on()); }); + split_row(app, ui); ui.horizontal(|ui| { widgets::dim_label(ui, tl!("Mode:")); let mode = st.params["mode"].as_str().unwrap_or("blackAndWhite").to_string(); diff --git a/crates/ui-egui/src/panels/image_trace/tests.rs b/crates/ui-egui/src/panels/image_trace/tests.rs index af2ec39921..15cbffe9e9 100644 --- a/crates/ui-egui/src/panels/image_trace/tests.rs +++ b/crates/ui-egui/src/panels/image_trace/tests.rs @@ -635,6 +635,106 @@ fn holding_the_eye_button_shows_the_source_image_until_released() { frame(&mut app, &ctx, vec![press(false)]); } +/// In the Split view the panel shows a Divider slider that screen readers find by its name and +/// value; with the keyboard focus on it, → moves the divider a percent, one undo step a press. +/// It is not shown in any other view. +#[test] +fn the_divider_slider_names_and_moves_the_split_views_divider() { + use egui::accesskit::Role; + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = traced_app(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + ctx.enable_accesskit(); + let screen = Rect::from_min_size(Pos2::ZERO, vec2(280.0, 700.0)); + let slider_id = egui::Id::unique("trace-split-slider-id"); + let nodes = |app: &mut VectorcraftApp, events: Vec| { + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }, |ui| show(app, ui)); + out.textures_delta.clear(); + out.platform_output.accesskit_update.map(|u| u.nodes.into_iter().map(|(_, n)| n).collect::>()).unwrap_or_default() + }; + let divider = + |tree: &[egui::accesskit::Node]| tree.iter().find(|n| n.role() == Role::Slider && n.label() == Some("Divider")).map(|n| n.numeric_value()); + nodes(&mut app, vec![]); + assert_eq!(divider(&nodes(&mut app, vec![])), None, "no divider in the Tracing Result view"); + app.run("imageTrace.setView", json!({"view": "split", "split": 0.3})).unwrap(); + nodes(&mut app, vec![]); + assert_eq!(divider(&nodes(&mut app, vec![])), Some(Some(30.0))); + let id = ctx.data(|d| d.get_temp::(slider_id)).expect("the slider's id"); + ctx.memory_mut(|m| m.request_focus(id)); + nodes(&mut app, vec![]); + let steps = app.session.active().unwrap().history.undo.len(); + let right = Event::Key { key: egui::Key::ArrowRight, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; + nodes(&mut app, vec![right.clone()]); + assert_eq!(first_selected(&app).unwrap().trace_split(), 0.31); + nodes(&mut app, vec![right]); + assert_eq!(first_selected(&app).unwrap().trace_split(), 0.32); + assert_eq!(app.session.active().unwrap().history.undo.len(), steps + 2, "one undo step a press"); + assert_eq!(divider(&nodes(&mut app, vec![])), Some(Some(32.0))); +} + +/// A divider between whole percents (as a canvas drag or an agent sets it) stays as it is while +/// the panel shows, with no undo step; dragging the Divider slider sets it as one undo step. +#[test] +fn the_divider_slider_keeps_an_exact_divider_and_a_drag_is_one_undo_step() { + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = traced_app(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let screen = Rect::from_min_size(Pos2::ZERO, vec2(280.0, 700.0)); + let run = |app: &mut VectorcraftApp, events: Vec| { + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }, |ui| show(app, ui)); + out.textures_delta.clear(); + }; + app.run("imageTrace.setView", json!({"view": "split", "split": 0.3025})).unwrap(); + let steps = app.session.active().unwrap().history.undo.len(); + for _ in 0..3 { + run(&mut app, vec![]); + } + assert_eq!(first_selected(&app).unwrap().trace_split(), 0.3025, "the panel leaves the divider as it is"); + assert_eq!(app.session.active().unwrap().history.undo.len(), steps, "no undo step"); + let rect = ctx.data(|d| d.get_temp::(egui::Id::unique("trace-split-slider-rect"))).expect("the slider's rect"); + let at = |f: f32| Pos2::new(rect.left() + rect.width() * f, rect.center().y); + let button = |pos, pressed| Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + run(&mut app, vec![Event::PointerMoved(at(0.3)), button(at(0.3), true)]); + for f in [0.4, 0.6, 0.8] { + run(&mut app, vec![Event::PointerMoved(at(f))]); + } + run(&mut app, vec![button(at(0.8), false)]); + run(&mut app, vec![]); + let split = first_selected(&app).unwrap().trace_split(); + assert!(split > 0.6, "the drag moved the divider: {split}"); + assert_eq!(app.session.active().unwrap().history.undo.len(), steps + 1, "one undo step for the drag"); +} + +/// Properties shows the Divider slider of the selected Image Trace object in the Split view only, +/// with its name and value for screen readers. +#[test] +fn properties_shows_the_divider_slider_in_the_split_view() { + use egui::accesskit::Role; + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = traced_app(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + ctx.enable_accesskit(); + let screen = Rect::from_min_size(Pos2::ZERO, vec2(280.0, 700.0)); + let divider = |app: &mut VectorcraftApp| { + let mut found = None; + for _ in 0..2 { + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| { + crate::panels::properties::show(app, ui); + }); + out.textures_delta.clear(); + let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); + found = nodes.iter().find(|(_, n)| n.role() == Role::Slider && n.label() == Some("Divider")).map(|(_, n)| n.numeric_value()); + } + found + }; + assert_eq!(divider(&mut app), None, "no divider in the Tracing Result view"); + app.run("imageTrace.setView", json!({"view": "split", "split": 0.4})).unwrap(); + assert_eq!(divider(&mut app), Some(Some(40.0))); +} + /// With another object first in the selection, the eye button and the panel menu's Release /// act on the selected Image Trace object. #[test] diff --git a/crates/ui-egui/src/panels/layers.rs b/crates/ui-egui/src/panels/layers.rs index f714264b45..ac53a63c27 100644 --- a/crates/ui-egui/src/panels/layers.rs +++ b/crates/ui-egui/src/panels/layers.rs @@ -66,13 +66,14 @@ mod model; mod rows; mod thumbs; +pub(crate) use controls::new_layer_unlisted; use controls::{bottom_bar, filter_button}; pub use controls::{delete, expand, menu, set_filter}; pub(crate) use model::shown_name; pub use model::{Filter, ObjectKind, RowState}; #[cfg(test)] use model::{Row, list_rows, painted_name}; -use model::{push_rows, rows_of_doc}; +use model::{isolated_root, push_rows, rows_of_doc}; use rows::{drag_ghost, key, rename_id, resolve_click, row}; #[cfg(test)] use thumbs::THUMBS; @@ -171,6 +172,8 @@ struct View<'a> { column: Option, /// The row to scroll into view. reveal: Option, + /// In isolation mode, the isolated node: the top row, which nothing is dropped beside. + root: Option, /// Preferences › Units › Identify Objects By › XML ID. identify_xml_id: bool, } @@ -197,6 +200,17 @@ pub(crate) const ROW_KEYS: &str = "ly-keys"; pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let t = Tokens::get(ui.ctx()); show_thumbs_of(app.session.active().map(|st| st.uid)); + // In isolation mode only rows inside the isolated art stay highlighted, since the panel lists + // no others. + if let Some(st) = app.session.active_mut() + && let Some(root) = st.isolation.filter(|i| st.doc.node(*i).is_some()) + { + let doc = st.doc.clone(); + let inside = |r: &NodeId| doc.ancestry(*r).is_some_and(|a| a.contains(&root)); + if !st.layer_rows.iter().all(&inside) { + st.layer_rows.retain(&inside); + } + } let Some(st) = app.session.active() else { return }; // A rename belongs to the document it started in (node ids are per document): drop it when // another document shows, so it can't rename that document's node with the same id. @@ -237,16 +251,38 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { if rows.is_empty() && let Some(layer) = current { - let around = doc.ancestry(layer).unwrap_or_default().split_last().map(|(_, a)| a.to_vec()).unwrap_or_default(); - if let Some(st) = app.session.active_mut() { - for a in around { - st.layers_open.set(a, true); - } - } + open_around(app, &doc, &[layer]); reveal = Some(layer); } ui.data_mut(|d| d.insert_temp(key("seen-current"), current)); } + // Entering isolation mode opens the isolated row, now the top row, and scrolls to it; leaving it + // opens the rows around the row that was isolated and scrolls to that row. Each document's + // isolation mode is followed on its own: a document first shown in isolation mode opens its + // isolated row, and showing again a document whose isolation mode did not change opens nothing. + if let Some(uid) = app.session.active().map(|st| st.uid) { + let isolated = app.session.active().and_then(|st| st.isolation).filter(|i| doc.node(*i).is_some()); + let mut seen: std::collections::HashMap> = ui.data(|d| d.get_temp(key("seen-isolation"))).unwrap_or_default(); + let was = seen.get(&uid).copied(); + if was != Some(isolated) { + match isolated { + Some(root) => { + if let Some(st) = app.session.active_mut() { + st.layers_open.set(root, true); + } + reveal = Some(root); + } + None => { + if let Some(was) = was.flatten().filter(|i| doc.node(*i).is_some()) { + open_around(app, &doc, &[was]); + reveal = Some(was); + } + } + } + seen.insert(uid, isolated); + ui.data_mut(|d| d.insert_temp(key("seen-isolation"), seen)); + } + } // With Locate Selected Objects on, an object selected anew outside the panel (below). let located = newly_selected(app, ui).filter(|_| !highlighted); // Search All, and the Filter button at its right. @@ -265,7 +301,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { // search or the filter can leave it out): those rows open, and its row is revealed instead of // the row revealed above. Otherwise nothing opens. let located = located.filter(|id| { - app.session.active().is_some_and(|st| listed_when_opened(&doc, &st.layers_open, &app.ui.layers_panel, &query, &app.ui.layers_filter, *id)) + app.session + .active() + .is_some_and(|st| listed_when_opened(&doc, st.isolation, &st.layers_open, &app.ui.layers_panel, &query, &app.ui.layers_filter, *id)) }); if let Some(id) = located { open_around(app, &doc, &[id]); @@ -289,6 +327,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { h: app.ui.layers_panel.row(), column: ui.data(|d| d.get_temp(key("column"))), reveal, + root: st.isolation.and_then(|i| isolated_root(&doc, i)).map(|(n, ..)| n.id), identify_xml_id: app.session.prefs.identify_objects_by == "xmlId", }; let mut out = Out::default(); @@ -338,12 +377,14 @@ 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). The bottom layer itself goes there only as an Alt copy, - // which lands below it; moved, it would stay where it is (#8237). + // no row there to take the drop), except in isolation mode, where that layer is not listed. + // 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() + && view.root.is_none() && let Some(drag) = egui::DragAndDrop::payload::(ui.ctx()) && let LayersDrag::Rows(ids) = &*drag && let Some(bottom) = doc.layers.first() @@ -454,8 +495,9 @@ fn search_query(ctx: &egui::Context) -> String { /// `id`, as double-clicking the row's name does: Enter renames it (`layer.setProps`, one undo /// step), Escape leaves the name as it was. Without `id`, the row Rename names is the Layers /// panel's highlighted row when a row was clicked last, else the one selected object or group, -/// else the one highlighted row, else the current layer. Several of them, or a row the panel's -/// search, filter or Show Layers Only leaves out, is an error that opens nothing. +/// else the one highlighted row, else the current layer. Several of them, a row the panel's +/// search, filter or Show Layers Only leaves out, or in isolation mode an object outside the +/// isolated art, is an error that opens nothing. pub fn rename(app: &mut VectorcraftApp, p: &Value) -> Result { let ctx = app.ui_ctx.clone().ok_or("the Layers panel is not shown")?; let st = app.session.active().ok_or("no document open")?; @@ -483,7 +525,10 @@ pub fn rename(app: &mut VectorcraftApp, p: &Value) -> Result { }; let doc = st.doc.clone(); let node = doc.node(id).ok_or("no such layer or object")?; - if !listed_when_opened(&doc, &st.layers_open, &app.ui.layers_panel, &search_query(&ctx), &app.ui.layers_filter, id) { + if st.isolation.and_then(|i| isolated_root(&doc, i)).is_some_and(|(root, ..)| !doc.ancestry(id).is_some_and(|a| a.contains(&root.id))) { + return Err("the object is outside the isolated group".into()); + } + if !listed_when_opened(&doc, st.isolation, &st.layers_open, &app.ui.layers_panel, &search_query(&ctx), &app.ui.layers_filter, id) { return Err("the Layers panel's search, filter or Show Layers Only hides its row".into()); } let name = node.identify_label(app.session.prefs.identify_objects_by == "xmlId"); @@ -497,10 +542,19 @@ pub fn rename(app: &mut VectorcraftApp, p: &Value) -> Result { Ok(json!({ "id": id.0, "name": name })) } -/// Open the layers and groups around rows `ids`. +/// Open the layers and groups around rows `ids`. In isolation mode only those from the isolated +/// row down open, and nothing opens for a row outside it. fn open_around(app: &mut VectorcraftApp, doc: &Document, ids: &[NodeId]) { - let around: Vec = - ids.iter().flat_map(|r| doc.ancestry(*r).unwrap_or_default().split_last().map(|(_, a)| a.to_vec()).unwrap_or_default()).collect(); + let root = app.session.active().and_then(|st| st.isolation).filter(|i| doc.node(*i).is_some()); + let around: Vec = ids + .iter() + .flat_map(|r| { + let ancestry = doc.ancestry(*r).unwrap_or_default(); + let from = root.map_or(Some(0), |i| ancestry.iter().position(|a| *a == i)); + let parents = ancestry.split_last().map(|(_, a)| a.to_vec()).unwrap_or_default(); + from.map(|f| parents.into_iter().skip(f).collect::>()).unwrap_or_default() + }) + .collect(); if let Some(st) = app.session.active_mut() { for a in around { st.layers_open.set(a, true); @@ -509,20 +563,37 @@ fn open_around(app: &mut VectorcraftApp, doc: &Document, ids: &[NodeId]) { } /// Whether [`list_rows`] gives `id` a row once the layers and groups around it are open as well as -/// `open`. Only the rows of `id`'s top-level layer are listed. -fn listed_when_opened(doc: &Document, open: &OpenRows, opts: &PanelOptions, query: &str, filter: &Filter, id: NodeId) -> bool { +/// `open`, in isolation mode `isolation` (None: outside it). Only the rows of `id`'s top-level +/// layer, or in isolation mode those of the isolated row, are listed. +fn listed_when_opened( + doc: &Document, + isolation: Option, + open: &OpenRows, + opts: &PanelOptions, + query: &str, + filter: &Filter, + id: NodeId, +) -> bool { let Some(ancestry) = doc.ancestry(id) else { return false }; - let Some(layer) = doc.layers.iter().find(|l| ancestry.first() == Some(&l.id)) else { return false }; - if doc.mask_edit.is_some_and(|m| m.layer != layer.id) { - return false; - } let mut open = open.clone(); for a in ancestry.split_last().map(|(_, a)| a).unwrap_or_default() { open.set(*a, true); } let mut rows = vec![]; // Only object rows are looked for, so the guide rows are left out. - push_rows(layer, 0, false, (Color32::PLACEHOLDER, true), (&open, opts, query, filter, &[]), &mut rows); + let cx = (&open, opts, query, filter, &[][..]); + if let Some((root, clip_path, around)) = isolation.and_then(|i| isolated_root(doc, i)) { + if !ancestry.contains(&root.id) { + return false; + } + push_rows(root, 0, clip_path, around, cx, &mut rows); + } else { + let Some(layer) = doc.layers.iter().find(|l| ancestry.first() == Some(&l.id)) else { return false }; + if doc.mask_edit.is_some_and(|m| m.layer != layer.id) { + return false; + } + push_rows(layer, 0, false, (Color32::PLACEHOLDER, true), cx, &mut rows); + } rows.iter().any(|r| r.node.id == id && r.guide.is_none() && !r.spine) } diff --git a/crates/ui-egui/src/panels/layers/controls.rs b/crates/ui-egui/src/panels/layers/controls.rs index 573c18adb9..31f07c4929 100644 --- a/crates/ui-egui/src/panels/layers/controls.rs +++ b/crates/ui-egui/src/panels/layers/controls.rs @@ -71,9 +71,14 @@ pub(super) fn bottom_bar(app: &mut VectorcraftApp, ui: &mut Ui, view: &View, doc actions.push(("ui.layerDelete".into(), json!({}))); } } + // In isolation mode New Layer and New Sublayer are off while the layer they make would be + // outside the isolated art, where the panel does not list it. + let unlisted = |sublayer: bool, top: bool| app.session.active().is_some_and(|st| new_layer_unlisted(st, sublayer, top)); + let new_layer_ok = !unlisted(false, m.command && !m.alt); + let new_sublayer_ok = !unlisted(true, false); // Create New Layer: Alt asks for its options first, Ctrl/Cmd puts it on top of every layer, // and Ctrl/Cmd+Alt puts it directly below the current layer. - let new_layer = widgets::icon_button(&mut child, "file-plus", tl!("Create New Layer"), false, 24.0); + let new_layer = widgets::icon_button_enabled(&mut child, "file-plus", tl!("Create New Layer"), false, new_layer_ok, 24.0); if new_layer.clicked() { if m.alt && m.command { actions.push(("layer.new".into(), json!({"below": true}))); @@ -90,13 +95,15 @@ pub(super) fn bottom_bar(app: &mut VectorcraftApp, ui: &mut Ui, view: &View, doc let deletes = cmd == "ui.layerDelete"; if let Some(d) = button.dnd_release_payload::() { match &*d { + // A copy of the isolated node would go beside it, outside the isolated art. + LayersDrag::Rows(ids) if !deletes && view.root.is_some_and(|r| ids.contains(&r)) => {} LayersDrag::Rows(ids) => actions.push((cmd.into(), json!({"ids": ids.iter().map(|i| i.0).collect::>()}))), LayersDrag::Guides(guides) if deletes => actions.push(("guide.remove".into(), json!({"indexes": guides}))), _ => {} } } - let over = button.dnd_hover_payload::().is_some_and(|d| match *d { - LayersDrag::Rows(_) => true, + let over = button.dnd_hover_payload::().is_some_and(|d| match &*d { + LayersDrag::Rows(ids) => deletes || !view.root.is_some_and(|r| ids.contains(&r)), LayersDrag::Guides(_) => deletes, LayersDrag::Art => false, }) || (deletes && button.dnd_hover_payload::().is_some_and(|d| matches!(*d, PanelDrag::Appearance(_)))); @@ -106,7 +113,7 @@ pub(super) fn bottom_bar(app: &mut VectorcraftApp, ui: &mut Ui, view: &View, doc } // Create New Sublayer: Alt asks for its options first, and Ctrl/Cmd+Alt puts it under the // layer's contents. - if widgets::icon_button(&mut child, "plus", tl!("Create New Sublayer"), false, 24.0).clicked() { + if widgets::icon_button_enabled(&mut child, "plus", tl!("Create New Sublayer"), false, new_sublayer_ok, 24.0).clicked() { actions.push(match (m.alt, m.command) { (true, true) => ("layer.newSublayer".into(), json!({"bottom": true})), (true, false) => ("ui.newLayer".into(), json!({"sublayer": true})), @@ -119,7 +126,8 @@ pub(super) fn bottom_bar(app: &mut VectorcraftApp, ui: &mut Ui, view: &View, doc // 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() { + let locate_ok = !layers_only || super::rows::locate_layer_listed(doc, view.root); + if widgets::icon_button_enabled(&mut child, "search", locate, false, locate_ok, 24.0).clicked() { actions.push(("layer.locate".into(), json!({ "layersOnly": layers_only }))); } } @@ -131,12 +139,15 @@ type MenuItem<'a> = (&'a str, &'a str, Value, bool, bool); pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { let Some(st) = app.session.active() else { return }; let doc = st.doc.clone(); - let rows = st.highlighted_rows(); + let rows = listed_highlighted_rows(st); 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 targets: Vec = if rows.is_empty() { listed_current_layer(st).into_iter().collect() } else { rows.clone() }; + let (new_layer_ok, new_sublayer_ok) = (!new_layer_unlisted(st, false, false), !new_layer_unlisted(st, true, false)); + // A copy of the isolated node goes beside it, outside the isolated art. + let duplicate_ok = !targets.is_empty() && !st.isolation.is_some_and(|r| targets.contains(&r)); let one_container = match targets.as_slice() { [id] => doc.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. })), _ => false, @@ -153,9 +164,10 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { } }); let mut items: Vec> = vec![ - Some(("New Layer…", "ui.newLayer", json!({}), true, false)), - Some(("New Sublayer…", "ui.newLayer", json!({"sublayer": true}), current.is_some(), false)), - Some(("Duplicate Selection", "layer.duplicate", json!({}), !targets.is_empty(), false)), + Some(("New Layer…", "ui.newLayer", json!({}), new_layer_ok, false)), + Some(("New Sublayer…", "ui.newLayer", json!({"sublayer": true}), current.is_some() && new_sublayer_ok, false)), + // The rows listed, so no highlighted row outside the isolated art is copied. + Some(("Duplicate Selection", "layer.duplicate", json!({"ids": targets.iter().map(|i| i.0).collect::>()}), duplicate_ok, false)), Some(("Delete Selection", "ui.layerDelete", json!({}), !targets.is_empty(), false)), Some(("Options for Selection…", "ui.layerOptions", json!({}), !targets.is_empty(), false)), None, @@ -171,7 +183,7 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { items.extend([ None, Some(if layers_only { - ("Locate Layer", "layer.locate", json!({"layersOnly": true}), has_sel, false) + ("Locate Layer", "layer.locate", json!({"layersOnly": true}), has_sel && super::rows::locate_layer_listed(&doc, st.isolation), false) } else { ("Locate Object", "layer.locate", json!({}), has_sel, false) }), @@ -189,28 +201,29 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { None, Some(("Template", "layer.template", json!({}), !layers_in.is_empty(), template)), ]); - // Each pair reads by state: Hide Others while another layer shows, else Show All Layers. + // Each pair reads by state: Hide Others while another layer shows, else Show All Layers. In + // isolation mode the other layers are outside the isolated art, so the pairs are off. let any_other = |f: &dyn Fn(&Node) -> bool| others.iter().any(|l| f(l)); items.push(Some(if any_other(&|l| l.visible) { - ("Hide Others", "layer.hideOthers", json!({}), true, false) + ("Hide Others", "layer.hideOthers", json!({}), !isolated, false) } else { - ("Show All Layers", "layer.showAll", json!({}), all_layers.iter().any(|l| !l.visible), false) + ("Show All Layers", "layer.showAll", json!({}), !isolated && all_layers.iter().any(|l| !l.visible), false) })); items.push(Some(if any_other(&|l| !matches!(l.kind, NodeKind::Layer { preview: false, .. })) { - ("Outline Others", "layer.outlineOthers", json!({}), true, false) + ("Outline Others", "layer.outlineOthers", json!({}), !isolated, false) } else { ( "Preview All Layers", "layer.previewAll", json!({}), - all_layers.iter().any(|l| matches!(l.kind, NodeKind::Layer { preview: false, .. })), + !isolated && all_layers.iter().any(|l| matches!(l.kind, NodeKind::Layer { preview: false, .. })), false, ) })); items.push(Some(if any_other(&|l| !l.locked) { - ("Lock Others", "layer.lockOthers", json!({}), true, false) + ("Lock Others", "layer.lockOthers", json!({}), !isolated, false) } else { - ("Unlock All Layers", "layer.unlockAll", json!({}), all_layers.iter().any(|l| l.locked), false) + ("Unlock All Layers", "layer.unlockAll", json!({}), !isolated && all_layers.iter().any(|l| l.locked), false) })); items.push(None); let remembers = doc.paste_remembers_layers; @@ -291,10 +304,11 @@ fn save_selection_menu(app: &mut VectorcraftApp, ui: &mut Ui) { /// `ui.layerDelete {ids?|id?, doc?, confirmed?}`: Delete Selection as the Layers panel runs it (the /// trash button, rows dropped on it, the panel menu, Delete and Backspace), on the rows -/// `layer.delete` takes. When a layer or sublayer among them holds art (an object other than a +/// `layer.delete` takes (default: the highlighted rows, else the current layer; in isolation mode a +/// current layer outside the isolated art is an error). When a layer or sublayer among them holds art (an object other than a /// guide, hidden, locked and nested ones included), it asks first: OK deletes those rows, by id, in /// the same document (`doc`, its uid, with `confirmed`); with another document active then, nothing -/// is deleted. Other rows, and rows `layer.delete` refuses (an unknown id, every top-level layer), +/// is deleted. In isolation mode a row outside the isolated art is an error, and nothing is deleted. Other rows, and rows `layer.delete` refuses (an unknown id, every top-level layer), /// go to `layer.delete` at once. → `layer.delete`'s result, or null while the question is open pub fn delete(app: &mut VectorcraftApp, p: &Value) -> Result { let confirmed = crate::menus::opt_bool(p, "confirmed")?.unwrap_or(false); @@ -314,11 +328,24 @@ pub fn delete(app: &mut VectorcraftApp, p: &Value) -> Result { (Some(v), _) => v.as_array().and_then(|a| a.iter().map(row).collect()), (None, Some(v)) => row(v).map(|id| vec![id]), (None, None) => { - let rows = st.highlighted_rows(); + let rows = listed_highlighted_rows(st); + if rows.is_empty() && st.current_layer().is_some() && listed_current_layer(st).is_none() { + return Err("the object is outside the isolated group".into()); + } Some(if rows.is_empty() { st.current_layer().into_iter().collect() } else { rows }) } }; - let Some(ids) = ids.filter(|_| !confirmed) else { return app.run("layer.delete", Value::Object(rows)) }; + // Isolation mode can start while rows are dragged to the trash or while the question is open: + // nothing is deleted when a row is outside the isolated art. + if ids.as_ref().is_some_and(|ids| ids.iter().any(|id| !in_isolated_art(st, *id))) { + return Err("the object is outside the isolated group".into()); + } + let ids = match ids { + // Confirmed without rows given: the rows the panel lists, not every highlighted row. + Some(ids) if confirmed && rows.is_empty() => return app.run("layer.delete", json!({ "ids": ids.iter().map(|i| i.0).collect::>() })), + Some(ids) if !confirmed => ids, + _ => return app.run("layer.delete", Value::Object(rows)), + }; let listed: HashSet = ids.iter().copied().collect(); let mut roots = vec![]; row_roots(&st.doc.layers, &listed, &mut roots); @@ -335,6 +362,38 @@ pub fn delete(app: &mut VectorcraftApp, p: &Value) -> Result { Ok(Value::Null) } +/// Whether `id` is the isolated node or inside it: a row the panel can list. Always true outside +/// isolation mode. +fn in_isolated_art(st: &vectorcraft_engine::DocState, id: NodeId) -> bool { + let root = st.isolation.filter(|i| st.doc.node(*i).is_some()); + root.is_none_or(|r| st.doc.ancestry(id).is_some_and(|a| a.contains(&r))) +} + +/// The highlighted rows the panel lists: in isolation mode only those in the isolated art. +fn listed_highlighted_rows(st: &vectorcraft_engine::DocState) -> Vec { + st.highlighted_rows().into_iter().filter(|id| in_isolated_art(st, *id)).collect() +} + +/// The current layer, which the panel's commands act on when no row is highlighted. In isolation +/// mode it is None unless the layer is inside the isolated art, the only art the panel lists. +fn listed_current_layer(st: &vectorcraft_engine::DocState) -> Option { + st.current_layer().filter(|l| in_isolated_art(st, *l)) +} + +/// In isolation mode, whether the layer that New Layer (`sublayer` false; `top`: on top of every +/// layer) or New Sublayer makes would be outside the isolated art, where the panel does not list +/// it. New Layer goes beside the current layer, New Sublayer into the layer of the last highlighted +/// row, else into the current layer, as `layer.new` and `layer.newSublayer` place them. +pub(crate) fn new_layer_unlisted(st: &vectorcraft_engine::DocState, sublayer: bool, top: bool) -> bool { + let Some(root) = st.isolation.filter(|i| st.doc.node(*i).is_some()) else { return false }; + if sublayer { + let row = st.highlighted_rows().last().and_then(|r| st.doc.layer_containing(*r)); + !row.or(st.current_layer()).is_some_and(|p| in_isolated_art(st, p)) + } else { + top || !st.current_layer().is_some_and(|c| c != root && in_isolated_art(st, c)) + } +} + /// The rows among `nodes` (and the rows inside them) that are in `listed` and not inside another /// listed row, top-level first. fn row_roots<'a>(nodes: &'a [Arc], listed: &HashSet, out: &mut Vec<&'a Node>) { diff --git a/crates/ui-egui/src/panels/layers/model.rs b/crates/ui-egui/src/panels/layers/model.rs index 428149d776..201d65fb1d 100644 --- a/crates/ui-egui/src/panels/layers/model.rs +++ b/crates/ui-egui/src/panels/layers/model.rs @@ -217,6 +217,7 @@ pub(super) fn parse_names(p: &Value, key: &str, all: &[(T, struct RowsKey { uid: u64, revision: u64, + isolation: Option, open: u64, layers_only: bool, query: String, @@ -224,22 +225,49 @@ struct RowsKey { } /// The rows the panel shows, top down: the layers (only the opacity mask's while one is edited) -/// with the rows of the open ones inside them. A search or a filter shows every row whose name -/// contains `query` (lowercase) and that `filter` keeps, and every row holding one. -pub(super) fn list_rows(doc: &Document, open: &OpenRows, opts: &PanelOptions, query: &str, filter: &Filter) -> Vec { +/// with the rows of the open ones inside them. In isolation mode (`isolation`) only the isolated +/// layer, sublayer, group or object is listed, as the top row, with the open rows inside it. A +/// search or a filter shows every row whose name contains `query` (lowercase) and that `filter` +/// keeps, and every row holding one. +pub(super) fn list_rows(doc: &Document, isolation: Option, open: &OpenRows, opts: &PanelOptions, query: &str, filter: &Filter) -> Vec { let mask_layer = doc.mask_edit.map(|m| m.layer); // The ruler guides' ids by `guide.list` index, listed once for every layer. let guides: Vec = doc.ruler_guides().into_iter().filter_map(|g| g.id).collect(); let mut out = vec![]; + if let Some((root, clip_path, around)) = isolation.and_then(|i| isolated_root(doc, i)) { + push_rows(root, 0, clip_path, around, (open, opts, query, filter, &guides), &mut out); + return out; + } for l in doc.layers.iter().rev().filter(|l| mask_layer.is_none_or(|m| m == l.id)) { push_rows(l, 0, false, (Color32::PLACEHOLDER, true), (open, opts, query, filter, &guides), &mut out); } out } +/// The isolated node `id`, which heads the rows in isolation mode, with what [`push_rows`] takes +/// for it: whether it is its parent's clipping path, and the color of the layer holding it and +/// whether the layers and groups around it are visible. None when `id` is not in `doc`. +pub(super) fn isolated_root(doc: &Document, id: NodeId) -> Option<(&Arc, bool, (Color32, bool))> { + let path = doc.index_path(id)?; + let (first, rest) = path.split_first()?; + let mut cur = doc.layers.get(*first)?; + let (mut clip_path, mut colour, mut shown) = (false, Color32::PLACEHOLDER, true); + for &i in rest { + if let NodeKind::Layer { color, .. } = &cur.kind { + let [r, g, b] = color.rgb(); + colour = Color32::from_rgb(r, g, b); + } + shown &= cur.visible; + clip_path = i == 0 && cur.clips(); + cur = cur.children()?.get(i)?; + } + Some((cur, clip_path, (colour, shown))) +} + /// Add the rows of `n` and those open inside it to `out`; `(colour, shown)` are those of what holds /// it (the layer's colour, and whether it is visible). The last item of `cx` is the document's -/// ruler guide ids by `guide.list` index. +/// ruler guide ids by `guide.list` index. With Show Layers Only on, a group or object at `depth` 0, +/// the isolated row in isolation mode, keeps its own row. pub(super) fn push_rows( n: &Arc, depth: usize, @@ -250,7 +278,7 @@ pub(super) fn push_rows( ) { let (open_rows, opts, query, filter, all_guides) = cx; // A ruler guide node gets no object row: its layer lists the guide rows. - if n.is_ruler_guide() || (opts.layers_only && !n.is_layer()) { + if n.is_ruler_guide() || (opts.layers_only && depth > 0 && !n.is_layer()) { return; } let colour = match &n.kind { @@ -325,11 +353,12 @@ pub(super) fn push_rows( } /// The rows of the active document as [`list_rows`] lists them, listed again only when the -/// document, its open rows, the search, the filter or Show Layers Only changed. +/// document, isolation mode, its open rows, the search, the filter or Show Layers Only changed. pub(super) fn rows_of_doc(ui: &Ui, st: &vectorcraft_engine::DocState, opts: &PanelOptions, query: &str, filter: &Filter) -> Arc> { let now = RowsKey { uid: st.uid, revision: st.revision, + isolation: st.isolation, open: st.layers_open.generation(), layers_only: opts.layers_only, query: query.to_string(), @@ -341,7 +370,7 @@ pub(super) fn rows_of_doc(ui: &Ui, st: &vectorcraft_engine::DocState, opts: &Pan { return rows; } - let rows = Arc::new(list_rows(&st.doc, &st.layers_open, opts, query, filter)); + let rows = Arc::new(list_rows(&st.doc, st.isolation, &st.layers_open, opts, query, filter)); ui.data_mut(|d| d.insert_temp(id, (now, rows.clone()))); rows } diff --git a/crates/ui-egui/src/panels/layers/rows.rs b/crates/ui-egui/src/panels/layers/rows.rs index 1763210ef8..7dc9bc3d03 100644 --- a/crates/ui-egui/src/panels/layers/rows.rs +++ b/crates/ui-egui/src/panels/layers/rows.rs @@ -564,6 +564,42 @@ pub(super) fn row(ui: &mut Ui, view: &View, item: &Row, out: &mut Out) { /// The right-click context menu of row `n`. fn row_context_menu(ui: &mut Ui, view: &View, n: &Node, collect_ids: &[u64], out: &mut Out) { let is_multi = collect_ids.len() > 1; + if n.is_guide() { + // "Release Guide" / "Release Guides" + let rel_label = if is_multi { "Release Guides" } else { "Release Guide" }; + if widgets::menu_item(ui, rel_label, true, false) { + out.actions.push(("view.guides.release".into(), json!({ "ids": collect_ids }))); + ui.close(); + } + // "Duplicate" / "Duplicate Selection" + let dup_label = if is_multi { "Duplicate Selection" } else { "Duplicate" }; + if widgets::menu_item(ui, dup_label, true, false) { + out.actions.push(("layer.duplicate".into(), json!({ "ids": collect_ids }))); + ui.close(); + } + // "Delete Guide" / "Delete Guides" + let del_label = if is_multi { "Delete Guides" } else { "Delete Guide" }; + if widgets::menu_item(ui, del_label, true, false) { + out.actions.push(("layer.delete".into(), json!({ "ids": collect_ids }))); + ui.close(); + } + ui.separator(); + // Lock / Unlock + let any_unlocked = collect_ids.iter().filter_map(|&id| view.doc.node(NodeId(id))).any(|node| !node.locked); + let lock_label = if any_unlocked { "Lock" } else { "Unlock" }; + if widgets::menu_item(ui, lock_label, true, false) { + out.actions.push(("layer.setProps".into(), json!({ "ids": collect_ids, "locked": any_unlocked }))); + ui.close(); + } + // Hide / Show + let any_visible = collect_ids.iter().filter_map(|&id| view.doc.node(NodeId(id))).any(|node| node.visible); + let hide_label = if any_visible { "Hide" } else { "Show" }; + if widgets::menu_item(ui, hide_label, true, false) { + out.actions.push(("layer.setProps".into(), json!({ "ids": collect_ids, "visible": !any_visible }))); + ui.close(); + } + return; + } // "Layer Options…" / "Options for Selection…" / "Options…" let options_label = if is_multi { "Options for Selection…" @@ -587,7 +623,9 @@ fn row_context_menu(ui: &mut Ui, view: &View, n: &Node, collect_ids: &[u64], out } }; let dup_label = if is_multi { tl!("Duplicate Selection").to_string() } else { format!("{} \"{display}\"", tl!("Duplicate")) }; - if widgets::menu_item_name(ui, &dup_label, true, false) { + // A copy of the isolated node goes beside it, outside the isolated art. + let dup_enabled = !view.root.is_some_and(|r| collect_ids.contains(&r.0)); + if widgets::menu_item_name(ui, &dup_label, dup_enabled, false) { out.actions.push(("layer.duplicate".into(), json!({ "ids": collect_ids }))); ui.close(); } @@ -602,11 +640,13 @@ fn row_context_menu(ui: &mut Ui, view: &View, n: &Node, collect_ids: &[u64], out ui.close(); } ui.separator(); + // In isolation mode the other layers are outside the isolated art, so these pairs are off. + let isolated = view.root.is_some(); // Lock Others / Unlock All Layers { let (lock_cmd, lock_params, lock_enabled) = multi_others_action(view.doc, collect_ids, false); let lock_label = if lock_cmd == "layer.lockOthers" { "Lock Others" } else { "Unlock All Layers" }; - if widgets::menu_item(ui, lock_label, lock_enabled, false) { + if widgets::menu_item(ui, lock_label, lock_enabled && !isolated, false) { out.actions.push((lock_cmd, lock_params)); ui.close(); } @@ -615,7 +655,7 @@ fn row_context_menu(ui: &mut Ui, view: &View, n: &Node, collect_ids: &[u64], out { let (hide_cmd, hide_params, hide_enabled) = multi_others_action(view.doc, collect_ids, true); let hide_label = if hide_cmd == "layer.hideOthers" { "Hide Others" } else { "Show All Layers" }; - if widgets::menu_item(ui, hide_label, hide_enabled, false) { + if widgets::menu_item(ui, hide_label, hide_enabled && !isolated, false) { out.actions.push((hide_cmd, hide_params)); ui.close(); } @@ -623,7 +663,8 @@ fn row_context_menu(ui: &mut Ui, view: &View, n: &Node, collect_ids: &[u64], out ui.separator(); // 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) { + let locate_ok = !layers_only || locate_layer_listed(view.doc, view.root); + if widgets::menu_item(ui, if layers_only { "Locate Layer" } else { "Locate Object" }, locate_ok, false) { out.actions.push(("layer.locate".into(), json!({ "id": n.id.0, "layersOnly": layers_only }))); ui.close(); } @@ -706,6 +747,13 @@ fn layer_row(n: &Node, own: Option) -> NodeId { if n.is_ruler_guide() { own.unwrap_or(n.id) } else { n.id } } +/// Whether Locate Layer can highlight a row the panel lists: outside isolation mode, or with a +/// layer or sublayer isolated (`root`). An isolated group or object holds no layer row, and the +/// layer holding it is not listed. +pub(super) fn locate_layer_listed(doc: &Document, root: Option) -> bool { + root.is_none_or(|r| doc.node(r).is_some_and(Node::is_layer)) +} + /// The eye and lock columns of row `n` at `r`. fn eye_and_lock(ui: &mut Ui, view: &View, n: &Node, r: egui::Rect, out: &mut Out) { let t = &view.t; @@ -736,11 +784,17 @@ fn eye_and_lock(ui: &mut Ui, view: &View, n: &Node, r: egui::Rect, out: &mut Out icons::paint(ui, "lock", egui::Rect::from_center_size(lock.center(), vec2(12.0, 12.0)), t.text_disabled); } let m = ui.input(|i| i.modifiers); + // In isolation mode the other layers are outside the isolated art: Alt-clicks change nothing. + let isolated = view.root.is_some(); if er.clicked() { if m.alt && m.command { - out.actions.push(outline_others_action(view.doc, n)); + if !isolated { + out.actions.push(outline_others_action(view.doc, n)); + } } else if m.alt { - out.actions.push(others_action(view.doc, n, true)); + if !isolated { + out.actions.push(others_action(view.doc, n, true)); + } } else if m.command && n.is_layer() { // Ctrl/Cmd-click: Preview ↔ Outline for this layer. out.actions.push(("layer.setProps".into(), json!({"ids": [n.id.0], "preview": !preview}))); @@ -749,7 +803,9 @@ fn eye_and_lock(ui: &mut Ui, view: &View, n: &Node, r: egui::Rect, out: &mut Out } } if lr.clicked() && m.alt { - out.actions.push(others_action(view.doc, n, false)); + if !isolated { + out.actions.push(others_action(view.doc, n, false)); + } } else if lr.clicked() { out.actions.push(("layer.setProps".into(), json!({"ids": [n.id.0], "locked": !n.locked}))); } @@ -779,8 +835,11 @@ fn drop_target(ui: &Ui, view: &View, n: &Node, r: egui::Rect, indent: f32, open: LayersDrag::Rows(ids) => ids.clone(), LayersDrag::Art => view.sel.iter().copied().collect(), LayersDrag::Guides(guides) => { - // Guides go to the layer of the row (the row's own, for a layer). - if let Some(layer) = if n.is_layer() { Some(n.id) } else { doc.layer_containing(n.id) } { + // Guides go to the layer of the row (the row's own, for a layer); in isolation mode only + // to a layer inside the isolated art. + if let Some(layer) = if n.is_layer() { Some(n.id) } else { doc.layer_containing(n.id) } + && view.root.is_none_or(|r| doc.ancestry(layer).is_some_and(|a| a.contains(&r))) + { guide_drop(ui, view, guides, layer, r, resp, out); } return; @@ -806,6 +865,16 @@ fn drop_target(ui: &Ui, view: &View, n: &Node, r: egui::Rect, indent: f32, open: LayersDrag::Rows(_) if rel < 0.5 => Place::Above, LayersDrag::Rows(_) | LayersDrag::Guides(_) => Place::Below, }; + // In isolation mode the isolated row takes a drop only inside it, so nothing leaves the isolated + // art or lands beside it; held over its own row, it goes nowhere. + let place = if view.root == Some(n.id) { + if !inside || beside_itself { + return; + } + Place::Inside + } else { + place + }; // Beside a member of an Intertwine group (or a row in one) only what can be intertwined goes. if place != Place::Inside && doc.parent_of(n.id).is_some_and(|p| in_intertwine(doc, p)) diff --git a/crates/ui-egui/src/panels/layers/tests.rs b/crates/ui-egui/src/panels/layers/tests.rs index b0e4355d21..9e14cccb98 100644 --- a/crates/ui-egui/src/panels/layers/tests.rs +++ b/crates/ui-egui/src/panels/layers/tests.rs @@ -763,6 +763,358 @@ fn masks_underline_dashed_and_mask_editing_lists_only_the_mask() { assert!(after > before + 1, "a dashed underline: {before} → {after}"); } +// ---- isolation mode ---- + +/// The object rows [`list_rows`] lists for the active document, top down, with their depths. +fn listed_ids(app: &VectorcraftApp) -> Vec<(NodeId, usize)> { + let st = app.session.active().unwrap(); + let rows = list_rows(&st.doc, st.isolation, &st.layers_open, &PanelOptions::default(), "", &Filter::default()); + rows.iter().filter(|r| r.guide.is_none() && !r.spine).map(|r| (r.node.id, r.depth)).collect() +} + +/// In isolation mode the panel lists only the isolated sublayer, group or object, as the top row +/// with the open rows inside it; the other layers and groups are listed again when it ends. +#[test] +fn isolation_lists_only_the_isolated_art_and_exit_lists_every_layer_again() { + let (mut app, [layer, sub, g, b, a, c]) = nested(); + let run = |app: &mut VectorcraftApp, id: &str, p: serde_json::Value| app.session.execute(id, &p).unwrap(); + let top = NodeId(run(&mut app, "layer.new", json!({"top": true, "name": "Top"}))["id"].as_u64().unwrap()); + let all = vec![(top, 0), (layer, 0), (sub, 1), (g, 2), (b, 3), (a, 2), (c, 1)]; + assert_eq!(listed_ids(&app), all); + run(&mut app, "object.isolate", json!({"id": g.0})); + assert_eq!(listed_ids(&app), [(g, 0), (b, 1)], "the group and its art"); + run(&mut app, "object.exitIsolation", json!({})); + assert_eq!(listed_ids(&app), all, "every layer again"); + run(&mut app, "object.isolate", json!({"id": sub.0})); + assert_eq!(listed_ids(&app), [(sub, 0), (g, 1), (b, 2), (a, 1)], "the sublayer and its art"); + // Isolating an object inside lists that object alone. + run(&mut app, "object.isolate", json!({"id": a.0})); + assert_eq!(listed_ids(&app), [(a, 0)]); + run(&mut app, "object.exitIsolation", json!({})); + assert_eq!(listed_ids(&app), all); + // A closed isolated group lists its own row alone, and an isolated object that is gone leaves + // every layer listed. + run(&mut app, "object.isolate", json!({"id": g.0})); + app.session.active_mut().unwrap().layers_open.set(g, false); + assert_eq!(listed_ids(&app), [(g, 0)]); + app.session.active_mut().unwrap().isolation = Some(NodeId(999_999)); + assert_eq!(listed_ids(&app), [(top, 0), (layer, 0), (sub, 1), (g, 2), (a, 2), (c, 1)]); +} + +/// Entering isolation mode opens the isolated row and leaving it lists every row again; a drop +/// beside the isolated row or into the empty space under it moves nothing out of the isolated art. +#[test] +fn isolation_opens_the_isolated_row_and_keeps_drops_inside_it() { + let (mut app, [layer, sub, g, _, a, _]) = nested(); + let ctx = egui::Context::default(); + let parent = |app: &VectorcraftApp, id: NodeId| app.session.active().unwrap().doc.parent_of(id); + let (circles, _) = frame(&mut app, &ctx, vec![], false); + assert_eq!(circles.len(), 6); + app.session.active_mut().unwrap().layers_open.set(sub, false); + app.session.execute("object.isolate", &json!({"id": sub.0})).unwrap(); + // Rows: Sub, g, b, a. + let (circles, _) = frame(&mut app, &ctx, vec![], false); + assert_eq!(circles.len(), 4, "the sublayer's row opens"); + // Rectangle a onto the upper edge of the sublayer's row: not above it, outside the sublayer. + let primary = egui::PointerButton::Primary; + let dragged = drag_by(&mut app, &ctx, egui::pos2(150.0, circles[3].y), egui::pos2(150.0, circles[0].y - ROW_MEDIUM * 0.4), false, primary); + assert!(dragged, "the drag started"); + assert_eq!(parent(&app, a), Some(sub)); + // The sublayer into the empty space under the rows: it stays in Layer 1. + let (circles, _) = frame(&mut app, &ctx, vec![], false); + assert_eq!(circles.len(), 4); + let dragged = drag_by(&mut app, &ctx, egui::pos2(150.0, circles[0].y), egui::pos2(150.0, circles[3].y + 3.0 * ROW_MEDIUM), false, primary); + assert!(dragged, "the drag started"); + assert_eq!(parent(&app, sub), Some(layer)); + // Rectangle a onto the middle of the group's row: into it. + let (circles, _) = frame(&mut app, &ctx, vec![], false); + let at = |app: &VectorcraftApp, id: NodeId| circles[listed_ids(app).iter().position(|(n, _)| *n == id).unwrap()]; + let (from, to) = (at(&app, a), at(&app, g)); + drag(&mut app, &ctx, egui::pos2(150.0, from.y), egui::pos2(150.0, to.y), false); + assert_eq!(parent(&app, a), Some(g)); + app.session.execute("object.exitIsolation", &json!({"all": true})).unwrap(); + let (circles, _) = frame(&mut app, &ctx, vec![], false); + assert_eq!(circles.len(), 6, "every row again"); +} + +/// In isolation mode the rows outside the isolated art are no longer highlighted, so Delete and the +/// trash in the panel act only on rows it lists. +#[test] +fn isolation_drops_highlights_outside_the_isolated_art() { + let (mut app, [_, sub, _, b, _, c]) = nested(); + let ctx = egui::Context::default(); + app.session.execute("layer.highlight", &json!({"ids": [c.0, b.0], "mode": "set"})).unwrap(); + app.session.execute("object.isolate", &json!({"id": sub.0})).unwrap(); + frame(&mut app, &ctx, vec![], false); + assert_eq!(rows_of(&app), [b], "the rectangle on Layer 1, outside the sublayer, is let go"); +} + +/// In isolation mode Rename and the rows opened around a located object stay inside the isolated +/// row: an object outside it has no row to rename, and opens no rows. +#[test] +fn isolation_keeps_rename_and_locate_to_the_rows_listed() { + let (mut app, [layer, sub, g, b, _, c]) = nested(); + let ctx = egui::Context::default(); + app.ui_ctx = Some(ctx.clone()); + app.session.execute("object.isolate", &json!({"id": sub.0})).unwrap(); + let err = app.run("ui.rename", json!({"id": c.0})).unwrap_err(); + assert!(err.contains("the object is outside the isolated group"), "{err}"); + assert_eq!(app.run("ui.rename", json!({"id": b.0})).unwrap()["id"], json!(b.0)); + { + let st = app.session.active().unwrap(); + let listed = |id| listed_when_opened(&st.doc, st.isolation, &st.layers_open, &PanelOptions::default(), "", &Filter::default(), id); + assert_eq!([layer, sub, g, b, c].map(listed), [false, true, true, true, false]); + } + let st = app.session.active_mut().unwrap(); + st.layers_open.set(layer, false); + st.layers_open.set(g, false); + let doc = st.doc.clone(); + open_around(&mut app, &doc, &[c]); + open_around(&mut app, &doc, &[b]); + let open = &app.session.active().unwrap().layers_open; + assert!(open.contains(g), "the group inside the sublayer opens"); + assert!(!open.contains(layer), "the layer around the sublayer stays closed"); +} + +/// In isolation mode, with no row highlighted, Delete Selection and the trash do not delete the +/// current layer when it is outside the isolated art, where the panel does not list it. +#[test] +fn isolation_keeps_delete_to_the_rows_listed() { + let (mut app, [layer, sub, g, b, a, c]) = nested(); + app.session.execute("object.isolate", &json!({"id": g.0})).unwrap(); + // A row left highlighted outside the isolated group before the panel shows again. + let st = app.session.active_mut().unwrap(); + st.layer_rows = vec![c]; + let current = st.current_layer().unwrap(); + assert!([layer, sub].contains(¤t), "the current layer holds the isolated group"); + let err = app.run("ui.layerDelete", json!({})).unwrap_err(); + assert!(err.contains("the object is outside the isolated group"), "{err}"); + let doc = &app.session.active().unwrap().doc; + assert!([layer, sub, g, b, a, c].iter().all(|id| doc.node(*id).is_some()), "nothing was deleted"); + app.session.active_mut().unwrap().layer_rows = vec![b]; + app.run("ui.layerDelete", json!({})).unwrap(); + let doc = &app.session.active().unwrap().doc; + assert!(doc.node(b).is_none(), "a highlighted row inside the isolated group is deleted"); + assert!(doc.node(a).is_some() && doc.node(c).is_some()); +} + +/// In isolation mode New Layer and New Sublayer are off, and `ui.newLayer` is an error, while the +/// layer they make would be outside the isolated art; a sublayer of an isolated sublayer is listed. +#[test] +fn isolation_keeps_new_layers_to_the_rows_listed() { + let (mut app, [_, sub, g, ..]) = nested(); + app.session.execute("object.isolate", &json!({"id": g.0})).unwrap(); + let st = app.session.active().unwrap(); + assert_eq!([(false, false), (true, false), (false, true)].map(|(s, t)| new_layer_unlisted(st, s, t)), [true; 3]); + for p in [json!({}), json!({"sublayer": true})] { + let err = app.run("ui.newLayer", p).unwrap_err(); + assert!(err.contains("exit isolation mode first"), "{err}"); + } + assert!(app.ui.dialog.is_none()); + app.session.execute("object.exitIsolation", &json!({})).unwrap(); + app.session.execute("layer.setCurrent", &json!({"id": sub.0})).unwrap(); + app.session.execute("object.isolate", &json!({"id": sub.0})).unwrap(); + let st = app.session.active().unwrap(); + assert!(new_layer_unlisted(st, false, false), "a new layer would go beside the isolated sublayer"); + assert!(!new_layer_unlisted(st, true, false), "a new sublayer goes inside it"); + app.run("ui.newLayer", json!({"sublayer": true})).unwrap(); + assert!(app.ui.dialog.is_some()); + // Exit Isolation Mode on the sublayer isolates its layer, beside which a new layer would go. + app.session.execute("object.exitIsolation", &json!({})).unwrap(); + assert!(new_layer_unlisted(app.session.active().unwrap(), false, true)); + app.session.execute("object.exitIsolation", &json!({})).unwrap(); + assert!(!new_layer_unlisted(app.session.active().unwrap(), false, true)); +} + +/// With Show Layers Only on, an isolated group or object is still listed as the top row, without +/// the art inside it, and its row can be renamed. +#[test] +fn isolation_with_show_layers_only_lists_the_isolated_group_or_object() { + let (mut app, [_, sub, g, _, a, _]) = nested(); + let opts = PanelOptions { layers_only: true, ..Default::default() }; + let listed = |app: &VectorcraftApp| { + let st = app.session.active().unwrap(); + list_rows(&st.doc, st.isolation, &st.layers_open, &opts, "", &Filter::default()).iter().map(|r| r.node.id).collect::>() + }; + app.session.execute("object.isolate", &json!({"id": g.0})).unwrap(); + assert_eq!(listed(&app), [g], "the group's row, without its art"); + let st = app.session.active().unwrap(); + assert!(listed_when_opened(&st.doc, st.isolation, &st.layers_open, &opts, "", &Filter::default(), g)); + app.session.execute("object.isolate", &json!({"id": a.0})).unwrap(); + assert_eq!(listed(&app), [a]); + app.session.execute("object.isolate", &json!({"id": sub.0})).unwrap(); + assert_eq!(listed(&app), [sub], "a sublayer with no sublayers inside lists itself alone"); +} + +/// Click the item of the Layers panel menu whose text ends with `label`. +fn click_menu_item(app: &mut VectorcraftApp, ctx: &egui::Context, label: &str) { + let draw = |app: &mut VectorcraftApp, events: Vec| { + let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| menu(app, ui)); + out.textures_delta.clear(); + out.shapes.iter().find_map(|c| match &c.shape { + egui::Shape::Text(t) if t.galley.text().ends_with(label) => Some(t.visual_bounding_rect()), + _ => None, + }) + }; + let Some(r) = draw(app, vec![]) else { panic!("no menu item {label}") }; + for e in [egui::Event::PointerMoved(r.center()), button(r.center(), true), button(r.center(), false)] { + draw(app, vec![e]); + } +} + +/// In isolation mode the panel menu's Duplicate Selection copies only the rows the panel lists, Hide +/// Others is off, and with a group isolated so is Locate Layer, whose layer row is not listed. +#[test] +fn isolation_keeps_the_panel_menu_to_the_rows_listed() { + let (mut app, [layer, sub, g, b, _, c]) = nested(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let top = NodeId(app.session.execute("layer.new", &json!({"top": true, "name": "Top"})).unwrap()["id"].as_u64().unwrap()); + app.session.execute("object.isolate", &json!({"id": sub.0})).unwrap(); + // A row left highlighted outside the sublayer before the panel shows again. + app.session.active_mut().unwrap().layer_rows = vec![c, b]; + click_menu_item(&mut app, &ctx, "Duplicate Selection"); + let count = |app: &VectorcraftApp, id: NodeId| app.session.active().unwrap().doc.node(id).unwrap().children().unwrap().len(); + assert_eq!(count(&app, layer), 2, "rectangle c, outside the sublayer, is not copied"); + assert_eq!(count(&app, g), 2, "rectangle b is copied"); + click_menu_item(&mut app, &ctx, "Hide Others"); + assert!(app.session.active().unwrap().doc.node(top).unwrap().visible, "the layer outside the isolated art still shows"); + app.ui.layers_panel.layers_only = true; + app.session.execute("object.isolate", &json!({"id": g.0})).unwrap(); + app.session.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + app.session.active_mut().unwrap().layer_rows = vec![]; + click_menu_item(&mut app, &ctx, "Locate Layer"); + assert!(rows_of(&app).is_empty(), "the sublayer holding the group is not highlighted"); +} + +/// OK in Delete Selection's question deletes nothing when isolation mode started while it asked and +/// a row it asked about is outside the isolated art, and rows given outside it, as rows dropped on +/// the trash are, are not deleted either. +#[test] +fn isolation_keeps_a_confirmed_delete_to_the_rows_listed() { + let (mut app, [_, sub, g, _, a, c]) = nested(); + let uid = app.session.active().unwrap().uid; + app.session.active_mut().unwrap().layer_rows = vec![sub]; + assert!(app.run("ui.layerDelete", json!({})).unwrap().is_null(), "it asks first"); + app.session.execute("object.isolate", &json!({"id": g.0})).unwrap(); + let ok = json!({"ids": [sub.0], "doc": uid, "confirmed": true}); + let err = app.run("ui.layerDelete", ok.clone()).unwrap_err(); + assert!(err.contains("the object is outside the isolated group"), "{err}"); + assert!(app.session.active().unwrap().doc.node(sub).is_some(), "nothing was deleted"); + let err = app.run("ui.layerDelete", json!({"ids": [c.0]})).unwrap_err(); + assert!(err.contains("the object is outside the isolated group"), "{err}"); + assert!(app.session.active().unwrap().doc.node(c).is_some(), "the rectangle outside the group stays"); + // OK with no rows given deletes the highlighted rows the panel lists, inside the sublayer. + app.session.execute("object.isolate", &json!({"id": sub.0})).unwrap(); + app.session.active_mut().unwrap().layer_rows = vec![a, c]; + app.run("ui.layerDelete", json!({"doc": uid, "confirmed": true})).unwrap(); + let doc = &app.session.active().unwrap().doc; + assert!(doc.node(a).is_none() && doc.node(c).is_some(), "only the row inside the sublayer is deleted"); + app.session.execute("object.exitIsolation", &json!({"all": true})).unwrap(); + app.run("ui.layerDelete", ok).unwrap(); + assert!(app.session.active().unwrap().doc.node(sub).is_none()); +} + +/// A document first shown in isolation mode opens its isolated row, also when the panel showed +/// another document last; shown again with its isolation mode unchanged, it opens nothing. +#[test] +fn isolation_opens_the_isolated_row_of_each_document() { + let (mut app, [_, _, g, ..]) = nested(); + let ctx = egui::Context::default(); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + frame(&mut app, &ctx, vec![], false); + app.session.execute("document.activate", &json!({"index": 0})).unwrap(); + app.session.active_mut().unwrap().layers_open.set(g, false); + app.session.execute("object.isolate", &json!({"id": g.0})).unwrap(); + frame(&mut app, &ctx, vec![], false); + assert!(app.session.active().unwrap().layers_open.contains(g), "the isolated group's row opens"); + app.session.active_mut().unwrap().layers_open.set(g, false); + app.session.execute("document.activate", &json!({"index": 1})).unwrap(); + frame(&mut app, &ctx, vec![], false); + app.session.execute("document.activate", &json!({"index": 0})).unwrap(); + frame(&mut app, &ctx, vec![], false); + assert!(!app.session.active().unwrap().layers_open.contains(g), "a row closed in isolation mode stays closed"); +} + +/// In isolation mode an Alt-drag of the isolated row onto itself shows no place to drop and copies +/// nothing, and a guide dragged since before isolation mode began goes to no layer outside the +/// isolated art. +#[test] +fn isolation_keeps_drops_on_the_isolated_row_inside_it() { + let (mut app, [layer, sub, g, ..]) = nested(); + app.session.execute("guide.add", &json!({"vertical": true, "pos": 50, "layer": layer.0})).unwrap(); + let ctx = egui::Context::default(); + app.session.execute("object.isolate", &json!({"id": sub.0})).unwrap(); + // Rows: Sub, g, b, a. + let (circles, _) = frame(&mut app, &ctx, vec![], false); + assert_eq!(circles.len(), 4); + let nodes = |app: &VectorcraftApp| { + let mut n = 0; + app.session.active().unwrap().doc.walk(|_| n += 1); + n + }; + let before = nodes(&app); + // The boxes drawn around a row that would take the drop, in one frame with Alt held. + let boxes = |app: &mut VectorcraftApp, e: egui::Event| { + let events = vec![egui::Event::ModifiersChanged(egui::Modifiers::ALT), e]; + let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| show(app, ui)); + out.textures_delta.clear(); + let accent = Tokens::get(&ctx).accent; + out.shapes.iter().filter(|c| matches!(&c.shape, egui::Shape::Rect(r) if r.stroke.width == 2.0 && r.stroke.color == accent)).count() + }; + let (from, to) = (egui::pos2(150.0, circles[0].y - 6.0), egui::pos2(150.0, circles[0].y + 2.0)); + boxes(&mut app, egui::Event::PointerMoved(from)); + boxes(&mut app, button(from, true)); + boxes(&mut app, egui::Event::PointerMoved(from + vec2(0.0, 6.0))); + let shown = boxes(&mut app, egui::Event::PointerMoved(to)) + boxes(&mut app, egui::Event::PointerMoved(to + vec2(1.0, 0.0))); + assert!(egui::DragAndDrop::has_any_payload(&ctx), "the drag started"); + assert_eq!(shown, 0, "no box around the isolated row"); + boxes(&mut app, button(to, false)); + frame(&mut app, &ctx, vec![], false); + assert_eq!(nodes(&app), before, "nothing was copied"); + app.session.execute("object.exitIsolation", &json!({"all": true})).unwrap(); + // Rows: Layer 1, its guide (no target circle), Sub, g, b, a, c. + let (circles, _) = frame(&mut app, &ctx, vec![], false); + assert_eq!(circles.len(), 6); + let guide_row = egui::pos2(150.0, (circles[0].y + circles[1].y) / 2.0); + click_with(&mut app, &ctx, guide_row, egui::Modifiers::NONE); + frame(&mut app, &ctx, vec![button(guide_row, true)], false); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(guide_row + vec2(0.0, 6.0))], false); + // Over the group's row the guide would go to the sublayer holding it. + let over = egui::pos2(150.0, circles[2].y); + let shown = boxes(&mut app, egui::Event::PointerMoved(over)) + boxes(&mut app, egui::Event::PointerMoved(over + vec2(1.0, 0.0))); + assert!(shown > 0, "a box around the group's row"); + app.session.execute("object.isolate", &json!({"id": g.0})).unwrap(); + // Rows: g, b. + let (circles, _) = frame(&mut app, &ctx, vec![], false); + let over = egui::pos2(150.0, circles[0].y); + let shown = boxes(&mut app, egui::Event::PointerMoved(over)) + boxes(&mut app, egui::Event::PointerMoved(over + vec2(1.0, 0.0))); + assert!(egui::DragAndDrop::has_any_payload(&ctx), "the guide is still dragged"); + assert_eq!(shown, 0, "no box around the isolated group's row, outside which its sublayer is"); + frame(&mut app, &ctx, vec![button(over, false)], false); + frame(&mut app, &ctx, vec![], false); + assert_eq!(app.session.active().unwrap().doc.ruler_guides()[0].layer, Some(layer), "the guide stays on Layer 1"); +} + +/// In isolation mode Alt-clicking or Ctrl/Cmd+Alt-clicking an eye, or Alt-clicking a lock, changes +/// no layer outside the isolated art. +#[test] +fn isolation_keeps_alt_clicks_on_eyes_and_locks_inside_it() { + let (mut app, [_, sub, ..]) = nested(); + let top = NodeId(app.session.execute("layer.new", &json!({"top": true, "name": "Top"})).unwrap()["id"].as_u64().unwrap()); + app.session.execute("object.isolate", &json!({"id": sub.0})).unwrap(); + let ctx = egui::Context::default(); + let (circles, _) = frame(&mut app, &ctx, vec![], false); + let click = |app: &mut VectorcraftApp, at: egui::Pos2, mods: egui::Modifiers| click_with(app, &ctx, at, mods); + let (eye, lock) = (egui::pos2(12.0, circles[0].y), egui::pos2(37.0, circles[0].y)); + click(&mut app, eye, egui::Modifiers::ALT); + click(&mut app, eye, egui::Modifiers::ALT | egui::Modifiers::COMMAND); + click(&mut app, lock, egui::Modifiers::ALT); + let st = app.session.active().unwrap(); + let t = st.doc.node(top).unwrap(); + assert!(t.visible && !t.locked && !matches!(t.kind, NodeKind::Layer { preview: false, .. }), "the layer outside the isolated art is unchanged"); +} + // ---- rows at every depth (layers, sublayers, groups, objects) ---- /// Layer 1 holding rectangle `c` and a sublayer holding rectangle `a` and a group of @@ -901,7 +1253,8 @@ fn guide_rows_have_their_own_eye_and_lock() { }; let dimmed = |app: &VectorcraftApp| { let st = app.session.active().unwrap(); - list_rows(&st.doc, &st.layers_open, &PanelOptions::default(), "", &Filter::default()).iter().find(|r| r.guide.is_some()).unwrap().dim + let rows = list_rows(&st.doc, st.isolation, &st.layers_open, &PanelOptions::default(), "", &Filter::default()); + rows.iter().find(|r| r.guide.is_some()).unwrap().dim }; click_with(&mut app, &ctx, name, egui::Modifiers::NONE); assert_eq!(selected(&app), [guide]); @@ -1295,7 +1648,7 @@ fn kinds() -> (VectorcraftApp, HashMap<&'static str, NodeId>) { /// for a guide's row). fn listed(app: &VectorcraftApp, ids: &HashMap<&'static str, NodeId>, query: &str, filter: &Filter) -> Vec<&'static str> { let st = app.session.active().unwrap(); - let rows = list_rows(&st.doc, &st.layers_open, &PanelOptions::default(), query, filter); + let rows = list_rows(&st.doc, st.isolation, &st.layers_open, &PanelOptions::default(), query, filter); let name = |r: &Row| match r.guide { Some(_) => "ruler guide", None => ids.iter().find(|(_, id)| **id == r.node.id).map_or("?", |(name, _)| *name), @@ -2750,10 +3103,10 @@ fn a_blends_spine_is_a_row_below_its_keys_that_selects_the_blend() { run(&mut app, "select.none", json!({})); expand(&mut app, &json!({})).unwrap(); let st = app.session.active().unwrap(); - let rows = list_rows(&st.doc, &st.layers_open, &PanelOptions::default(), "", &Filter::default()); + let rows = list_rows(&st.doc, st.isolation, &st.layers_open, &PanelOptions::default(), "", &Filter::default()); let kinds: Vec<(u64, bool)> = rows.iter().map(|r| (r.node.id.0, r.spine)).collect(); assert_eq!(kinds[1..], [(blend.0, false), (b, false), (a, false), (blend.0, true)], "the spine row comes last in the blend"); - let rows = list_rows(&st.doc, &st.layers_open, &PanelOptions::default(), "rect", &Filter::default()); + let rows = list_rows(&st.doc, st.isolation, &st.layers_open, &PanelOptions::default(), "rect", &Filter::default()); assert!(!rows.iter().any(|r| r.spine), "no spine row while searching"); // Rows top down: the layer, the blend, both keys (with target circles), then the spine. let ctx = egui::Context::default(); @@ -2784,7 +3137,7 @@ fn ruler_guide_nodes_get_no_object_row() { let g = Node::new(doc.alloc_id(), NodeKind::RulerGuide { vertical: true, pos: 20.0, artboard: None }); doc.insert(Some(l), usize::MAX, g).unwrap(); } - let rows = list_rows(&st.doc, &st.layers_open, &PanelOptions::default(), "", &Filter::default()); + let rows = list_rows(&st.doc, st.isolation, &st.layers_open, &PanelOptions::default(), "", &Filter::default()); let ids: Vec = rows.iter().filter(|r| r.guide.is_none()).map(|r| r.node.id).collect(); assert_eq!(ids, [second, first, rect]); // Each guide is a guide row of its layer instead. @@ -2810,7 +3163,7 @@ fn guide_rows_list_by_index_whatever_the_node_order() { doc.move_node(first, Some(layer), usize::MAX).unwrap(); let kids: Vec = doc.layers[0].children().unwrap().iter().map(|c| c.id).collect(); assert_eq!(kids.last(), Some(&first)); - let rows = list_rows(&st.doc, &st.layers_open, &PanelOptions::default(), "", &Filter::default()); + let rows = list_rows(&st.doc, st.isolation, &st.layers_open, &PanelOptions::default(), "", &Filter::default()); let indexes: Vec = rows.iter().filter_map(|r| r.guide).collect(); assert_eq!(indexes, [2, 1, 0]); } @@ -3007,6 +3360,250 @@ fn context_menu_others_actions_sublayer_state_enables_all_commands() { assert!(lock_enabled, "locked sublayer enables Unlock All Layers"); } +/// Right-clicking a guide row presents specialized context menu actions: +/// Release Guide, Duplicate, Delete Guide, Lock/Unlock, Hide/Show. +#[test] +fn context_menu_on_guide_row_presents_specialized_actions() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let rect = app.session.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap(); + app.session.execute("select.set", &json!({"ids": [rect]})).unwrap(); + app.session.execute("view.guides.make", &json!({})).unwrap(); + let doc = &app.session.active().unwrap().doc; + let layer = doc.layers[0].id; + assert!(doc.node(NodeId(rect)).unwrap().is_guide(), "node was made a guide"); + + app.session.active_mut().unwrap().layers_open.set(layer, true); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + + let (circles, _) = frame(&mut app, &ctx, vec![], false); + assert_eq!(circles.len(), 2, "Layer 1 row and guide row"); + + // Secondary-click the guide row (bottom row) + let at = egui::pos2(150.0, circles[1].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); + } + + // Capture the open context menu shapes + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| show(&mut app, ui)); + out.textures_delta.clear(); + let labels: Vec = out + .shapes + .iter() + .filter_map(|c| match &c.shape { + egui::Shape::Text(t) => Some(t.galley.text().trim().to_string()), + _ => None, + }) + .collect(); + + assert!(labels.iter().any(|s| s == "Release Guide"), "Release Guide present in {labels:?}"); + assert!(labels.iter().any(|s| s == "Duplicate"), "Duplicate present in {labels:?}"); + assert!(labels.iter().any(|s| s == "Delete Guide"), "Delete Guide present in {labels:?}"); + assert!(labels.iter().any(|s| s == "Lock"), "Lock present in {labels:?}"); + assert!(labels.iter().any(|s| s == "Hide"), "Hide present in {labels:?}"); +} + +/// Clicking "Release Guide" dispatches the command and converts the guide to a path in one undo step. +#[test] +fn context_menu_release_guide_dispatches_and_is_one_undo_step() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let rect = app.session.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap(); + app.session.execute("select.set", &json!({"ids": [rect]})).unwrap(); + app.session.execute("view.guides.make", &json!({})).unwrap(); + let layer = app.session.active().unwrap().doc.layers[0].id; + app.session.active_mut().unwrap().layers_open.set(layer, true); + + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + + let (circles, _) = frame(&mut app, &ctx, vec![], false); + assert_eq!(circles.len(), 2); + + // Secondary-click the guide row + let at = egui::pos2(150.0, circles[1].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); + } + + // Find "Release Guide" position + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| show(&mut app, ui)); + out.textures_delta.clear(); + let release_pos = out + .shapes + .iter() + .find_map(|c| match &c.shape { + egui::Shape::Text(t) if t.galley.text().trim() == "Release Guide" => Some(t.pos + egui::vec2(10.0, 5.0)), + _ => None, + }) + .expect("Release Guide text position"); + + let undo_before = app.session.active().unwrap().history.undo.len(); + click_with(&mut app, &ctx, release_pos, egui::Modifiers::NONE); + + // Verify it is no longer a guide + let node = app.session.active().unwrap().doc.node(NodeId(rect)).unwrap(); + assert!(!node.is_guide(), "node is now a regular path, not a guide"); + let undo_after = app.session.active().unwrap().history.undo.len(); + assert_eq!(undo_after, undo_before + 1, "exactly one undo step added"); + + // Undo restores the guide + app.session.execute("edit.undo", &json!({})).unwrap(); + let node = app.session.active().unwrap().doc.node(NodeId(rect)).unwrap(); + assert!(node.is_guide(), "undo restores guide status"); +} + +/// Clicking "Duplicate" and "Delete Guide" in a guide row's context menu dispatches duplicate and delete. +#[test] +fn context_menu_guide_row_duplicate_and_delete() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let rect = app.session.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap(); + app.session.execute("select.set", &json!({"ids": [rect]})).unwrap(); + app.session.execute("view.guides.make", &json!({})).unwrap(); + let layer = app.session.active().unwrap().doc.layers[0].id; + app.session.active_mut().unwrap().layers_open.set(layer, true); + + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + + let (circles, _) = frame(&mut app, &ctx, vec![], false); + assert_eq!(circles.len(), 2); + + // 1. Right-click guide row and click "Duplicate" + let at = egui::pos2(150.0, circles[1].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 mut out = ctx.run_ui(egui::RawInput::default(), |ui| show(&mut app, ui)); + out.textures_delta.clear(); + let dup_pos = out + .shapes + .iter() + .find_map(|c| match &c.shape { + egui::Shape::Text(t) if t.galley.text().trim() == "Duplicate" => Some(t.pos + egui::vec2(10.0, 5.0)), + _ => None, + }) + .expect("Duplicate text position"); + click_with(&mut app, &ctx, dup_pos, egui::Modifiers::NONE); + + // Document now has 2 guides + let (circles2, _) = frame(&mut app, &ctx, vec![], false); + assert_eq!(circles2.len(), 3, "Layer and 2 guide rows"); + + // 2. Right-click the second guide row and click "Delete Guide" + let at2 = egui::pos2(150.0, circles2[2].y); + for e in [egui::Event::PointerMoved(at2), button_by(at2, true, right), button_by(at2, false, right)] { + frame(&mut app, &ctx, vec![e], false); + } + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| show(&mut app, ui)); + out.textures_delta.clear(); + let del_pos = out + .shapes + .iter() + .find_map(|c| match &c.shape { + egui::Shape::Text(t) if t.galley.text().trim() == "Delete Guide" => Some(t.pos + egui::vec2(10.0, 5.0)), + _ => None, + }) + .expect("Delete Guide text position"); + click_with(&mut app, &ctx, del_pos, egui::Modifiers::NONE); + + let (circles3, _) = frame(&mut app, &ctx, vec![], false); + assert_eq!(circles3.len(), 2, "Back to layer and 1 guide row"); +} + +/// Clicking "Lock"/"Unlock" and "Hide"/"Show" in a guide row's context menu toggles locked and visible. +#[test] +fn context_menu_guide_row_lock_and_hide() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let rect = app.session.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap(); + app.session.execute("select.set", &json!({"ids": [rect]})).unwrap(); + app.session.execute("view.guides.make", &json!({})).unwrap(); + let layer = app.session.active().unwrap().doc.layers[0].id; + app.session.active_mut().unwrap().layers_open.set(layer, true); + + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + + let (circles, _) = frame(&mut app, &ctx, vec![], false); + let at = egui::pos2(150.0, circles[1].y); + let right = egui::PointerButton::Secondary; + + // 1. Right-click -> menu shows "Lock" -> click "Lock" + 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 mut out = ctx.run_ui(egui::RawInput::default(), |ui| show(&mut app, ui)); + out.textures_delta.clear(); + let lock_pos = out + .shapes + .iter() + .find_map(|c| match &c.shape { + egui::Shape::Text(t) if t.galley.text().trim() == "Lock" => Some(t.pos + egui::vec2(10.0, 5.0)), + _ => None, + }) + .expect("Lock text position"); + click_with(&mut app, &ctx, lock_pos, egui::Modifiers::NONE); + assert!(app.session.active().unwrap().doc.node(NodeId(rect)).unwrap().locked, "guide is locked"); + + // 2. Right-click -> menu now shows "Unlock" -> click "Unlock" + 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 mut out = ctx.run_ui(egui::RawInput::default(), |ui| show(&mut app, ui)); + out.textures_delta.clear(); + let unlock_pos = out + .shapes + .iter() + .find_map(|c| match &c.shape { + egui::Shape::Text(t) if t.galley.text().trim() == "Unlock" => Some(t.pos + egui::vec2(10.0, 5.0)), + _ => None, + }) + .expect("Unlock text position"); + click_with(&mut app, &ctx, unlock_pos, egui::Modifiers::NONE); + assert!(!app.session.active().unwrap().doc.node(NodeId(rect)).unwrap().locked, "guide is unlocked"); + + // 3. Right-click -> menu shows "Hide" -> click "Hide" + 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 mut out = ctx.run_ui(egui::RawInput::default(), |ui| show(&mut app, ui)); + out.textures_delta.clear(); + let hide_pos = out + .shapes + .iter() + .find_map(|c| match &c.shape { + egui::Shape::Text(t) if t.galley.text().trim() == "Hide" => Some(t.pos + egui::vec2(10.0, 5.0)), + _ => None, + }) + .expect("Hide text position"); + click_with(&mut app, &ctx, hide_pos, egui::Modifiers::NONE); + assert!(!app.session.active().unwrap().doc.node(NodeId(rect)).unwrap().visible, "guide is hidden"); + + // 4. Right-click -> menu shows "Show" -> click "Show" + 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 mut out = ctx.run_ui(egui::RawInput::default(), |ui| show(&mut app, ui)); + out.textures_delta.clear(); + let show_pos = out + .shapes + .iter() + .find_map(|c| match &c.shape { + egui::Shape::Text(t) if t.galley.text().trim() == "Show" => Some(t.pos + egui::vec2(10.0, 5.0)), + _ => None, + }) + .expect("Show text position"); + click_with(&mut app, &ctx, show_pos, egui::Modifiers::NONE); + assert!(app.session.active().unwrap().doc.node(NodeId(rect)).unwrap().visible, "guide is visible again"); +} + /// One headless frame of the panel in a 300 × 600 window, returning every drawn text and its rect. fn frame_texts(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) -> Vec<(String, egui::Rect)> { let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::pos2(0.0, 0.0), vec2(300.0, 600.0))), events, ..Default::default() }; diff --git a/crates/ui-egui/src/panels/paragraph.rs b/crates/ui-egui/src/panels/paragraph.rs index de5864565a..99f11eec57 100644 --- a/crates/ui-egui/src/panels/paragraph.rs +++ b/crates/ui-egui/src/panels/paragraph.rs @@ -8,8 +8,7 @@ use egui::{Ui, vec2}; use serde_json::{Value, json}; use vectorcraft_doc::{ - Composer, HyphenationOptions, JustificationOptions, Justify, Kinsoku, KinsokuShoriType, Mojikumi, NodeKind, ParaDirection, ParaStyle, - SingleWordJustify, + Composer, HyphenationOptions, JustificationOptions, Justify, KinsokuShoriType, Mojikumi, NodeKind, ParaDirection, ParaStyle, SingleWordJustify, }; use super::character::{Metric, Shared, text_style}; @@ -794,14 +793,22 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { // Which characters may not start or end a line. ui.horizontal(|ui| { widgets::dim_label(ui, tl!("Kinsoku Set")); - let sets = [(tl!("None"), Kinsoku::None, "none"), (tl!("Hard"), Kinsoku::Hard, "hard"), (tl!("Soft"), Kinsoku::Soft, "soft")]; - let names = sets.map(|s| s.0); - let current = shared_para(app, |p| p.kinsoku).and_then(|k| sets.iter().find(|s| s.1 == k).map(|s| s.0)).unwrap_or(""); + let sets = [(tl!("None"), "None", "none"), (tl!("Hard"), "Hard", "hard"), (tl!("Soft"), "Soft", "soft")]; + let custom: Vec = app.session.active().map(|st| st.doc.kinsoku_sets.iter().map(|k| k.name.clone()).collect()).unwrap_or_default(); + let mut names: Vec<&str> = sets.iter().map(|s| s.0).collect(); + names.extend(custom.iter().map(String::as_str)); + names.push(tl!("Kinsoku Shori Settings…")); + let current = shared_kinsoku_name(app); + let current = current.as_deref().map_or("", |n| sets.iter().find(|s| s.1 == n).map_or(n, |s| s.0)); // Already translated: shown as they are. - if let Some(i) = widgets::dropdown_names(ui, "pa-kinsoku", current, &names, ui.available_width() - 4.0) - && let Some((_, _, key)) = sets.get(i) - { - format(app, json!({"kinsoku": key})); + if let Some(i) = widgets::dropdown_names(ui, "pa-kinsoku", current, &names, ui.available_width() - 4.0) { + if let Some((_, _, key)) = sets.get(i) { + format(app, json!({"kinsoku": key})); + } else if let Some(name) = custom.get(i - sets.len()) { + format(app, json!({"kinsoku": name})); + } else { + crate::menus::invoke(app, crate::dialogs::kinsoku_sets::COMMAND, json!({})); + } } }); } @@ -931,7 +938,23 @@ fn mojikumi_sets() -> [(&'static str, Mojikumi, &'static str); 6] { /// Bunri-Kinshi's menu item for the paragraphs the panel acts on ([`format`]): (available, checked). /// It is available when none of them has kinsoku None, and checked when every one of them has it. fn bunri_kinshi_item(app: &VectorcraftApp) -> (bool, bool) { - (shared_para(app, |p| p.kinsoku == Kinsoku::None) == Some(false), shared_para(app, |p| p.bunri_kinshi) == Some(true)) + (shared_para(app, ParaStyle::kinsoku_on) == Some(true), shared_para(app, |p| p.bunri_kinshi) == Some(true)) +} + +/// The Kinsoku set every paragraph the panel acts on ([`format`]) has, by name (None, Hard, Soft or +/// a custom set's), or `None` when they differ. +fn shared_kinsoku_name(app: &VectorcraftApp) -> Option { + let mut first: Option = None; + let mut differ = false; + visit_paragraphs(app, |p| match &first { + None => first = Some(p.kinsoku_name().to_string()), + Some(n) => differ |= n != p.kinsoku_name(), + }); + match first { + None => text_style(app).map(|(_, p)| p.kinsoku_name().to_string()), + Some(_) if differ => None, + n => n, + } } /// Bunri-Kinshi (Paragraph panel menu): a click turns it off for all the paragraphs the panel acts diff --git a/crates/ui-egui/src/panels/paragraph/tests.rs b/crates/ui-egui/src/panels/paragraph/tests.rs index aebdbbf1cf..ecc0dfffad 100644 --- a/crates/ui-egui/src/panels/paragraph/tests.rs +++ b/crates/ui-egui/src/panels/paragraph/tests.rs @@ -1,4 +1,5 @@ use super::*; +use vectorcraft_doc::Kinsoku; use vectorcraft_doc::Mojikumi; use vectorcraft_doc::NodeId; use vectorcraft_engine::Session; @@ -184,6 +185,25 @@ fn paragraph_mixed_kinsoku_and_mojikumi_show_blank_dropdowns() { assert_eq!(shared_para(&app, |p| p.mojikumi), Some(Mojikumi::LineEndHalf)); } +/// Kinsoku Set shows a custom set by its name, a blank when the paragraphs' sets differ, even when +/// each has Hard under it; Bunri-Kinshi is available with a custom set. +#[test] +fn kinsoku_set_shows_a_custom_set_by_name() { + let (mut app, id) = editing_text("A\nB\n"); + app.run("type.kinsokuSets.set", json!({"sets": [{"name": "Tight", "cannotStart": "」"}]})).unwrap(); + app.run("text.setFormat", json!({"id": id, "kinsoku": "hard"})).unwrap(); + app.run("text.setFormat", json!({"id": id, "start": 2, "end": 3, "kinsoku": "tight"})).unwrap(); + app.session.set_tool_option("selectAll", &json!(true)); + assert_eq!(shared_para(&app, |p| p.kinsoku), Some(Kinsoku::Hard)); + assert_eq!(shared_kinsoku_name(&app), None); + app.run("text.setFormat", json!({"id": id, "kinsoku": "Tight"})).unwrap(); + assert_eq!(shared_kinsoku_name(&app).as_deref(), Some("Tight")); + assert!(bunri_kinshi_item(&app).0); + app.run("text.setFormat", json!({"id": id, "kinsoku": "none"})).unwrap(); + assert_eq!(shared_kinsoku_name(&app).as_deref(), Some("None")); + assert!(!bunri_kinshi_item(&app).0); +} + /// The Mojikumi Set menu lists None, the four other predefined sets and Line-end Punctuation Half /// Width, each under its own label in every interface language. Each entry sets the selected /// paragraphs' set in one undo step and is shown as the current set; paragraphs with different diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index 02870c371f..52b74a5fb5 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -377,6 +377,7 @@ fn trace_section(app: &mut VectorcraftApp, ui: &mut Ui, preset: &str, view: vect crate::panels::image_trace::preset_dropdown(app, ui, preset, ui.available_width()); }); ui.horizontal(|ui| crate::panels::image_trace::view_row(app, ui, view, ui.available_width())); + crate::panels::image_trace::split_row(app, ui); if widgets::flat_button(ui, tl!("Image Trace"), ui.available_width()).clicked() { crate::panels::image_trace::open_settings(app); } diff --git a/crates/ui-egui/src/panels/separations.rs b/crates/ui-egui/src/panels/separations.rs index 2b3e112c5f..8d5dd13890 100644 --- a/crates/ui-egui/src/panels/separations.rs +++ b/crates/ui-egui/src/panels/separations.rs @@ -109,8 +109,8 @@ fn settings_section(app: &mut VectorcraftApp, ui: &mut Ui) { } /// The section's rows: the RGB and CMYK working spaces, intent, black point compensation, the RGB -/// and CMYK color management policies, Load Profile… and Gamut Check, and the profile the active -/// document is assigned. +/// and CMYK color management policies, the Ask boxes of Profile Mismatches and Missing Profiles, +/// Load Profile… and Gamut Check, and the profile the active document is assigned. fn settings_rows(app: &mut VectorcraftApp, ui: &mut Ui) { let st = cms::working_settings(); widgets::section_header(ui, tl!("Color Settings")); @@ -151,6 +151,22 @@ fn settings_rows(app: &mut VectorcraftApp, ui: &mut Ui) { } }); } + // Profile Mismatches and Missing Profiles: what opening and pasting ask about. + let asks: [(&str, &str, &str, bool); 3] = [ + ("askMismatchOpen", tl!("Profile Mismatches:"), tl!("Ask When Opening"), st.ask_mismatch_open), + ("askMismatchPaste", "", tl!("Ask When Pasting"), st.ask_mismatch_paste), + ("askMissingOpen", tl!("Missing Profiles:"), tl!("Ask When Opening"), st.ask_missing_open), + ]; + for (key, heading, label, on) in asks { + if !heading.is_empty() { + ui.label(heading); + } + ui.push_id(key, |ui| { + if widgets::check(ui, label, on, true) { + run(app, "edit.colorSettings", json!({ key: !on })); + } + }); + } ui.horizontal(|ui| { if widgets::flat_button(ui, tl!("Load Profile…"), 110.0).clicked() { // Its file dialog, shown off the UI thread, loads the profile when it answers. diff --git a/crates/ui-egui/src/panels/swatches.rs b/crates/ui-egui/src/panels/swatches.rs index da789a9944..41b42bfd60 100644 --- a/crates/ui-egui/src/panels/swatches.rs +++ b/crates/ui-egui/src/panels/swatches.rs @@ -212,6 +212,89 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { body(app, ui, TILE); } +/// The color group selected alone in the panel (what Color Group Options opens on), if any. +pub(crate) fn sole_selected_group(app: &VectorcraftApp) -> Option { + let (ctx, st) = (app.ui_ctx.as_ref()?, app.session.active()?); + if !body::selection_is_current(app, ctx) { + return None; + } + let mut sel: Vec = pstate(ctx, "swatch-selected"); + sel.retain(|n| n == REGISTRATION || st.doc.swatch_name_taken(n)); + actions::sole_group(app, &sel) +} + +/// Command `id` ran with `params` and replied `reply`: a color group that `swatch.renameGroup` +/// or `swatch.editGroup` renamed stays selected in the panel under its new name, and Shift-click still extends the +/// selection from it. Ungroup Color Group and Delete Swatch take the names they removed out of the +/// selection, so a group that later takes such a name is not selected in its place. The steps of a +/// `command.batch` are followed in order up to the first step that is not one of [`KEEPS_GROUPS`]: +/// such a step may switch documents or replace a group, and the selection stays as it is from there. +pub(crate) fn after_command(ctx: &egui::Context, id: &str, params: &Value, reply: &Value) { + let rename = |old: &str, new: Option<&str>| { + let mut sel: Vec = pstate(ctx, "swatch-selected"); + match new { + Some(new) => sel.iter_mut().filter(|n| *n == old).for_each(|n| *n = new.to_string()), + None => sel.retain(|n| n != old), + } + set_pstate(ctx, "swatch-selected", sel); + if pstate::(ctx, "swatch-anchor") == old { + set_pstate(ctx, "swatch-anchor", new.unwrap_or_default().to_string()); + } + }; + match id { + "swatch.renameGroup" | "swatch.editGroup" => { + if let (Some(old), Some(new)) = (params["group"].as_str(), reply["name"].as_str()) { + rename(old, Some(new)); + } + } + "swatch.ungroup" => { + if let Some(name) = params["name"].as_str() { + rename(name, None); + } + } + "swatch.delete" => { + let names = params["names"].as_array().map(Vec::as_slice).unwrap_or_default(); + for name in names.iter().chain(std::iter::once(¶ms["name"])).filter_map(Value::as_str) { + rename(name, None); + } + } + "command.batch" => { + let steps = params["commands"].as_array().map(Vec::as_slice).unwrap_or_default(); + let results = reply["results"].as_array().map(Vec::as_slice).unwrap_or_default(); + for (step, r) in steps.iter().zip(results) { + let id = step["command"].as_str().unwrap_or_default(); + if !KEEPS_GROUPS.contains(&id) { + break; + } + after_command(ctx, id, &step["params"], r); + } + } + _ => {} + } +} + +/// The batch steps the panel's selection follows: they act on the active document only, and +/// remove no color group except the ones they name. +const KEEPS_GROUPS: &[&str] = &[ + "swatch.renameGroup", + "swatch.ungroup", + "swatch.delete", + "swatch.new", + "swatch.newGroup", + "swatch.edit", + "swatch.move", + "swatch.merge", + "swatch.duplicate", + "swatch.addUsedColors", + "swatch.sortByKind", + "swatch.sortByName", + "swatch.editGroup", + "swatch.spotOptions", + "swatch.setSpot", + "swatch.list", + "swatch.unused", +]; + /// Item actions target the clicked swatch, independently of the paint or other selected chips. fn item_context_menu(app: &mut VectorcraftApp, ui: &Ui, resp: &Response, e: &Entry) { if e.is_folder() { diff --git a/crates/ui-egui/src/panels/swatches/actions.rs b/crates/ui-egui/src/panels/swatches/actions.rs index 1034f6207a..812a3ffb33 100644 --- a/crates/ui-egui/src/panels/swatches/actions.rs +++ b/crates/ui-egui/src/panels/swatches/actions.rs @@ -34,6 +34,14 @@ pub(super) fn selected_group(app: &VectorcraftApp, sel: &[String]) -> Option Option { + match sel { + [_] => selected_group(app, sel), + _ => None, + } +} + /// Edit or Apply Color Group: Recolor Artwork on colour group `group` (and the selected art). pub(super) fn edit_group(app: &mut VectorcraftApp, group: &str) { app.run("ui.recolorDialog", json!({ "group": group })).ok(); @@ -253,6 +261,12 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { { app.run("swatch.ungroup", json!({ "name": g })).ok(); } + let sole = sole_group(app, &selected); + if menu_item(ui, tl!("Color Group Options…"), sole.is_some(), false) + && let Some(g) = sole + { + app.run("ui.colorGroupOptions", json!({ "group": g })).ok(); + } if menu_item(ui, tl!("Select All Unused"), true, false) && let Ok(r) = app.run("swatch.unused", json!({})) { diff --git a/crates/ui-egui/src/panels/swatches/body.rs b/crates/ui-egui/src/panels/swatches/body.rs index bcecabb20c..944a245b9e 100644 --- a/crates/ui-egui/src/panels/swatches/body.rs +++ b/crates/ui-egui/src/panels/swatches/body.rs @@ -197,6 +197,14 @@ pub(super) fn focus_swatch(app: &VectorcraftApp, ui: &Ui, active: Option<&str>) active.filter(|_| changed).map(str::to_string) } +/// Whether the panel's selection is still the one it showed last: neither another document nor +/// other art has been selected since, which [`focus_swatch`] clears it for on the next frame. +pub(super) fn selection_is_current(app: &VectorcraftApp, ctx: &egui::Context) -> bool { + let art: Option = app.session.active().map(|st| (st.uid, st.selection.objects.iter().map(|id| id.0).collect())); + let (last_art, _): (Option>, Option) = pstate(ctx, "swatch-focus"); + last_art.is_none_or(|l| l == art) +} + /// The swatch the active paint comes from: a linked colour's global swatch (a tint's tint swatch /// when there is one), a process colour's swatch of that colour (a colour no swatch has: none, so /// text in a colour of its own highlights nothing), a gradient's gradient swatch, or None; nothing diff --git a/crates/ui-egui/src/panels/swatches/dnd.rs b/crates/ui-egui/src/panels/swatches/dnd.rs index d8cd2534ab..5cf2d06b23 100644 --- a/crates/ui-egui/src/panels/swatches/dnd.rs +++ b/crates/ui-egui/src/panels/swatches/dnd.rs @@ -62,8 +62,9 @@ pub(super) enum Drop { /// A paint from elsewhere (a Fill/Stroke proxy, a Recent Colors chip, a Color Guide color, the /// Gradient panel's thumbnail) dropped on row `target` (or between rows) becomes a swatch; with Alt held /// (`replace`) it replaces swatch `target` when that is of its kind and neither Registration - /// nor a tint swatch. - New { paint: Paint, target: Option, replace: bool }, + /// nor a tint swatch. With Cmd/Ctrl held (`spot`), a solid color other than Registration + /// becomes a spot color swatch. + New { paint: Paint, target: Option, replace: bool, spot: bool }, /// Art dragged off the canvas becomes a pattern swatch made of a copy of it (the art stays). Pattern { ids: Vec }, } @@ -71,15 +72,15 @@ pub(super) enum Drop { impl Drop { /// What releasing `d` before or `after` row `target` (`None`: at the end) does: move the rows /// it carries (with Alt held, `replace`, a swatch grabbed may replace `target`), make a swatch of - /// a paint dragged from elsewhere, or a pattern swatch of art dragged off the canvas (appearances: - /// nothing). - fn of(d: &PanelDrag, target: Option, after: bool, replace: bool) -> Option { + /// a paint dragged from elsewhere (a spot color with Cmd/Ctrl held, `spot`), or a pattern swatch + /// of art dragged off the canvas (appearances: nothing). + fn of(d: &PanelDrag, target: Option, after: bool, replace: bool, spot: bool) -> Option { match d { PanelDrag::Paint { rows: Some(r), .. } => { let with = (replace && !r.groups).then(|| r.grabbed.clone()); Some(Drop::Move { names: r.names.clone(), target, after, with }) } - PanelDrag::Paint { paint, .. } => Some(Drop::New { paint: paint.clone(), target, replace }), + PanelDrag::Paint { paint, .. } => Some(Drop::New { paint: paint.clone(), target, replace, spot }), PanelDrag::Art(ids) => Some(Drop::Pattern { ids: ids.iter().map(|id| id.0).collect() }), _ => None, } @@ -182,7 +183,8 @@ fn tile_drop(ui: &Ui, resp: &Response, e: &Entry, list: bool, ev: &mut TileEvent ui.painter().line_segment([pos2(x, r.top() - 1.0), pos2(x, r.bottom() + 1.0)], Stroke::new(2.0, t.accent)); } if resp.dnd_release_payload::().is_some() { - ev.drop = Drop::of(&d, Some(name.to_string()), after, crate::panels::alt_held(ui)); + let m = release_modifiers(ui); + ev.drop = Drop::of(&d, Some(name.to_string()), after, m.alt, m.command); } } @@ -194,10 +196,25 @@ pub(super) fn zone_input(ui: &Ui, zone: &Response, ev: &mut TileEvents) { ui.painter().rect_stroke(zone.rect, 0.0, Stroke::new(1.5, Tokens::get(ui.ctx()).accent), StrokeKind::Inside); } if zone.dnd_release_payload::().is_some() { - ev.drop = Drop::of(&d, None, false, false); + ev.drop = Drop::of(&d, None, false, false, release_modifiers(ui).command); } } +/// The modifiers (Alt; Cmd on macOS, Ctrl on Windows and Linux) held when the primary button was +/// released this frame, as the release event carries them, so a key let go later in the same frame +/// does not change the drop. Without such an event, the modifiers held at the end of the frame. +fn release_modifiers(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 colour group `name` is, or the one swatch `name` belongs to. pub(super) fn group_of(d: &Document, name: &str) -> Option { if d.swatch_groups.iter().any(|g| g.name == name) { @@ -253,9 +270,20 @@ fn replaces(d: &Document, with: &str, target: &str) -> bool { } } +/// `paint` as swatch params. A solid color other than Registration is sent as the color the drag +/// carries, not as its base swatch and tint, which the command would resolve again at the drop. +fn shown_color_params(paint: &Paint) -> Value { + match paint.color() { + Some(c) if !paint.is_registration() => crate::panels::swatch_paint_params(&Paint::solid(c)), + _ => crate::panels::swatch_paint_params(paint), + } +} + /// Run a drop on the panel: move the swatches, give the paint of a swatch Alt-dropped on another of /// its kind to that one, or make a swatch of the proxy's paint (a color dropped on a folder or a -/// grouped swatch joins that group). +/// grouped swatch joins that group; a color Cmd/Ctrl-dropped becomes a new spot color of the color +/// the drag shows, tints included). With Alt also held, a color dropped on a swatch it can replace +/// replaces that swatch's color with the color the drag shows and makes no spot color. pub(super) fn apply_drop(app: &mut VectorcraftApp, drop: Drop) { let Some(d) = app.session.active().map(|st| &st.doc) else { return }; let (cmd, params) = match drop { @@ -266,18 +294,24 @@ pub(super) fn apply_drop(app: &mut VectorcraftApp, drop: Drop) { Some(p) => ("swatch.move", p), None => return, }, - // Alt: an edited gradient (or colour) replaces the swatch it is dropped on. - Drop::New { paint, target: Some(t), replace: true } + // Alt: an edited gradient (or colour) replaces the swatch it is dropped on. With Cmd/Ctrl also + // held, a tint gives the color the drag shows; Alt alone sends the paint as it is. + Drop::New { paint, target: Some(t), replace: true, spot } if d.swatch(&t).is_some_and(|w| !w.is_reserved() && w.tint_of().is_none() && same_kind(&w.paint, &paint)) => { - ("swatch.edit", json!({"name": t, "paint": crate::panels::swatch_paint_params(&paint)})) + let p = if spot { shown_color_params(&paint) } else { crate::panels::swatch_paint_params(&paint) }; + ("swatch.edit", json!({"name": t, "paint": p})) } - Drop::New { paint, target, .. } => { - let mut p = crate::panels::swatch_paint_params(&paint); - if paint.color().is_some() - && let Some(g) = target.and_then(|t| group_of(d, &t)) - { - p["group"] = json!(g); + Drop::New { paint, target, spot, .. } => { + // Only a spot color needs a color of its own; other drops keep a tint's link to its base. + let mut p = if spot { shown_color_params(&paint) } else { crate::panels::swatch_paint_params(&paint) }; + if paint.color().is_some() { + if let Some(g) = target.and_then(|t| group_of(d, &t)) { + p["group"] = json!(g); + } + if spot && !paint.is_registration() { + p["spot"] = json!(true); + } } ("swatch.new", p) } diff --git a/crates/ui-egui/src/panels/swatches/tests.rs b/crates/ui-egui/src/panels/swatches/tests.rs index 56e6b664b1..e871c8d68b 100644 --- a/crates/ui-egui/src/panels/swatches/tests.rs +++ b/crates/ui-egui/src/panels/swatches/tests.rs @@ -1119,6 +1119,237 @@ fn a_color_alt_dropped_on_registration_becomes_a_new_swatch() { assert_eq!(d.swatch(REGISTRATION).map(|w| w.paint.clone()), registration, "Registration is unchanged"); } +/// Release a drag of `paint` from elsewhere at `at` with `m` held (a layout frame at `time`, the +/// release at `time + 0.5`). +fn drop_paint_at(app: &mut VectorcraftApp, ctx: &egui::Context, at: Pos2, paint: Paint, m: Modifiers, time: f64) { + egui::DragAndDrop::set_payload(ctx, PanelDrag::paint(paint)); + let release = Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: false, modifiers: m }; + frame_with(app, ctx, vec![Event::PointerMoved(at), release], m, time + 0.5, show); +} + +/// [`drop_paint_at`] on the tile of swatch `name`. +fn drop_paint_on(app: &mut VectorcraftApp, ctx: &egui::Context, name: &str, paint: Paint, m: Modifiers, time: f64) { + frame(app, ctx, vec![], time, show); + let at = tile_center(ctx, name); + drop_paint_at(app, ctx, at, paint, m, time); +} + +/// The newest ungrouped swatch. +fn newest_swatch(app: &VectorcraftApp) -> Swatch { + app.session.doc().unwrap().doc.swatches.last().cloned().expect("a swatch") +} + +/// How many swatches are spot colors. +fn spot_count(app: &VectorcraftApp) -> usize { + app.session.doc().unwrap().doc.swatches_iter().filter(|w| w.spot).count() +} + +/// A color Cmd/Ctrl-dropped on the panel becomes a global spot color swatch in the color's own +/// model, in the group it is dropped into, as one undo step that paints no art; without the +/// modifier it stays a process color. +#[test] +fn a_color_cmd_dropped_on_the_panel_becomes_a_spot_swatch() { + let mut app = app(); + let ctx = context(); + let (id, cmyk) = art_with_two_recent_colors(&mut app); + app.run("select.set", json!({"ids": [id.0]})).unwrap(); + frame(&mut app, &ctx, vec![], 0.0, show); + let art = fill_of(&app, id); + let undo = app.session.doc().unwrap().history.undo.len(); + // A proxy's RGB color onto a grouped swatch: a spot color in that group. + let rgb = Color::from_hex("#123456").unwrap(); + drop_paint_on(&mut app, &ctx, "Bright Red", Paint::solid(rgb), Modifiers::COMMAND, 1.0); + let d = &app.session.doc().unwrap().doc; + let made = names_of(&app, Some("Brights")).last().and_then(|n| d.swatch(n).cloned()).expect("a swatch"); + assert_eq!((made.paint, made.spot, made.global), (Paint::solid(rgb), true, true), "{}", app.ui.status); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1, "one undo step"); + assert_eq!(fill_of(&app, id), art, "the drop paints no art"); + // A CMYK Recent Colors chip dragged with Cmd/Ctrl in an RGB document: a CMYK spot color. + frame(&mut app, &ctx, vec![], 2.0, show); + let chip = recent_chip(&mut app, &ctx, 1, 2.5, show, false); + drag_with(&mut app, &ctx, chip, tile_center(&ctx, "Red"), Modifiers::COMMAND, 3.0); + let newest = newest_swatch(&app); + assert_eq!((newest.paint, newest.spot), (Paint::solid(cmyk), true), "{}", app.ui.status); + // Without the modifier: a process color. + let spots = spot_count(&app); + drop_paint_on(&mut app, &ctx, "Red", Paint::solid(Color::from_hex("#654321").unwrap()), Modifiers::NONE, 4.0); + let newest = newest_swatch(&app); + assert_eq!((newest.spot, newest.global, spot_count(&app)), (false, false, spots)); + // An RGB color in a CMYK document stays RGB; the document stays CMYK. + app.run("file.documentColorMode", json!({"mode": "cmyk"})).unwrap(); + drop_paint_on(&mut app, &ctx, "Red", Paint::solid(rgb), Modifiers::COMMAND, 5.0); + let newest = newest_swatch(&app); + assert_eq!((newest.paint, newest.spot), (Paint::solid(rgb), true), "{}", app.ui.status); + assert_eq!(app.session.doc().unwrap().doc.color_mode, vectorcraft_doc::ColorMode::Cmyk); + // Undo takes the spot color off. + let count = app.session.doc().unwrap().doc.swatches_iter().count(); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.doc().unwrap().doc.swatches_iter().count(), count - 1); +} + +/// A color Cmd/Ctrl-dropped in the list's empty space becomes an ungrouped spot color swatch. +#[test] +fn a_color_cmd_dropped_on_empty_list_space_becomes_a_spot_swatch() { + let mut app = app(); + let ctx = context(); + // Leave Red the only ungrouped swatch besides None and Registration, so the row it ends has + // empty space after it (each colour group starts a new row). + let d = &app.session.doc().unwrap().doc; + let others: Vec = names_of(&app, None).into_iter().filter(|n| n != "Red" && d.swatch(n).is_some_and(|w| !w.is_reserved())).collect(); + app.run("swatch.delete", json!({"names": others})).unwrap(); + frame(&mut app, &ctx, vec![], 0.0, show); + frame(&mut app, &ctx, vec![], 0.5, show); + let red = ctx.read_response(egui::Id::unique(("swatch-tile", "Red"))).expect("Red's tile").rect; + let at = pos2(red.right() + 60.0, red.center().y); + let d = &app.session.doc().unwrap().doc; + let names = d.swatches_iter().map(|w| w.name.clone()).chain(d.swatch_groups.iter().map(|g| g.name.clone())).chain([REGISTRATION.to_string()]); + for n in names { + let hit = ctx.read_response(egui::Id::unique(("swatch-tile", n.as_str()))).is_some_and(|r| r.rect.expand(8.0).contains(at)); + assert!(!hit, "{at:?} is clear of the tile of {n}"); + } + let count = d.swatches_iter().count(); + let rgb = Color::from_hex("#123456").unwrap(); + drop_paint_at(&mut app, &ctx, at, Paint::solid(rgb), Modifiers::COMMAND, 1.0); + let newest = newest_swatch(&app); + assert_eq!((newest.paint, newest.spot, newest.global), (Paint::solid(rgb), true, true), "{}", app.ui.status); + assert_eq!(app.session.doc().unwrap().doc.swatches_iter().count(), count + 1); + assert!(egui::DragAndDrop::payload::(&ctx).is_none()); +} + +/// Cmd/Ctrl makes a spot color only of a solid color dragged from elsewhere: a gradient and +/// Registration make no spot color, and swatches dragged within the panel move. +#[test] +fn a_cmd_drop_of_other_paints_or_rows_makes_no_spot_color() { + let mut app = app(); + let ctx = context(); + let spots = spot_count(&app); + let count = app.session.doc().unwrap().doc.swatches_iter().count(); + let stops = + vec![vectorcraft_color::GradientStop::new(0.0, Color::from_hex("#ff0000").unwrap()), vectorcraft_color::GradientStop::new(1.0, Color::WHITE)]; + let grad = Paint::Gradient(Box::new(vectorcraft_color::GradientPaint::new(vectorcraft_color::Gradient::new(GradientKind::Radial, stops)))); + drop_paint_on(&mut app, &ctx, "Red", grad, Modifiers::COMMAND, 1.0); + assert!(matches!(newest_swatch(&app).paint, Paint::Gradient(_)), "a gradient swatch: {}", app.ui.status); + assert_eq!((app.session.doc().unwrap().doc.swatches_iter().count(), spot_count(&app)), (count + 1, spots)); + drop_paint_on(&mut app, &ctx, "Red", Paint::registration(), Modifiers::COMMAND, 2.0); + assert_eq!(spot_count(&app), spots, "Registration makes no spot color"); + // A swatch dragged with Cmd/Ctrl within the panel moves. + frame(&mut app, &ctx, vec![], 3.0, show); + frame(&mut app, &ctx, vec![], 3.5, show); + let count = app.session.doc().unwrap().doc.swatches_iter().count(); + drag_with(&mut app, &ctx, tile_center(&ctx, "Lime"), tile_center(&ctx, "Red") - vec2(4.0, 0.0), Modifiers::COMMAND, 4.0); + let n = names_of(&app, None); + assert_eq!(n[n.iter().position(|x| x == "Red").unwrap() - 1], "Lime", "{}", app.ui.status); + assert_eq!((app.session.doc().unwrap().doc.swatches_iter().count(), spot_count(&app)), (count, spots)); +} + +/// A tint of a global color Cmd/Ctrl-dropped becomes a new spot color of the tinted color, and its +/// base stays as it is. With Alt also held, a color dropped on a solid swatch replaces it; dropped on +/// a tint swatch, which only takes a new name, it becomes a spot color. +#[test] +fn cmd_drops_of_tints_and_with_alt_follow_the_replacement_rule() { + let mut app = app(); + let ctx = context(); + app.run("swatch.edit", json!({"name": "Orange", "global": true})).unwrap(); + app.run("swatch.new", json!({"swatch": "Orange", "tint": 40})).unwrap(); + let orange = app.session.doc().unwrap().doc.swatch("Orange").cloned(); + let tint = app.session.doc().unwrap().doc.tint_paint("Orange", 0.4).expect("a tint of Orange"); + let shown = tint.color().expect("a color"); + drop_paint_on(&mut app, &ctx, "Red", tint, Modifiers::COMMAND, 1.0); + let newest = newest_swatch(&app); + assert_eq!((newest.paint, newest.spot, newest.global), (Paint::solid(shown), true, true), "{}", app.ui.status); + assert_eq!(app.session.doc().unwrap().doc.swatch("Orange").cloned(), orange, "Orange is unchanged"); + // Cmd/Ctrl and Alt on a solid swatch: it takes the color, and no swatch is added. + let count = app.session.doc().unwrap().doc.swatches_iter().count(); + let blue = Color::from_hex("#2040c0").unwrap(); + drop_paint_on(&mut app, &ctx, "Red", Paint::solid(blue), Modifiers::COMMAND | Modifiers::ALT, 2.0); + let red = app.session.doc().unwrap().doc.swatch("Red").cloned().expect("Red"); + assert_eq!((red.paint.color(), red.spot), (Some(blue), false), "{}", app.ui.status); + assert_eq!(app.session.doc().unwrap().doc.swatches_iter().count(), count); + // Cmd/Ctrl and Alt on a tint swatch: a new spot color, the tint swatch unchanged. + let green = Color::from_hex("#20a040").unwrap(); + drop_paint_on(&mut app, &ctx, "Orange 40%", Paint::solid(green), Modifiers::COMMAND | Modifiers::ALT, 3.0); + let newest = newest_swatch(&app); + assert_eq!((newest.paint, newest.spot), (Paint::solid(green), true), "{}", app.ui.status); + assert!(app.session.doc().unwrap().doc.swatch("Orange 40%").is_some_and(|w| w.tint_of().is_some())); +} + +/// A tint Cmd/Ctrl-dropped becomes a spot color of the color the drag showed, even when its base +/// swatch changes between the drag start and the drop. +#[test] +fn a_cmd_dropped_tint_makes_its_spot_from_the_captured_color() { + let mut app = app(); + let ctx = context(); + app.run("swatch.edit", json!({"name": "Orange", "global": true})).unwrap(); + app.run("swatch.new", json!({"swatch": "Orange", "tint": 40})).unwrap(); + let tint = app.session.doc().unwrap().doc.tint_paint("Orange", 0.4).expect("a tint of Orange"); + let shown = tint.color().expect("a color"); + app.run("swatch.edit", json!({"name": "Orange", "paint": {"color": "#2040c0"}})).unwrap(); + drop_paint_on(&mut app, &ctx, "Red", tint, Modifiers::COMMAND, 1.0); + let newest = newest_swatch(&app); + assert_eq!((newest.paint, newest.spot), (Paint::solid(shown), true), "{}", app.ui.status); +} + +/// A tint Cmd/Ctrl+Alt-dropped on a solid swatch gives it the color the drag showed, even when the +/// tint's base swatch changes between the drag start and the drop. +#[test] +fn a_tint_alt_dropped_on_a_swatch_replaces_it_with_the_captured_color() { + let mut app = app(); + let ctx = context(); + app.run("swatch.edit", json!({"name": "Orange", "global": true})).unwrap(); + app.run("swatch.new", json!({"swatch": "Orange", "tint": 40})).unwrap(); + let tint = app.session.doc().unwrap().doc.tint_paint("Orange", 0.4).expect("a tint of Orange"); + let shown = tint.color().expect("a color"); + app.run("swatch.edit", json!({"name": "Orange", "paint": {"color": "#2040c0"}})).unwrap(); + drop_paint_on(&mut app, &ctx, "Red", tint, Modifiers::COMMAND | Modifiers::ALT, 1.0); + let red = app.session.doc().unwrap().doc.swatch("Red").cloned().expect("Red"); + assert_eq!(red.paint.color(), Some(shown), "{}", app.ui.status); +} + +/// A tint Alt-dropped on a solid swatch without Cmd/Ctrl sends the tint as it is, so the swatch takes +/// the tint of its base swatch as the base is at the drop. +#[test] +fn a_tint_alt_dropped_without_cmd_keeps_the_tint_paint() { + let mut app = app(); + let ctx = context(); + app.run("swatch.edit", json!({"name": "Orange", "global": true})).unwrap(); + app.run("swatch.new", json!({"swatch": "Orange", "tint": 40})).unwrap(); + let tint = app.session.doc().unwrap().doc.tint_paint("Orange", 0.4).expect("a tint of Orange"); + let shown = tint.color().expect("a color"); + app.run("swatch.edit", json!({"name": "Orange", "paint": {"color": "#2040c0"}})).unwrap(); + let now = app.session.doc().unwrap().doc.tint_paint("Orange", 0.4).and_then(|p| p.color()).expect("a tint of Orange"); + assert_ne!(now, shown); + drop_paint_on(&mut app, &ctx, "Red", tint, Modifiers::ALT, 1.0); + let red = app.session.doc().unwrap().doc.swatch("Red").cloned().expect("Red"); + assert_eq!(red.paint.color(), Some(now), "{}", app.ui.status); +} + +/// A drop on the list follows the modifiers the release carries, not the ones held at the end of the +/// frame: Cmd/Ctrl let go after the release still makes a spot color, Cmd/Ctrl pressed after it does +/// not, and Alt let go after the release still replaces the swatch. +#[test] +fn a_drop_follows_the_modifiers_of_its_release() { + let mut app = app(); + let ctx = context(); + frame(&mut app, &ctx, vec![], 0.0, show); + let at = tile_center(&ctx, "Red"); + let drop = |app: &mut VectorcraftApp, color: &str, held: Modifiers, after: Modifiers, time: f64| { + egui::DragAndDrop::set_payload(&ctx, PanelDrag::paint(Paint::solid(Color::from_hex(color).unwrap()))); + let release = Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: false, modifiers: held }; + frame_with(app, &ctx, vec![Event::PointerMoved(at), release, Event::ModifiersChanged(after)], held, time, show); + }; + let spots = spot_count(&app); + drop(&mut app, "#30a050", Modifiers::COMMAND, Modifiers::NONE, 1.0); + assert_eq!(spot_count(&app), spots + 1, "Cmd/Ctrl held at the release: {}", app.ui.status); + let count = app.session.doc().unwrap().doc.swatches_iter().count(); + drop(&mut app, "#50a030", Modifiers::NONE, Modifiers::COMMAND, 2.0); + let d = &app.session.doc().unwrap().doc; + assert_eq!((d.swatches_iter().count(), spot_count(&app)), (count + 1, spots + 1), "{}", app.ui.status); + drop(&mut app, "#2040c0", Modifiers::ALT, Modifiers::NONE, 3.0); + let d = &app.session.doc().unwrap().doc; + assert_eq!(d.swatches_iter().count(), count + 1, "Alt held at the release adds no swatch: {}", app.ui.status); + assert_eq!(d.swatch("Red").and_then(|w| w.paint.color()), Color::from_hex("#2040c0")); +} + /// A Recent Colors chip of the Color panel dragged onto the Swatches panel becomes a swatch; a click /// on it still paints the selected art. #[test] @@ -1421,6 +1652,140 @@ fn click_menu_item(app: &mut VectorcraftApp, ctx: &egui::Context, label: &str) { menu_frame(app, ctx, vec![button(false)]); } +/// The panel menu's Color Group Options… opens on the selected color group when that group is the +/// whole selection; with nothing selected, a swatch alone, or a swatch or a second group beside the +/// group, it opens nothing. After OK, and after `swatch.renameGroup` run on its own or in a batch, +/// the group stays selected under its new name. +#[test] +fn color_group_options_opens_on_a_sole_selected_group() { + let mut app = app(); + let ctx = context(); + for sel in [vec![], vec!["Red"], vec!["Brights", "Red"], vec!["Brights", "Grays"]] { + set_pstate(&ctx, "swatch-selected", sel.iter().map(|s| s.to_string()).collect::>()); + click_menu_item(&mut app, &ctx, "Color Group Options…"); + assert!(app.ui.dialog.is_none(), "{sel:?}"); + } + set_pstate(&ctx, "swatch-selected", vec!["Grays".to_string()]); + click_menu_item(&mut app, &ctx, "Color Group Options…"); + let d = app.ui.dialog.as_ref().expect("Color Group Options opens"); + assert_eq!((d.kind.as_str(), d.str("__group").as_str()), (crate::dialogs::color_group_options::KIND, "Grays")); + // OK keeps the renamed group selected, so the item opens on it again. + app.ui_ctx = Some(ctx.clone()); + set_pstate(&ctx, "swatch-anchor", "Grays".to_string()); + app.ui.dialog.as_mut().unwrap().fields.insert("name".into(), json!("Neutrals")); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(selected(&ctx), ["Neutrals"]); + assert_eq!(pstate::(&ctx, "swatch-anchor"), "Neutrals", "Shift-click extends from the renamed group"); + click_menu_item(&mut app, &ctx, "Color Group Options…"); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.str("__group")).as_deref(), Some("Neutrals")); + crate::dialogs::cancel(&mut app); + // The command run on its own, and as batch steps, keeps the selection the same way. + app.run("swatch.renameGroup", json!({"group": "Neutrals", "name": "Stone"})).unwrap(); + assert_eq!((selected(&ctx), pstate::(&ctx, "swatch-anchor")), (vec!["Stone".to_string()], "Stone".to_string())); + let steps = json!([ + {"command": "swatch.renameGroup", "params": {"group": "Stone", "name": "Slate"}}, + {"command": "swatch.renameGroup", "params": {"group": "Slate", "name": "Ash"}}, + ]); + app.run("command.batch", json!({"commands": steps})).unwrap(); + assert_eq!((selected(&ctx), pstate::(&ctx, "swatch-anchor")), (vec!["Ash".to_string()], "Ash".to_string())); +} + +/// Color Group Options from the command palette (no `group`) opens on the color group selected +/// alone in the panel; without one it opens nothing and reports the missing group. +#[test] +fn color_group_options_without_a_group_opens_on_the_selected_group() { + let mut app = app(); + let ctx = context(); + app.ui_ctx = Some(ctx.clone()); + for sel in [vec![], vec!["Red"], vec!["Brights", "Grays"]] { + set_pstate(&ctx, "swatch-selected", sel.iter().map(|s| s.to_string()).collect::>()); + assert!(app.run("ui.colorGroupOptions", json!({})).is_err() && app.ui.dialog.is_none(), "{sel:?}"); + } + set_pstate(&ctx, "swatch-selected", vec!["Grays".to_string()]); + app.run("ui.colorGroupOptions", json!({})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.str("__group")).as_deref(), Some("Grays")); + crate::dialogs::cancel(&mut app); + // The panel showed the selection in this document; another document made active since then + // does not take it. + let uid = app.session.active().unwrap().uid; + set_pstate(&ctx, "swatch-focus", (Some(Some((uid, Vec::::new()))), None::)); + app.run("ui.colorGroupOptions", json!({})).unwrap(); + crate::dialogs::cancel(&mut app); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + assert!(app.run("ui.colorGroupOptions", json!({})).is_err() && app.ui.dialog.is_none(), "another document"); +} + +/// Renames in a batch move the selection to another group neither after an Ungroup of the +/// selected group nor in another document; a batch step that keeps the groups (Sort by Kind) does +/// not stop the selection from following a rename, and Delete Swatch on the group ends it. +#[test] +fn a_batch_moves_the_selection_only_with_its_group() { + let mut app = app(); + let ctx = context(); + app.ui_ctx = Some(ctx.clone()); + let select = |sel: &str| { + set_pstate(&ctx, "swatch-selected", vec![sel.to_string()]); + set_pstate(&ctx, "swatch-anchor", sel.to_string()); + }; + select("Brights"); + let steps = json!([ + {"command": "swatch.ungroup", "params": {"name": "Brights"}}, + {"command": "swatch.renameGroup", "params": {"group": "Grays", "name": "Brights"}}, + {"command": "swatch.renameGroup", "params": {"group": "Brights", "name": "Vivid"}}, + ]); + app.run("command.batch", json!({"commands": steps})).unwrap(); + assert_eq!((selected(&ctx), pstate::(&ctx, "swatch-anchor")), (Vec::::new(), String::new()), "Ungroup ends the selection"); + // A step that keeps the groups, then a rename of the selected group. + select("Vivid"); + let steps = json!([ + {"command": "swatch.sortByKind", "params": {}}, + {"command": "swatch.renameGroup", "params": {"group": "Vivid", "name": "Bold"}}, + ]); + app.run("command.batch", json!({"commands": steps})).unwrap(); + assert_eq!((selected(&ctx), pstate::(&ctx, "swatch-anchor")), (vec!["Bold".to_string()], "Bold".to_string())); + app.run("swatch.delete", json!({"name": "Bold"})).unwrap(); + assert_eq!((selected(&ctx), pstate::(&ctx, "swatch-anchor")), (Vec::::new(), String::new()), "Delete Swatch ends the selection"); + // Brights selected in one new document, renamed in another. + for _ in 0..2 { + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + } + app.run("document.activate", json!({"index": 1})).unwrap(); + select("Brights"); + let steps = json!([ + {"command": "document.activate", "params": {"index": 2}}, + {"command": "swatch.renameGroup", "params": {"group": "Brights", "name": "Vivid"}}, + {"command": "document.activate", "params": {"index": 1}}, + ]); + app.run("command.batch", json!({"commands": steps})).unwrap(); + assert_eq!((selected(&ctx), pstate::(&ctx, "swatch-anchor")), (vec!["Brights".to_string()], "Brights".to_string())); +} + +/// Sort by Name keeps the groups, so a rename after it in a batch still moves the selection, and +/// Edit Color Group's `rename` moves it as Color Group Options does, alone or in a batch. +#[test] +fn the_selection_follows_sorting_and_group_edits() { + let mut app = app(); + let ctx = context(); + app.ui_ctx = Some(ctx.clone()); + set_pstate(&ctx, "swatch-selected", vec!["Brights".to_string()]); + set_pstate(&ctx, "swatch-anchor", "Brights".to_string()); + let follows = |name: &str| (vec![name.to_string()], name.to_string()); + let steps = json!([ + {"command": "swatch.sortByName", "params": {}}, + {"command": "swatch.renameGroup", "params": {"group": "Brights", "name": "Vivid"}}, + ]); + app.run("command.batch", json!({"commands": steps})).unwrap(); + assert_eq!((selected(&ctx), pstate::(&ctx, "swatch-anchor")), follows("Vivid"), "Sort by Name"); + app.run("swatch.editGroup", json!({"group": "Vivid", "colors": ["#ff0000"], "rename": "Bold"})).unwrap(); + assert_eq!((selected(&ctx), pstate::(&ctx, "swatch-anchor")), follows("Bold"), "Edit Color Group"); + let steps = json!([ + {"command": "swatch.editGroup", "params": {"group": "Bold", "colors": ["#00ff00"], "rename": "Loud"}}, + {"command": "swatch.renameGroup", "params": {"group": "Loud", "name": "Calm"}}, + ]); + app.run("command.batch", json!({"commands": steps})).unwrap(); + assert_eq!((selected(&ctx), pstate::(&ctx, "swatch-anchor")), follows("Calm"), "Edit Color Group in a batch"); +} + /// The panel menu's Show Recent Colors hides and shows the panel's Recent Colors row (#6617): /// checked by default, applied colors still join the list while the row is hidden, and the Color /// panel keeps its own row and setting. diff --git a/crates/ui-egui/src/panels/symbols.rs b/crates/ui-egui/src/panels/symbols.rs index 84c138b8a8..bc8637989f 100644 --- a/crates/ui-egui/src/panels/symbols.rs +++ b/crates/ui-egui/src/panels/symbols.rs @@ -25,6 +25,16 @@ use crate::menus::Item; use crate::theme::Tokens; use crate::widgets::{self, PanelDrag, menu_item}; +/// The largest side of a symbol thumbnail, in pixels. A larger chip draws its thumbnail scaled up. +const MAX_THUMB_PX: f32 = 1024.0; + +/// The pixels on a side of the thumbnail for a chip `size` points wide at `pixels_per_point`: 8 +/// to [`MAX_THUMB_PX`]. +fn thumb_px(size: f32, pixels_per_point: f32) -> u32 { + let px = (size * pixels_per_point).round(); + if px.is_nan() { 8 } else { px.clamp(8.0, MAX_THUMB_PX) as u32 } +} + /// A thumbnail of symbol `name` (an instance at its natural size), cached by its key in `keys` /// ([`Thumbs`]). fn thumb(ui: &Ui, doc: &Document, keys: &Thumbs, name: &str, size: f32) -> Option { @@ -32,7 +42,7 @@ fn thumb(ui: &Ui, doc: &Document, keys: &Thumbs, name: &str, size: f32) -> Optio static RENDERER: RefCell = RefCell::new(vectorcraft_render::Renderer::new()); static CACHE: crate::graphics::TexCache> = crate::graphics::TexCache::default(); } - let px = (size * ui.ctx().pixels_per_point()).round().max(8.0) as u32; + let px = thumb_px(size, ui.ctx().pixels_per_point()); let key = (*keys.keys.get(name)?, px); if let Some(t) = CACHE.with(|c| c.borrow().get(&key).cloned()) { return Some(t); @@ -135,6 +145,67 @@ pub(crate) fn chip(ui: &Ui, doc: &Document, keys: &Thumbs, r: egui::Rect, name: } } +/// The cache key of an [`art_chip`]: the symbol's key, the pixels across and down, and the bits of +/// the art's bounds. +type ArtKey = (u64, u32, u32, [u64; 4]); + +/// Symbol `name`'s art on white in `r`, its bounds `art` (at its own size, as a mapped graphic +/// measures them) stretched to fill `r`, as a box the art is scaled into shows it. The art is +/// rendered at most [`MAX_THUMB_PX`] pixels on a side, cached by its key in `keys`. +pub(crate) fn art_chip(ui: &Ui, doc: &Document, keys: &Thumbs, r: egui::Rect, name: &str, art: vectorcraft_geom::Rect) { + thread_local! { + static RENDERER: RefCell = RefCell::new(vectorcraft_render::Renderer::new()); + static CACHE: crate::graphics::TexCache> = crate::graphics::TexCache::default(); + } + ui.painter().rect_filled(r, 0.0, egui::Color32::WHITE); + let ppp = ui.ctx().pixels_per_point(); + let (w, h) = (thumb_px(r.width(), ppp), thumb_px(r.height(), ppp)); + let Some(&symbol) = keys.keys.get(name) else { return }; + let key = (symbol, w, h, [art.x0, art.y0, art.x1, art.y1].map(f64::to_bits)); + let tex = match CACHE.with(|c| c.borrow().get(&key).cloned()) { + Some(t) => t, + None => { + let Some(img) = RENDERER.with(|rr| render_art(&mut rr.borrow_mut(), doc, name, art, (w, h))) else { return }; + let tex = ui.ctx().load_texture(format!("sym-art-{name}-{w}x{h}"), crate::canvas::color_image(&img), egui::TextureOptions::LINEAR); + CACHE.with(|c| { + let mut c = c.borrow_mut(); + if c.len() > 64 { + c.clear(); + } + c.insert(key, tex.clone()); + }); + tex + } + }; + ui.painter().image(tex.id(), r, egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), egui::Color32::WHITE); +} + +/// Symbol `name` of `doc` (an instance at its natural size, as [`render_thumb`] places it) drawn +/// into `w` × `h` pixels with its bounds `art` stretched to fill them. `None` for bounds with no +/// area. +fn render_art( + r: &mut vectorcraft_render::Renderer, + doc: &Document, + name: &str, + art: vectorcraft_geom::Rect, + (w, h): (u32, u32), +) -> Option { + let (aw, ah) = (art.width(), art.height()); + if !(aw.is_finite() && ah.is_finite() && aw > 0.0 && ah > 0.0) { + return None; + } + let (sw, sh) = symbol_size(doc, name); + let mut d = doc.clone(); + let layer = d.alloc_id(); + d.layers = vec![Arc::new(Node::layer(layer, "Preview", vectorcraft_doc::LayerColor::Preset(0)))]; + let id = d.alloc_id(); + let xf = vectorcraft_geom::Affine::scale_non_uniform(sw / 20.0, sh / 20.0); + let n = Arc::new(Node::new(id, NodeKind::SymbolInstance { symbol: name.into(), xf })); + let view = + vectorcraft_geom::Affine::scale_non_uniform(f64::from(w) / aw, f64::from(h) / ah) * vectorcraft_geom::Affine::translate((-art.x0, -art.y0)); + r.render_node(&d, &n, u16::try_from(w).ok()?, u16::try_from(h).ok()?, view) +} + /// The active document's current symbol (`symbol.list`'s `current`), read without running a /// command; `None` without a document or symbols. fn current(app: &VectorcraftApp) -> Option { @@ -872,6 +943,35 @@ mod tests { (painted.len(), red) } + /// A thumbnail is at most 1,024 pixels on a side, whatever the size of the chip it draws. + #[test] + fn thumbnails_are_bounded_in_size() { + assert_eq!(thumb_px(40.0, 2.0), 80); + assert_eq!(thumb_px(1.0, 1.0), 8); + assert_eq!(thumb_px(100_000.0, 2.0), 1024); + assert_eq!(thumb_px(f32::NAN, 1.0), 8); + } + + /// Art drawn into a box fills the box, its bounds stretched to the box's proportions, as the + /// art's map scales it; art with no area draws nothing. + #[test] + fn mapped_art_fills_its_box_in_the_box_s_proportions() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 20})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + s.execute("symbol.new", &json!({"name": "Wide"})).unwrap(); + let doc = &*s.doc().unwrap().doc; + let art = vectorcraft_effects::graphic_bounds(doc, "Wide").expect("the art's bounds"); + let mut r = vectorcraft_render::Renderer::new(); + // A square box draws the 2:1 art stretched to fill it, as its map scales it. + let img = render_art(&mut r, doc, "Wide", art, (40, 40)).expect("the art"); + let (painted, red) = painted(&img); + assert!(red * 10 >= 40 * 40 * 9 && red == painted, "{painted} painted, {red} red"); + assert!(render_art(&mut r, doc, "Wide", vectorcraft_geom::Rect::new(0.0, 0.0, 0.0, 10.0), (40, 40)).is_none()); + } + /// A symbol that nests another (a library's included) shows the nested art in its /// thumbnail: the preview keeps the document's symbols and patterns, not its art. #[test] diff --git a/crates/ui-egui/src/panels/tests_brush_libraries.rs b/crates/ui-egui/src/panels/tests_brush_libraries.rs index fc9a18461b..30313cd3bd 100644 --- a/crates/ui-egui/src/panels/tests_brush_libraries.rs +++ b/crates/ui-egui/src/panels/tests_brush_libraries.rs @@ -199,6 +199,7 @@ fn the_window_menu_and_the_brushes_panel_open_brush_libraries() { json!("bristle-brushes"), json!("pattern-borders"), json!("scatter-shapes"), + json!("stipple"), json!("game-trails"), json!("energy-beams"), json!("dry-media"), diff --git a/crates/ui-egui/src/panels/tests_color_wheel_box.rs b/crates/ui-egui/src/panels/tests_color_wheel_box.rs index d527bf1fa8..3b55f52ac2 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_box.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_box.rs @@ -167,16 +167,22 @@ fn the_strip_takes_the_arrow_keys_and_screen_readers_actions() { #[test] fn ui_color_wheel_sets_and_reads_the_view_and_the_channel() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); - assert_eq!(app.run("ui.colorWheel", json!({})).unwrap(), json!({"view": "wheel", "channel": "hue", "vision": false})); - assert_eq!(app.run("ui.colorWheel", json!({"view": "box"})).unwrap(), json!({"view": "box", "channel": "hue", "vision": false})); - assert_eq!(app.run("ui.colorWheel", json!({"channel": "green"})).unwrap(), json!({"view": "box", "channel": "green", "vision": false})); + let harmony = json!({"harmony": false, "harmonyRule": "complementary", "vision": false}); + let with = |v: serde_json::Value| { + let mut v = v; + v.as_object_mut().unwrap().extend(harmony.as_object().unwrap().clone()); + v + }; + assert_eq!(app.run("ui.colorWheel", json!({})).unwrap(), with(json!({"view": "wheel", "channel": "hue"}))); + assert_eq!(app.run("ui.colorWheel", json!({"view": "box"})).unwrap(), with(json!({"view": "box", "channel": "hue"}))); + assert_eq!(app.run("ui.colorWheel", json!({"channel": "green"})).unwrap(), with(json!({"view": "box", "channel": "green"}))); let e = app.run("ui.colorWheel", json!({"view": "triangle"})).unwrap_err(); assert_eq!(e, "`view` must be wheel or box"); let e = app.run("ui.colorWheel", json!({"view": "wheel", "channel": 7})).unwrap_err(); assert_eq!(e, "`channel` must be hue, saturation, brightness, red, green or blue"); - assert_eq!(app.ui.color_wheel, Settings { view: View::Box, channel: Channel::Green, vision: false }, "an error changes nothing"); + assert_eq!(app.ui.color_wheel, Settings { view: View::Box, channel: Channel::Green, ..Default::default() }, "an error changes nothing"); let ui = crate::control::inspect(&app, &egui::Context::default()); - assert_eq!(ui["ui"]["color_wheel"], json!({"view": "box", "channel": "green", "vision": false})); + assert_eq!(ui["ui"]["color_wheel"], with(json!({"view": "box", "channel": "green"}))); } /// The command's errors are translated in the catalogs that translate status and error messages, @@ -211,10 +217,10 @@ fn ui_color_wheel_rejects_other_params() { let e = app.run("ui.colorWheel", json!([1])).unwrap_err(); assert_eq!(e, "the params must be an object, not [1]"); let e = app.run("ui.colorWheel", json!({"veiw": "wheel"})).unwrap_err(); - assert_eq!(e, "unknown parameter `veiw`; the command takes: view, channel, vision"); + assert_eq!(e, "unknown parameter `veiw`; the command takes: view, channel, harmony, harmonyRule, vision"); let e = app.run("ui.colorWheel", json!({"view": "wheel", "chanel": "blue"})).unwrap_err(); - assert_eq!(e, "unknown parameter `chanel`; the command takes: view, channel, vision"); - assert_eq!(app.ui.color_wheel, Settings { view: View::Box, channel: Channel::Red, vision: false }, "an error changes nothing"); + assert_eq!(e, "unknown parameter `chanel`; the command takes: view, channel, harmony, harmonyRule, vision"); + assert_eq!(app.ui.color_wheel, Settings { view: View::Box, channel: Channel::Red, ..Default::default() }, "an error changes nothing"); } /// With None there is no color to edit: the strip reads 0 to screen readers, as the hue ring does, @@ -271,7 +277,7 @@ fn ui_color_wheel_answers_junk_params_without_a_panic() { #[test] fn the_settings_are_kept_and_read_leniently() { let ui = crate::UiState { - color_wheel: Settings { view: View::Box, channel: Channel::Blue, vision: true }, + color_wheel: Settings { view: View::Box, channel: Channel::Blue, vision: true, ..Default::default() }, color_rgb_percent: true, ..Default::default() }; @@ -287,11 +293,11 @@ fn the_settings_are_kept_and_read_leniently() { let mut odd = saved.clone(); odd["color_wheel"] = json!({"view": "box", "channel": 7}); let back: crate::UiState = serde_json::from_value(odd).unwrap(); - assert_eq!(back.color_wheel, Settings { view: View::Box, channel: Channel::default(), vision: false }); + assert_eq!(back.color_wheel, Settings { view: View::Box, channel: Channel::default(), ..Default::default() }); let mut odd = saved.clone(); odd["color_wheel"] = json!({"view": "triangle", "channel": "blue"}); let back: crate::UiState = serde_json::from_value(odd).unwrap(); - assert_eq!(back.color_wheel, Settings { view: View::Wheel, channel: Channel::Blue, vision: false }); + assert_eq!(back.color_wheel, Settings { view: View::Wheel, channel: Channel::Blue, ..Default::default() }); let mut odd = saved; odd["color_wheel"] = json!("box"); let back: crate::UiState = serde_json::from_value(odd).unwrap(); diff --git a/crates/ui-egui/src/panels/tests_color_wheel_harmony.rs b/crates/ui-egui/src/panels/tests_color_wheel_harmony.rs new file mode 100644 index 0000000000..454e43ec49 --- /dev/null +++ b/crates/ui-egui/src/panels/tests_color_wheel_harmony.rs @@ -0,0 +1,351 @@ +//! The Color Wheel panel's Show Harmony drawn headless: the markers of a rule's other colors on the +//! ring, what a click, Alt, Enter and a screen reader do with them, `ui.colorWheel`'s `harmony` and +//! `harmonyRule`, the panel menu and the saved settings. + +use egui::{Event, Modifiers, PointerButton, Pos2, Rect, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; +use vectorcraft_color::Color; +use vectorcraft_color::cms; +use vectorcraft_color::harmony::Harmony; +use vectorcraft_engine::Session; + +use super::color_wheel::{Settings, View, display_hsb, harmony_rules, show}; +use crate::VectorcraftApp; + +/// An app with a selected rectangle filled with `fill`, its Color Wheel panel showing `rule`. +fn app(fill: serde_json::Value, rule: &str) -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + app.run("paint.setFill", json!({"color": fill})).unwrap(); + app.run("ui.colorWheel", json!({"harmony": true, "harmonyRule": rule})).unwrap(); + app +} + +/// The panel in a 260-point-wide flyout, with the app's shortcuts after it as in a frame of the app. +fn harness(app: VectorcraftApp) -> Harness<'static, VectorcraftApp> { + let mut h = Harness::builder().with_size(vec2(260.0, 320.0)).build_ui_state( + |ui, app: &mut VectorcraftApp| { + show(app, ui); + crate::shortcuts::handle(app, ui.ctx()); + }, + app, + ); + h.run_steps(2); + h +} + +/// The hue (degrees counterclockwise from 3 o'clock) of point `p` on the ring drawn in `ring`. +fn hue_at(ring: Rect, p: Pos2) -> f32 { + let v = p - ring.center(); + (-v.y).atan2(v.x).to_degrees().rem_euclid(360.0) +} + +/// The point at hue `deg` in the middle of the band of the ring drawn in `ring`. +fn on_ring(ring: Rect, deg: f32) -> Pos2 { + let r = ring.width() / 2.0 - 4.0 - 7.0; + let a = deg.to_radians(); + ring.center() + vec2(a.cos(), -a.sin()) * r +} + +/// The centers of the harmony markers, in the rule's order. +fn markers(h: &Harness<'static, VectorcraftApp>) -> Vec { + h.query_all_by_label("Harmony color").map(|n| n.rect().center()).collect() +} + +fn ring(h: &Harness<'static, VectorcraftApp>) -> Rect { + h.get_by_label("Hue ring").rect() +} + +fn press(h: &mut Harness<'static, VectorcraftApp>, pos: Pos2, pressed: bool, modifiers: Modifiers) { + h.event(Event::ModifiersChanged(modifiers)); + h.event(Event::PointerMoved(pos)); + h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers }); + h.run_steps(1); +} + +fn click(h: &mut Harness<'static, VectorcraftApp>, pos: Pos2, modifiers: Modifiers) { + press(h, pos, true, modifiers); + press(h, pos, false, modifiers); + h.event(Event::ModifiersChanged(Modifiers::NONE)); + h.run_steps(1); +} + +/// A drag through `points`, pressed at the first and released at the last. +fn drag(h: &mut Harness<'static, VectorcraftApp>, points: &[Pos2]) { + let (Some(first), Some(last)) = (points.first(), points.last()) else { return }; + press(h, *first, true, Modifiers::NONE); + for p in points { + for _ in 0..2 { + h.event(Event::PointerMoved(*p)); + h.run_steps(1); + } + } + press(h, *last, false, Modifiers::NONE); + h.run_steps(1); +} + +fn fill(app: &VectorcraftApp) -> Color { + crate::panels::current_paints(app).0.color().expect("a solid fill") +} + +fn hsb(c: &Color) -> [f32; 3] { + display_hsb(&cms::active(), c) +} + +fn undo_len(app: &VectorcraftApp) -> usize { + app.session.doc().unwrap().history.undo.len() +} + +/// With the complementary rule and a red fill, a marker sits at 180° on the ring, and a click on it +/// sets the fill to the complement that the rule gives, as one undo step. +#[test] +fn a_complementary_marker_sits_opposite_and_a_click_applies_it() { + let mut h = harness(app(json!("#ff0000"), "complementary")); + let at = markers(&h); + assert_eq!(at.len(), 1, "one other color"); + assert!((hue_at(ring(&h), at[0]) - 180.0).abs() < 1.0, "{}", hue_at(ring(&h), at[0])); + assert_eq!(h.get_by_label("Harmony color").value().as_deref(), Some("#00ffff")); + let undo = undo_len(h.state()); + click(&mut h, at[0], Modifiers::NONE); + let want = Harmony::Complementary.apply(Color::rgb(1.0, 0.0, 0.0))[1]; + assert_eq!(fill(h.state()).to_hex(), want.to_hex()); + assert_eq!(undo_len(h.state()), undo + 1); +} + +/// A click on a High Contrast marker applies the rule's color, whose brightness differs from the +/// current one, and not the hue under the pointer at the current brightness. +#[test] +fn a_click_on_a_marker_applies_the_rules_color_not_the_hue_under_it() { + let mut h = harness(app(json!([0.9, 0.8, 0.2]), "highContrast")); + let base = hsb(&fill(h.state())); + let at = markers(&h); + assert_eq!(at.len(), 1); + click(&mut h, at[0], Modifiers::NONE); + let want = Harmony::HighContrast.apply_hsb(base)[1]; + let got = hsb(&fill(h.state())); + assert!((got[2] - want[2]).abs() < 0.01 && got[2] < 0.5, "{got:?} {want:?}"); + assert!((got[0] - want[0]).abs() < 1.0, "{got:?} {want:?}"); +} + +/// Dragging the current color around the ring moves the other markers by the same angle. +#[test] +fn the_markers_follow_the_current_color() { + let mut h = harness(app(json!("#ff0000"), "triad")); + let r = ring(&h); + let before: Vec = markers(&h).iter().map(|p| hue_at(r, *p)).collect(); + assert_eq!(before.len(), 2); + assert!((before[0] - 120.0).abs() < 1.0 && (before[1] - 240.0).abs() < 1.0, "{before:?}"); + drag(&mut h, &[on_ring(r, 0.0), on_ring(r, 30.0), on_ring(r, 60.0)]); + assert!((hsb(&fill(h.state()))[0] - 60.0).abs() < 1.0, "{:?}", hsb(&fill(h.state()))); + let after: Vec = markers(&h).iter().map(|p| hue_at(r, *p)).collect(); + assert!((after[0] - 180.0).abs() < 1.0 && (after[1] - 300.0).abs() < 1.0, "{after:?}"); +} + +/// A drag that starts on a harmony marker moves the ring's hue as a drag on the band does, as one +/// undo step. +#[test] +fn a_drag_from_a_marker_moves_the_hue() { + let mut h = harness(app(json!("#ff0000"), "triad")); + let r = ring(&h); + let at = markers(&h); + assert!((hue_at(r, at[0]) - 120.0).abs() < 1.0); + let undo = undo_len(h.state()); + drag(&mut h, &[at[0], on_ring(r, 135.0), on_ring(r, 150.0)]); + assert!((hsb(&fill(h.state()))[0] - 150.0).abs() < 1.0, "{:?}", hsb(&fill(h.state()))); + assert_eq!(undo_len(h.state()), undo + 1); +} + +/// A press held on a High Contrast marker past the length of a click, without moving, applies the +/// rule's color on release, and the hue under the pointer is not previewed while it is held. +#[test] +fn a_press_held_on_a_marker_applies_the_rules_color() { + let mut h = harness(app(json!([0.9, 0.8, 0.2]), "highContrast")); + let base = hsb(&fill(h.state())); + let at = markers(&h); + assert_eq!(at.len(), 1); + let undo = undo_len(h.state()); + press(&mut h, at[0], true, Modifiers::NONE); + h.run_steps(6); + assert_eq!(hsb(&fill(h.state())), base, "nothing changes while the press is held"); + press(&mut h, at[0], false, Modifiers::NONE); + h.run_steps(1); + let want = Harmony::HighContrast.apply_hsb(base)[1]; + let got = hsb(&fill(h.state())); + assert!((got[2] - want[2]).abs() < 0.01 && (got[0] - want[0]).abs() < 1.0, "{got:?} {want:?}"); + assert_eq!(undo_len(h.state()), undo + 1); +} + +/// Alt-click on a marker paints the stroke, and the fill stays in front. +#[test] +fn alt_click_on_a_marker_paints_the_stroke() { + let mut app = app(json!("#ff0000"), "complementary"); + app.run("paint.setStroke", json!({"color": "#808080", "focus": false})).unwrap(); + let mut h = harness(app); + let at = markers(&h); + click(&mut h, at[0], Modifiers::ALT); + let (f, s) = crate::panels::current_paints(h.state()); + assert_eq!((f.color().unwrap().to_hex(), s.color().unwrap().to_hex()), ("#ff0000".into(), "#00ffff".into())); + assert!(h.state().session.fill_active); +} + +/// A click gives a marker the keyboard focus, and Enter or Space then applies its color; a screen +/// reader's click applies it too. +#[test] +fn the_markers_take_enter_space_and_a_screen_readers_click() { + let mut h = harness(app(json!("#ff0000"), "splitComplementary")); + let at = markers(&h); + assert_eq!(at.len(), 2); + click(&mut h, at[0], Modifiers::NONE); + assert!((hsb(&fill(h.state()))[0] - 150.0).abs() < 1.0, "{:?}", hsb(&fill(h.state()))); + // The markers moved with the color: from 150°, the focused first one is at 300°. + let undo = undo_len(h.state()); + h.key_press_modifiers(Modifiers::NONE, egui::Key::Enter); + h.run_steps(1); + assert!((hsb(&fill(h.state()))[0] - 300.0).abs() < 1.0, "{:?}", hsb(&fill(h.state()))); + h.key_press_modifiers(Modifiers::NONE, egui::Key::Space); + h.run_steps(1); + assert!((hsb(&fill(h.state()))[0] - 90.0).abs() < 1.0, "{:?}", hsb(&fill(h.state()))); + assert_eq!(undo_len(h.state()), undo + 2, "one undo step a key"); + let node = h.get_all_by_label("Harmony color").nth(1).unwrap(); + assert!(node.accesskit_node().data().supports_action(egui::accesskit::Action::Click)); + node.click_accesskit(); + h.run_steps(2); + assert!((hsb(&fill(h.state()))[0] - 300.0).abs() < 1.0, "{:?}", hsb(&fill(h.state()))); +} + +/// No markers show with Show Harmony off, in the box view, or with no color to edit. +#[test] +fn markers_show_only_on_the_wheel_with_a_color() { + let mut a = app(json!("#ff0000"), "triad"); + a.run("ui.colorWheel", json!({"harmony": false})).unwrap(); + assert!(markers(&harness(a)).is_empty()); + let mut a = app(json!("#ff0000"), "triad"); + a.run("ui.colorWheel", json!({"view": "box"})).unwrap(); + assert!(markers(&harness(a)).is_empty()); + let mut a = app(json!("#ff0000"), "triad"); + a.run("paint.setFill", json!({"none": true})).unwrap(); + assert!(markers(&harness(a)).is_empty()); +} + +/// A gray keeps the hue it was picked at, and its markers stay apart around the ring. +#[test] +fn a_gray_markers_turn_from_its_hue() { + let mut h = harness(app(json!([0.3, 0.6, 0.9]), "tetrad2")); + let r = ring(&h); + let hue = hsb(&fill(h.state()))[0]; + let sq = h.get_by_label("Saturation and brightness").rect(); + // A press between the square and the ring picks the square's left edge: no saturation. + click(&mut h, Pos2::new(sq.left() - 3.0, sq.center().y), Modifiers::NONE); + assert_eq!(hsb(&fill(h.state()))[1], 0.0, "a gray"); + let hues: Vec = markers(&h).iter().map(|p| hue_at(r, *p)).collect(); + assert_eq!(hues.len(), 3); + for (got, turn) in hues.iter().zip([90.0, 180.0, 270.0]) { + assert!(((got - hue - turn).rem_euclid(360.0) + 0.5).rem_euclid(360.0) < 2.0, "{hue} {hues:?}"); + } +} + +/// `ui.colorWheel` sets and answers `harmony` and `harmonyRule`, takes a rule's label as well as its +/// id, and answers an error that changes nothing for a value that is not a boolean or a rule +/// outside the wheel's list. +#[test] +fn ui_color_wheel_sets_the_harmony_and_its_rule() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let got = app.run("ui.colorWheel", json!({"harmony": true, "harmonyRule": "Split Complementary"})).unwrap(); + assert_eq!((got["harmony"].clone(), got["harmonyRule"].clone()), (json!(true), json!("splitComplementary"))); + let e = app.run("ui.colorWheel", json!({"harmony": "yes"})).unwrap_err(); + assert_eq!(e, "`harmony` must be true or false"); + let e = app.run("ui.colorWheel", json!({"view": "box", "harmonyRule": "monochromatic"})).unwrap_err(); + assert_eq!( + e, + "`harmonyRule` must be one of complementary, splitComplementary, leftComplement, rightComplement, analogous, analogous2, triad, \ + tetrad, tetrad2, tetrad3, compound, compound2, highContrast, highContrast3, pentagram" + ); + assert_eq!(app.ui.color_wheel, Settings { harmony: true, harmony_rule: Harmony::SplitComplementary, ..Default::default() }, "nothing changed"); + // Turning Show Harmony off and on keeps the rule. + app.run("ui.colorWheel", json!({"harmony": false})).unwrap(); + let got = app.run("ui.colorWheel", json!({"harmony": true})).unwrap(); + assert_eq!(got["harmonyRule"], json!("splitComplementary")); +} + +/// The errors are translated in the catalogs that translate status and error messages, and each +/// translation keeps the key and the accepted values. +#[test] +fn ui_color_wheel_harmony_errors_are_translated() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let flag = app.run("ui.colorWheel", json!({"harmony": 1})).unwrap_err(); + let rule = app.run("ui.colorWheel", json!({"harmonyRule": "shades"})).unwrap_err(); + for code in [ + "cs", "de", "el", "es", "fr", "hi", "hu", "it", "ja", "ka", "ko", "pl", "pt-br", "ru", "sv", "uk", "vi", "zh-hans", "zh-hant", "fi", "tr", + "ca", "nl", "bs", "da", "id", + ] { + let lang = crate::i18n::Lang::from_code(code).expect("registered"); + let shown = crate::i18n::message(lang, &flag); + assert!(shown != flag && shown.contains("`harmony`"), "{code}: {shown}"); + let shown = crate::i18n::message(lang, &rule); + assert!(shown != rule && shown.contains("`harmonyRule`") && shown.contains("highContrast3"), "{code}: {shown}"); + } +} + +/// The wheel offers the fifteen rules whose colors each have a hue of their own. +#[test] +fn the_wheel_offers_fifteen_rules_without_monochromatic() { + let rules: Vec = harmony_rules().collect(); + assert_eq!(rules.len(), 15); + assert!(!rules.contains(&Harmony::Monochromatic) && !rules.contains(&Harmony::Triad2)); + assert!(rules.contains(&Harmony::Pentagram) && rules.contains(&Harmony::HighContrast3)); +} + +/// The settings survive a JSON round trip of the preferences, and a saved value this build does +/// not know, or a rule the wheel leaves out, reads as the key's default. +#[test] +fn the_harmony_settings_are_kept_and_read_leniently() { + let set = Settings { view: View::Wheel, harmony: true, harmony_rule: Harmony::Pentagram, ..Default::default() }; + let ui = crate::UiState { color_wheel: set.clone(), color_rgb_percent: true, ..Default::default() }; + let saved = serde_json::to_value(&ui).unwrap(); + assert_eq!(saved["color_wheel"]["harmonyRule"], json!("pentagram")); + let back: crate::UiState = serde_json::from_value(saved.clone()).unwrap(); + assert_eq!(back.color_wheel, set); + let mut odd = saved; + odd["color_wheel"]["harmony"] = json!("yes"); + odd["color_wheel"]["harmonyRule"] = json!("monochromatic"); + let back: crate::UiState = serde_json::from_value(odd).unwrap(); + assert_eq!((back.color_wheel.harmony, back.color_wheel.harmony_rule), (false, Harmony::Complementary)); + assert!(back.color_rgb_percent, "the other preferences are kept"); +} + +/// The panel menu's Show Harmony is checked while on and gray while the box shows, and Harmony Rule +/// lists the wheel's rules with the current one checked; its items set the rule. +#[test] +fn the_panel_menu_shows_the_harmony_and_picks_the_rule() { + let a = app(json!("#ff0000"), "triad"); + let mut fonts = false; + let mut h = Harness::builder().with_size(vec2(260.0, 600.0)).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + // The fonts, which draw the check mark, take effect from the next frame. + if !fonts { + crate::theme::install_fonts(ui.ctx()); + fonts = true; + return; + } + assert!(super::panel_menu_items(app, ui, super::color_wheel::ID)); + }, + a, + ); + h.run_steps(3); + assert!(!h.get_by_label("✓ Show Harmony").accesskit_node().data().is_disabled()); + h.get_by_label(" Harmony Rule").click(); + h.run_steps(2); + assert!(h.query_by_label("✓ Triad").is_some()); + assert!(h.query_by_label(" Pentagram").is_some()); + assert!(h.query_by_label(" Monochromatic").is_none() && h.query_by_label(" Shades").is_none()); + h.get_by_label(" Pentagram").click(); + h.run_steps(2); + assert_eq!(h.state().ui.color_wheel.harmony_rule, Harmony::Pentagram); + h.state_mut().run("ui.colorWheel", json!({"view": "box"})).unwrap(); + h.run_steps(2); + assert!(h.get_by_label("✓ Show Harmony").accesskit_node().data().is_disabled(), "gray while the box shows"); + assert!(h.get_by_label(" Harmony Rule").accesskit_node().data().is_disabled(), "gray while the box shows"); +} diff --git a/crates/ui-egui/src/panels/tests_color_wheel_vision.rs b/crates/ui-egui/src/panels/tests_color_wheel_vision.rs index 5c73496642..7c07b71f90 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_vision.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_vision.rs @@ -225,24 +225,26 @@ fn the_panel_menu_turns_the_row_on_and_off() { #[test] fn ui_color_wheel_sets_and_reads_the_settings() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); - assert_eq!(app.run("ui.colorWheel", json!({})).unwrap(), json!({"view": "wheel", "channel": "hue", "vision": false})); - assert_eq!(app.run("ui.colorWheel", json!({"vision": true})).unwrap(), json!({"view": "wheel", "channel": "hue", "vision": true})); + let settings = + |view: &str, vision: bool| json!({"view": view, "channel": "hue", "harmony": false, "harmonyRule": "complementary", "vision": vision}); + assert_eq!(app.run("ui.colorWheel", json!({})).unwrap(), settings("wheel", false)); + assert_eq!(app.run("ui.colorWheel", json!({"vision": true})).unwrap(), settings("wheel", true)); assert_eq!(crate::control::inspect(&app, &egui::Context::default())["ui"]["color_wheel"]["vision"], true); assert_eq!(app.run("ui.colorWheel", json!({"vision": "no"})).unwrap_err(), "`vision` must be true or false"); assert_eq!(app.run("ui.colorWheel", json!({"view": "box", "channel": "red", "vision": 1})).unwrap_err(), "`vision` must be true or false"); - assert_eq!(app.run("ui.colorWheel", json!({})).unwrap(), json!({"view": "wheel", "channel": "hue", "vision": true})); + assert_eq!(app.run("ui.colorWheel", json!({})).unwrap(), settings("wheel", true)); assert_eq!(app.run("ui.colorWheel", json!("junk")).unwrap_err(), "the params must be an object, not \"junk\""); assert_eq!(app.run("ui.colorWheel", json!(5)).unwrap_err(), "the params must be an object, not 5"); assert_eq!( app.run("ui.colorWheel", json!({"visoin": false})).unwrap_err(), - "unknown parameter `visoin`; the command takes: view, channel, vision" + "unknown parameter `visoin`; the command takes: view, channel, harmony, harmonyRule, vision" ); assert!(app.ui.color_wheel.vision); assert_eq!(app.run("ui.colorWheel", json!({"vision": null})).unwrap()["vision"], true); assert_eq!(app.run("ui.colorWheel", Value::Null).unwrap()["vision"], true); // Setting the view or the channel keeps the row, and setting the row keeps them. assert_eq!(app.run("ui.colorWheel", json!({"view": "box"})).unwrap()["vision"], true); - assert_eq!(app.run("ui.colorWheel", json!({"vision": false})).unwrap(), json!({"view": "box", "channel": "hue", "vision": false})); + assert_eq!(app.run("ui.colorWheel", json!({"vision": false})).unwrap(), settings("box", false)); } /// `ui.colorWheel` answers every junk parameter, with and without a document, without a panic. diff --git a/crates/ui-egui/src/panels/tests_links.rs b/crates/ui-egui/src/panels/tests_links.rs index 1d38e6eb9b..b681fcc5cf 100644 --- a/crates/ui-egui/src/panels/tests_links.rs +++ b/crates/ui-egui/src/panels/tests_links.rs @@ -437,6 +437,20 @@ fn edit_original_opens_raster_images_in_photocraft_without_system_defaults() { assert_eq!(opened.borrow().len(), 4); } +#[test] +fn edit_original_with_chosen_editor_still_refuses_automation() { + let dir = Folder::new("chosen-automation"); + let (mut app, linked, _) = app(&dir); + app.ui.original_editor = serde_json::from_value(json!({"path": "/Apps/Editor.exe"})).unwrap(); + app.session.prefs.edit_original_system_defaults = false; + app.services.open_in_application = Some(Box::new(|_, _| panic!("automation must not launch an editor"))); + app.ui.answering_control = true; + assert!(app.run("links.editOriginal", json!({"id": linked})).unwrap_err().contains("only the person")); + app.ui.answering_control = false; + app.synthetic_frame = true; + assert!(app.run("links.editOriginal", json!({"id": linked})).unwrap_err().contains("only the person")); +} + /// Edit Original hands only regular image and document files to the system's default app. #[test] fn edit_original_opens_image_and_document_files_only() { diff --git a/crates/ui-egui/src/panels/tests_style_libraries.rs b/crates/ui-egui/src/panels/tests_style_libraries.rs index 569c1765a7..fac6a6bcf0 100644 --- a/crates/ui-egui/src/panels/tests_style_libraries.rs +++ b/crates/ui-egui/src/panels/tests_style_libraries.rs @@ -125,6 +125,47 @@ fn painted_and_sketched_opens_from_the_window_menu_and_a_click_applies_its_style assert_eq!(rows.iter().map(|r| r.name).collect::>(), ["Ink Contour", "Wet Ink"]); } +#[test] +fn paper_cutouts_opens_from_the_window_menu_and_applies_a_layered_style() { + let mut app = app(); + let entry = crate::menus::menu_entries(&app) + .into_iter() + .find(|e| e.path == ["Window", "Graphic Style Libraries"] && e.label == "Paper Cutouts") + .expect("a Window menu item"); + let rect = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 80, "height": 40})).unwrap()["id"].as_u64().unwrap(); + app.run(entry.command.as_deref().unwrap(), entry.params.clone()).unwrap(); + assert_eq!(last_open(&app.ui).map(|p| p.id.as_str()), Some("paper-cutouts")); + let undo = undo_len(&app); + click(&mut app, &context(), "Coral Layers", Modifiers::NONE, 0.0); + assert_eq!(undo_len(&app), undo + 1); + let appearance = &app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(rect)).unwrap().appearance; + assert_eq!(appearance.items.len(), 3); + assert_eq!(appearance.effects[0].id, "stylize.dropShadow"); +} + +/// A built-in library's list rows and Find field use the UI language; a user library's styles keep +/// their names, and clicks still name the stored style. +#[test] +fn built_in_style_names_show_in_the_ui_language() { + let mut app = app(); + let ctx = context(); + app.run("window.graphicStyleLibrary", json!({"library": "paper-cutouts"})).unwrap(); + app.run("ui.libraryPanel", json!({"panel": "library:graphicStyles:paper-cutouts", "view": "largeList"})).unwrap(); + crate::i18n::set_current(crate::i18n::Lang::from_code("fr").unwrap()); + let mut texts = vec![]; + for t in [0.0, 0.25] { + texts = frame(&ctx, vec![], Modifiers::NONE, t, |ui| library_panel::show_window(&mut app, ui.ctx())); + } + let (_, lib) = GraphicStyleLibraries::get(&app, "paper-cutouts").unwrap(); + let found: Vec<&str> = GraphicStyleLibraries::rows(&lib, "paper-cutouts", "corail").iter().map(|r| r.name).collect(); + let user = GraphicStyleLibraries::label("user/Mine", "Coral Layers").to_string(); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert!(texts.iter().any(|t| t == "Couches corail"), "{texts:?}"); + assert!(!texts.iter().any(|t| t == "Coral Layers"), "{texts:?}"); + assert_eq!(found, ["Coral Layers"]); + assert_eq!(user, "Coral Layers"); +} + #[test] fn the_window_menu_and_the_panel_open_every_library() { let mut app = app(); diff --git a/crates/ui-egui/src/panels/transform.rs b/crates/ui-egui/src/panels/transform.rs index 337b2755fa..14eb352d31 100644 --- a/crates/ui-egui/src/panels/transform.rs +++ b/crates/ui-egui/src/panels/transform.rs @@ -665,6 +665,22 @@ pub fn set_pref(app: &mut VectorcraftApp, key: &str, on: bool) { } } +/// Show on Shape Creation (`showOnShapeCreation`): after a shape was drawn +/// ([`vectorcraft_engine::Session::take_shape_drawn`]), the Transform panel shows as Window › +/// Transform shows it, unless it can be seen already. In Presentation Mode, or with the option off, +/// the panels stay as they are. Called once per frame, after the canvas and the dialogs; a frame +/// that shows the panel asks `ctx` for another, which draws it. +pub fn show_on_shape_creation(app: &mut VectorcraftApp, ctx: &egui::Context) { + let drawn = app.session.take_shape_drawn(); + if !drawn || !app.session.prefs.show_on_shape_creation || app.ui.screen_mode >= 3 || crate::panel_docking::visible(&app.ui, "transform") { + return; + } + match app.run("window.panel", json!({ "panel": "transform" })) { + Ok(_) => ctx.request_repaint(), + Err(e) => app.status(e), + } +} + pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { let hidden: bool = pstate(ui.ctx(), "xf-hide-options"); let has = super::selection_len(app) > 0; @@ -673,6 +689,10 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { if menu_item(ui, if hidden { tl!("Show Options") } else { tl!("Hide Options") }, true, false) { set_pstate(ui.ctx(), "xf-hide-options", !hidden); } + let on_creation = app.session.prefs.show_on_shape_creation; + if menu_item(ui, tl!("Show on Shape Creation"), true, on_creation) { + set_pref(app, "showOnShapeCreation", !on_creation); + } ui.separator(); if menu_item(ui, tl!("Flip Horizontal"), has, false) { run_transform(app, "object.reflect", json!({"axis": "vertical", "origin": origin})); diff --git a/crates/ui-egui/src/panels/transform/tests.rs b/crates/ui-egui/src/panels/transform/tests.rs index f4a06ee970..bb6b5f5000 100644 --- a/crates/ui-egui/src/panels/transform/tests.rs +++ b/crates/ui-egui/src/panels/transform/tests.rs @@ -1026,3 +1026,137 @@ fn align_new_objects_menu_item_toggles_the_active_document() { menu_click(&ctx, &mut app, item); assert_eq!((on(&app, 0), on(&app, 1)), (true, false)); } + +/// An app with a document and the Transform panel closed. +fn app_without_transform_panel() -> VectorcraftApp { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + if crate::panel_docking::visible(&app.ui, "transform") { + app.run("window.panel.close", json!({"panel": "transform"})).unwrap(); + } + assert!(!crate::panel_docking::visible(&app.ui, "transform")); + app.session.take_shape_drawn(); + app +} + +/// The panel menu's Show on Shape Creation is unchecked until chosen, and choosing it sets and +/// clears `showOnShapeCreation`. +#[test] +fn show_on_shape_creation_is_a_check_item_in_the_panel_menu() { + let mut app = app_without_transform_panel(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + assert!(menu_texts(&ctx, &mut app).contains(&" Show on Shape Creation".to_string())); + menu_click(&ctx, &mut app, "Show on Shape Creation"); + assert!(app.session.prefs.show_on_shape_creation); + assert!(menu_texts(&ctx, &mut app).contains(&"✓ Show on Shape Creation".to_string())); + menu_click(&ctx, &mut app, "Show on Shape Creation"); + assert!(!app.session.prefs.show_on_shape_creation); +} + +/// With Show on Shape Creation on, a shape drawn by a command or with OK in a shape tool's dialog +/// shows the closed Transform panel; with it off, after a canceled dialog, for other edits, for +/// saved steps and in Presentation Mode the panel stays closed. +#[test] +fn show_on_shape_creation_shows_the_transform_panel_after_a_shape() { + let ctx = egui::Context::default(); + let visible = |app: &VectorcraftApp| crate::panel_docking::visible(&app.ui, "transform"); + let rect = json!({"x": 10, "y": 10, "width": 40, "height": 30}); + + let mut app = app_without_transform_panel(); + app.run("shape.rectangle", rect.clone()).unwrap(); + show_on_shape_creation(&mut app, &ctx); + assert!(!visible(&app), "off: the panel stays closed"); + + let mut app = app_without_transform_panel(); + // A selected rectangle to move, drawn while the preference is off. + let id = app.run("shape.rectangle", rect.clone()).unwrap()["id"].as_u64().unwrap(); + app.session.take_shape_drawn(); + set_pref(&mut app, "showOnShapeCreation", true); + let x0 = |app: &VectorcraftApp| app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().geometric_bounds().unwrap().x0; + let before = x0(&app); + app.run("object.move", json!({"dx": 5, "dy": 0})).unwrap(); + assert_eq!(x0(&app), before + 5.0, "the move moved the rectangle"); + show_on_shape_creation(&mut app, &ctx); + assert!(!visible(&app), "an edit that draws no shape"); + app.replay("shape.rectangle", rect.clone()).unwrap(); + show_on_shape_creation(&mut app, &ctx); + assert!(!visible(&app), "saved steps"); + // A dialog that is canceled draws nothing; OK draws the shape. + app.run("tool.select", json!({"tool": "ellipse"})).unwrap(); + crate::dialogs::open_tool_dialog(&mut app, "ellipse", json!({"x": 10.0, "y": 10.0})); + app.ui.dialog = None; + show_on_shape_creation(&mut app, &ctx); + assert!(!visible(&app), "a canceled dialog"); + crate::dialogs::open_tool_dialog(&mut app, "ellipse", json!({"x": 10.0, "y": 10.0})); + crate::dialogs::confirm(&mut app).unwrap(); + show_on_shape_creation(&mut app, &ctx); + assert!(visible(&app), "OK in the Ellipse dialog"); + // Shown already: another shape leaves it showing. + app.run("shape.polygon", json!({"cx": 100, "cy": 100, "radius": 30})).unwrap(); + show_on_shape_creation(&mut app, &ctx); + assert!(visible(&app), "a shape with the panel showing"); + + // Presentation Mode keeps the panels hidden, also once it ends. + let mut app = app_without_transform_panel(); + set_pref(&mut app, "showOnShapeCreation", true); + app.ui.screen_mode = 3; + app.run("shape.star", json!({"cx": 100, "cy": 100, "radius1": 30, "radius2": 15, "points": 5})).unwrap(); + show_on_shape_creation(&mut app, &ctx); + app.ui.screen_mode = 0; + show_on_shape_creation(&mut app, &ctx); + assert!(!visible(&app), "Presentation Mode"); + + // A floating Transform panel in front stays showing (Window › Transform would close it). + let mut app = app_without_transform_panel(); + set_pref(&mut app, "showOnShapeCreation", true); + app.run("window.panel.float", json!({"panel": "transform"})).unwrap(); + assert!(visible(&app)); + app.run("shape.line", json!({"x1": 0, "y1": 0, "x2": 50, "y2": 50})).unwrap(); + show_on_shape_creation(&mut app, &ctx); + assert!(visible(&app), "a floating panel"); +} + +/// The app's frame shows the Transform panel after a shape is drawn, with Show on Shape Creation on, +/// and the next frame draws the panel's controls; with it off, no frame draws them. +#[test] +fn a_frame_after_a_shape_shows_the_transform_panel() { + fn walk(s: &egui::Shape, out: &mut Vec) { + match s { + egui::Shape::Text(t) => out.push(t.galley.text().to_string()), + egui::Shape::Vec(v) => v.iter().for_each(|s| walk(s, out)), + _ => {} + } + } + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0)); + // One frame of the app: the texts it drew. + let frame = |app: &mut VectorcraftApp| { + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| app.ui(ui)); + out.textures_delta.clear(); + let mut texts = vec![]; + out.shapes.iter().for_each(|c| walk(&c.shape, &mut texts)); + texts + }; + // The Transform panel's heading for a selected live rectangle. + let heading = "Rectangle Properties:"; + let rect = json!({"x": 10, "y": 10, "width": 40, "height": 30}); + for on in [false, true] { + let mut app = app_without_transform_panel(); + set_pref(&mut app, "showOnShapeCreation", on); + for _ in 0..3 { + frame(&mut app); + } + assert!(!crate::panel_docking::visible(&app.ui, "transform")); + app.run("shape.rectangle", rect.clone()).unwrap(); + frame(&mut app); + assert_eq!(crate::panel_docking::visible(&app.ui, "transform"), on, "on: {on}"); + // The panel opens in its icon column's flyout: the next pass draws the flyout's tabs and the + // one after it the panel's controls. + let tabs = frame(&mut app); + let texts = frame(&mut app); + assert!(!tabs.iter().any(|t| t == heading) || on, "on: {on}, {tabs:?}"); + assert_eq!(texts.iter().any(|t| t == heading), on, "on: {on}, {texts:?}"); + } +} diff --git a/crates/ui-egui/src/place.rs b/crates/ui-egui/src/place.rs index 3ff8159407..a644c91ce9 100644 --- a/crates/ui-egui/src/place.rs +++ b/crates/ui-egui/src/place.rs @@ -742,8 +742,9 @@ pub fn drop_files(app: &mut VectorcraftApp, mut files: Vec<(DropTarget, DropFile } DropTarget::Open => match path.as_deref() { Some(path) if app.services.read.is_some() => io::open_path(app, path).map(|_| ()), - _ => io::open_bytes(app, &name, &bytes, path.clone()).map(|_| { - if let Some(path) = &path { + _ => io::open_bytes(app, &name, &bytes, path.clone()).map(|r| { + // A document that asks a question first goes on the recent files once it opens. + if let Some(path) = path.as_ref().filter(|_| !io::asks_first(&r)) { io::note_recent(app, path); } }), diff --git a/crates/ui-egui/src/placing.rs b/crates/ui-egui/src/placing.rs index c43ad596b4..cdb35e7419 100644 --- a/crates/ui-egui/src/placing.rs +++ b/crates/ui-egui/src/placing.rs @@ -589,7 +589,7 @@ fn finish_paste(app: &mut VectorcraftApp, paste: Paste) { let _ = app.run(&paste.id, paste.params); // Also when the paste did not reach the clipboard (the Type tool took it). app.placing.adopted = false; - if let Some(d) = app.ui.dialog.as_mut().filter(|d| d.kind == crate::dialogs::swatch_conflict::KIND) { + if let Some(d) = app.ui.dialog.as_mut().filter(|d| asks_before_paste(&d.kind)) { d.fields.insert("__deferredPaste".into(), json!(chain)); if let Ok(st) = app.session.doc() { app.placing.swatch_paste = Some(PendingSwatch { @@ -643,12 +643,19 @@ pub(crate) fn cancel_swatch_paste(app: &mut VectorcraftApp) { } } +/// Is `kind` a dialog a paste asks before it runs (Paste Profile Mismatch, Swatch Conflict), whose +/// OK runs a deferred paste in the context it was given in? +fn asks_before_paste(kind: &str) -> bool { + kind == crate::dialogs::swatch_conflict::KIND || kind == crate::dialogs::profile_mismatch::PASTE_KIND +} + /// Release a deferred paste once its dialog is no longer the active dialog. pub(crate) fn settle_swatch_paste(app: &mut VectorcraftApp) { let active = app.placing.swatch_paste.as_ref().is_some_and(|waiting| { - app.ui.dialog.as_ref().is_some_and(|d| { - d.kind == crate::dialogs::swatch_conflict::KIND && d.fields.get("__deferredPaste").and_then(Value::as_u64) == Some(waiting.chain) - }) + app.ui + .dialog + .as_ref() + .is_some_and(|d| asks_before_paste(&d.kind) && d.fields.get("__deferredPaste").and_then(Value::as_u64) == Some(waiting.chain)) }); if app.placing.swatch_paste.is_some() && !active { cancel_swatch_paste(app); @@ -661,13 +668,41 @@ 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 { +/// The answer a paste question gave, checked again where the paste runs (in the document and with +/// the clipboard it was given with): `key` is the param that holds the answer, and `changed` tells +/// whether the question the paste command `id` with those params would ask now differs from the one +/// answered. The paste then runs without the answer, and so asks again. +pub(crate) struct Recheck<'a> { + pub key: &'static str, + pub changed: &'a dyn Fn(&mut VectorcraftApp, &str, &Value) -> bool, +} + +/// `params` without the answer `recheck` names when the question it answered has changed. +fn rechecked(app: &mut VectorcraftApp, id: &str, mut params: Value, recheck: Option<&Recheck<'_>>) -> Value { + if let Some(r) = recheck + && (r.changed)(app, id, ¶ms) + && let Some(o) = params.as_object_mut() + { + o.remove(r.key); + } + params +} + +/// Run the command confirmed by the deferred paste's Swatch Conflict or Paste Profile Mismatch +/// dialog, asking again first when `recheck` finds that the question has changed. +pub(crate) fn confirm_swatch_paste( + app: &mut VectorcraftApp, + id: &str, + params: Value, + token: Option, + recheck: Option<&Recheck<'_>>, +) -> Result { if !app.placing.swatch_paste.as_ref().is_some_and(|waiting| Some(waiting.chain) == token) { if token.is_some() || app.placing.swatch_paste.is_some() { cancel_swatch_paste(app); return Err("the deferred paste is no longer available".into()); } + let params = rechecked(app, id, params, recheck); return app.run(id, params); } let Some(waiting) = app.placing.swatch_paste.take() else { return app.run(id, params) }; @@ -693,9 +728,32 @@ pub(crate) fn confirm_swatch_paste(app: &mut VectorcraftApp, id: &str, params: V } let insertion = waiting.insertion.clone().or_now(changed.as_ref(), app, pastes_inside(id)); insertion.clone().set(app); + // The question checked again with the clipboard and document the paste runs with. + let params = rechecked(app, id, params, recheck); app.placing.adopted = true; let result = app.run(id, params); app.placing.adopted = false; + // The paste asked again (Swatch Conflict after Paste Profile Mismatch, or the same question + // about what changed): it stays deferred, in the context it was given in. + let asked_again = app.ui.dialog.as_mut().filter(|d| asks_before_paste(&d.kind) && !d.fields.contains_key("__deferredPaste")); + if let Some(d) = asked_again + && let Ok(st) = app.session.doc() + { + d.fields.insert("__deferredPaste".into(), json!(waiting.chain)); + app.placing.swatch_paste = Some(PendingSwatch { + clipboard: app.session.clipboard.clone(), + insertion: insertion.clone(), + selection: waiting.selection, + doc: st.uid, + reverts: st.reverts, + chain: waiting.chain, + }); + if let Some(changed) = changed { + changed.restore_changed(&insertion, app); + } + app.session.clipboard = current; + return result; + } if let Some(changed) = changed { changed.restore_changed(&insertion, app); } diff --git a/crates/ui-egui/src/prefs_dialog.rs b/crates/ui-egui/src/prefs_dialog.rs index bc0a52604a..f6bd364449 100644 --- a/crates/ui-egui/src/prefs_dialog.rs +++ b/crates/ui-egui/src/prefs_dialog.rs @@ -29,6 +29,7 @@ const RESET_UNITS: &str = "__resetUnits"; const APP_TITLE_BAR_SHOWN: bool = cfg!(not(any(target_arch = "wasm32", target_os = "macos", target_os = "windows"))); pub fn open(app: &mut VectorcraftApp, category: Option<&str>) { + crate::original_editor::open(app); // One field per preference key or group (the flattener presets have commands of their own). let mut fields: Map = app.session.prefs.to_json().as_object().cloned().unwrap_or_default(); fields.retain(|k, _| vectorcraft_engine::cmd::prefscmds::spec(k).is_some() || PREF_GROUPS.contains(&k.as_str())); @@ -230,6 +231,7 @@ pub fn confirm(app: &mut VectorcraftApp) -> Result { app.ui.view.smart_guides = d.fields.get("__smartGuides").and_then(Value::as_bool).unwrap_or(app.ui.view.smart_guides); app.ui.view.snap_to_grid = d.fields.get("__snapToGrid").and_then(Value::as_bool).unwrap_or(app.ui.view.snap_to_grid); app.ui.task_bar = d.fields.get("__taskBar").and_then(Value::as_bool).unwrap_or(app.ui.task_bar); + crate::original_editor::commit(app); app.ui.dialog = None; app.ui.engine_prefs = app.session.prefs.to_json(); app.prefs_changed = true; @@ -338,6 +340,10 @@ fn apply(app: &mut VectorcraftApp, ctx: &egui::Context, force: bool) { app.canvas.key = None; ctx.data_mut(|d| d.insert_temp(id, Some(want))); } + // Cards show only with Show Tool Tips on: an open card goes away as soon as tool tips are turned off. + let p = &app.session.prefs; + let cards = crate::toolbar::card::CardPrefs { on: p.show_tool_cards && p.show_tool_tips, animated_zoom: crate::canvas::animated_zoom(p) }; + crate::toolbar::card::set_prefs(ctx, cards); let z = app.session.prefs.ui_scaling.clamp(0.75, 2.0) as f32; if (ctx.zoom_factor() - z).abs() > 1e-3 { ctx.set_zoom_factor(z); @@ -468,6 +474,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { } app.ui.dialog = Some(d); if cancel { + crate::original_editor::cancel(app); app.ui.dialog = None; } else if ok && let Err(e) = confirm(app) { app.status(e); @@ -557,6 +564,27 @@ impl DescribedRows { } } +/// Whether the checkbox of the setting `key` is enabled, for a setting that acts only while +/// another setting allows it and is dimmed otherwise. `None` for every other setting. +fn bool_enabled(d: &Dialog, key: &str) -> Option { + match key { + // General › Scroll Sideways with Cmd/Ctrl + Wheel acts only while Zoom with Mouse Wheel + // is off: dimmed while it is on. + "ctrlWheelScrollsSideways" => Some(!d.bool("zoomWithMouseWheel")), + // Units › Numbers Without Units Are Points only tells points from picas: dimmed + // unless a unit is Picas. + "numbersWithoutUnitsArePoints" => Some(picas_in_use(d)), + // General › Show Tool Cards replaces the tool tips: dimmed while Show Tool Tips is off. + "showToolCards" => Some(d.bool("showToolTips")), + // Performance › Animated Zoom needs GPU Performance: dimmed while it is off. + "animatedZoom" => Some(d.bool("gpuPerformance")), + // Type › Show samples on white draws the samples that Enable in-menu font previews + // shows: dimmed while previews are off. + "fontSamplesOnWhite" => Some(d.bool("fontPreview")), + _ => None, + } +} + /// The fields of the category `cat`. → The rows under the pointer and with the keyboard focus. fn category_fields(ui: &mut egui::Ui, app: &mut VectorcraftApp, d: &mut Dialog, cat: &str) -> DescribedRows { let t = Tokens::get(ui.ctx()); @@ -596,25 +624,10 @@ fn category_fields(ui: &mut egui::Ui, app: &mut VectorcraftApp, d: &mut Dialog, let v = d.fields.get(sp.key).cloned().unwrap_or(Value::Null); let top = ui.cursor().top(); let mark = found_mark(ui, d, sp.key); + let enabled = bool_enabled(d, sp.key); match sp.kind { - // General › Scroll Sideways with Cmd/Ctrl + Wheel acts only while Zoom with Mouse Wheel - // is off: dimmed while it is on. - PrefKind::Bool if sp.key == "ctrlWheelScrollsSideways" => { - ui.add_enabled_ui(!d.bool("zoomWithMouseWheel"), |ui| bool_row(ui, d, sp.key, sp.label)); - } - // Units › Numbers Without Units Are Points only tells points from picas: dimmed - // unless a unit is Picas. - PrefKind::Bool if sp.key == "numbersWithoutUnitsArePoints" => { - ui.add_enabled_ui(picas_in_use(d), |ui| bool_row(ui, d, sp.key, sp.label)); - } - // Performance › Animated Zoom needs GPU Performance: dimmed while it is off. - PrefKind::Bool if sp.key == "animatedZoom" => { - ui.add_enabled_ui(d.bool("gpuPerformance"), |ui| bool_row(ui, d, sp.key, sp.label)); - } - // Type › Show samples on white draws the samples that Enable in-menu font previews - // shows: dimmed while previews are off. - PrefKind::Bool if sp.key == "fontSamplesOnWhite" => { - ui.add_enabled_ui(d.bool("fontPreview"), |ui| bool_row(ui, d, sp.key, sp.label)); + PrefKind::Bool if enabled.is_some() => { + ui.add_enabled_ui(enabled == Some(true), |ui| bool_row(ui, d, sp.key, sp.label)); } // Windows and Linux only: macOS always has the system's title bar, the web has none. PrefKind::Bool if sp.key == "systemTitleBar" => { @@ -657,15 +670,13 @@ fn category_fields(ui: &mut egui::Ui, app: &mut VectorcraftApp, d: &mut Dialog, ui.label(egui::RichText::new(note).color(t.text_dim).size(11.0)); } } + PrefKind::Bool if sp.key == "editOriginalSystemDefaults" => { + bool_row(ui, d, sp.key, sp.label); + crate::original_editor::show(ui, app, d); + } // The desktop app only: the web build has no display profile to read. A note says // which profile the canvas is drawn through, or why none. - PrefKind::Bool if sp.key == "monitorProfileDisplay" => { - if !cfg!(target_arch = "wasm32") { - bool_row(ui, d, sp.key, sp.label); - let note = app.display_profile.note(d.bool(sp.key)); - ui.label(egui::RichText::new(note).color(t.text_dim).size(11.0)); - } - } + PrefKind::Bool if sp.key == "monitorProfileDisplay" => monitor_profile_row(ui, app, d, sp.key, sp.label, &t), // The desktop app only: it sets the window's present mode when it starts, so a note // says the change applies at the next start. PrefKind::Bool if sp.key == "lowLatencyDrawing" => desktop_startup_bool_row(ui, d, sp.key, sp.label, &t), @@ -869,6 +880,14 @@ fn choice_row(ui: &mut egui::Ui, d: &mut Dialog, key: &str, label: &str, opts: & }); } +fn monitor_profile_row(ui: &mut egui::Ui, app: &VectorcraftApp, d: &mut Dialog, key: &str, label: &str, t: &theme::Tokens) { + if !cfg!(target_arch = "wasm32") { + bool_row(ui, d, key, label); + let note = app.display_profile.note(d.bool(key)); + ui.label(egui::RichText::new(note).color(t.text_dim).size(11.0)); + } +} + /// The row of the number preference `key` within `range`: a slider for Interface Scaling, a field /// shown with `unit` otherwise. fn num_row(ui: &mut egui::Ui, d: &mut Dialog, key: &str, label: &str, range: std::ops::RangeInclusive, unit: &str, v: &Value) { diff --git a/crates/ui-egui/src/prefs_dialog/descriptions.rs b/crates/ui-egui/src/prefs_dialog/descriptions.rs index 5ba36d7f56..e4c0856ca6 100644 --- a/crates/ui-egui/src/prefs_dialog/descriptions.rs +++ b/crates/ui-egui/src/prefs_dialog/descriptions.rs @@ -16,6 +16,7 @@ pub(crate) const DESCRIPTIONS: &[(&str, &str)] = &[ ("disableAutoAddDelete", "Stops the Pen tool from deleting the anchor you click on a selected path, or adding one where you click its segment."), ("usePreciseCursors", "Drawing tools show a crosshair pointer instead of their icon; Caps Lock does the same while it is on."), ("showToolTips", "Shows a tip when the pointer rests on a button or field that has one."), + ("showToolCards", "Shows a card with what a toolbar tool does and what its keys do instead of its tip; it needs Show Tool Tips."), ("showExternalScriptWarning", "Shows a warning before a script you choose runs."), ("antiAliasedArtwork", "Smooths the edges of artwork on the canvas."), ( @@ -59,6 +60,7 @@ pub(crate) const DESCRIPTIONS: &[(&str, &str)] = &[ "useRegistrationPointForSymbol", "With one symbol instance selected, the Transform panel uses the symbol's registration point as its reference point.", ), + ("showOnShapeCreation", "Drawing a rectangle, ellipse, polygon, star or line opens the Transform panel if it is closed."), ("fadeRegionOutsideArtboard", "Darkens the canvas outside the artboards while the Artboard tool is active."), ( "artboardUpdateWhileDragging", diff --git a/crates/ui-egui/src/prefs_dialog/tests.rs b/crates/ui-egui/src/prefs_dialog/tests.rs index 561d9f2084..d162af178c 100644 --- a/crates/ui-egui/src/prefs_dialog/tests.rs +++ b/crates/ui-egui/src/prefs_dialog/tests.rs @@ -1250,6 +1250,46 @@ fn show_samples_on_white_dims_without_in_menu_font_previews() { } } +/// General › Show Tool Cards: its checkbox is dimmed while Show Tool Tips is unchecked in the +/// dialog, and a click on it then leaves the setting as it was. +#[test] +fn show_tool_cards_dims_without_tool_tips() { + fn label(s: &egui::Shape, text: &str) -> Option<(egui::Color32, egui::Rect)> { + match s { + egui::Shape::Text(t) if t.galley.text() == text => t.galley.job.sections.first().map(|s| (s.format.color, t.visual_bounding_rect())), + egui::Shape::Vec(v) => v.iter().find_map(|s| label(s, text)), + _ => None, + } + } + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut a = app(); + let mut frame = |d: &mut Dialog, events: Vec| { + let raw = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(600.0, 3000.0))), + events, + ..Default::default() + }; + let mut out = ctx.run_ui(raw, |ui| { + category_fields(ui, &mut a, d, "General"); + }); + out.textures_delta.clear(); + out.shapes.iter().find_map(|c| label(&c.shape, "Show Tool Cards")) + }; + let t = Tokens::get(&ctx); + for (tips, color, what) in [(true, t.text, "enabled while tool tips are on"), (false, t.text_disabled, "dimmed while they are off")] { + let mut d = Dialog::new("preferences", json!({"showToolTips": tips, "showToolCards": false})); + let (shown, at) = frame(&mut d, vec![]).unwrap_or_else(|| panic!("no label ({what})")); + assert_eq!(shown, color, "{what}"); + let press = + |pressed| egui::Event::PointerButton { pos: at.center(), button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(&mut d, vec![egui::Event::PointerMoved(at.center()), press(true)]); + frame(&mut d, vec![press(false)]); + // A click turns it on while it is enabled, and leaves it off while it is dimmed. + assert_eq!(d.fields["showToolCards"], json!(tips), "after a click, {what}"); + } +} + /// 0.5.0 saved `powerSaving` for everyone (its default): it reads as Automatic, while the /// choices this version offers are kept (#502). #[test] diff --git a/crates/ui-egui/src/services.rs b/crates/ui-egui/src/services.rs index ce48ef17c1..6c38464bd0 100644 --- a/crates/ui-egui/src/services.rs +++ b/crates/ui-egui/src/services.rs @@ -31,6 +31,9 @@ impl FilePick { } } +pub type CheckApplicationFn = Box Result<(), String>>; +pub type OpenApplicationFn = Box Result>; + pub type PickOpen = Box Option>; pub type PickSave = Box Option>; @@ -166,6 +169,10 @@ pub struct Services { /// with Preferences › File Handling › Use System Defaults for Edit Original off); `Ok(false)` /// when it isn't. Without it Edit Original uses `open_file`. pub open_in_photocraft: Option, + /// Validate a native-picked application before keeping it as the raster editor. + pub check_application: Option, + /// Launch a native-picked application with one file argument; false only when absent. + pub open_in_application: Option, /// Show a folder picker; returns its path (desktop: Relink to Folder, Package). pub pick_folder: Option Option>>, /// Show a folder picker that starts in a folder (a script's `selectDlg`); returns its path. diff --git a/crates/ui-egui/src/shortcut_editor.rs b/crates/ui-egui/src/shortcut_editor.rs index bb71115d8a..da9c0938c0 100644 --- a/crates/ui-egui/src/shortcut_editor.rs +++ b/crates/ui-egui/src/shortcut_editor.rs @@ -802,9 +802,9 @@ fn listed(overrides: &Overrides, e: &Entry) -> bool { /// Options, Character, Set Bounds), the exports and saves that give the file back without a `path` /// (Save Document gives the file back when the document has no file yet; File › Save takes a key /// instead), the undo group's begin and end, and the commands that need a point, a value or a name -/// (Create Dimension, Edit Freeform Point, Select by Color, Move Brush, Paintbrush). New Symbol is left out +/// (Create Dimension, Edit Freeform Point, Select by Color, Move Brush, Paintbrush, Map Art). New Symbol is left out /// because the Symbols panel runs it through the Symbol Options dialog. -const NEEDS_A_PARAM: [&str; 75] = [ +const NEEDS_A_PARAM: [&str; 76] = [ "transparency.set", "transparency.setOpacityMask", "stroke.set", @@ -879,6 +879,7 @@ const NEEDS_A_PARAM: [&str; 75] = [ "text.setFormat", "text.setRangeStyle", "text.setStyle", + "threeD.mapArt", "type.ruby", ]; @@ -1037,13 +1038,28 @@ fn names_a_required_field(params: &str) -> bool { /// 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); + outside_marks(text, &['"']) +} + +/// [`outside_quotes`], with a span between backticks skipped as well, as the engine's params object +/// reads it: inside a span opened by a double quote or a backtick, only the same mark closes it. +pub(crate) fn outside_quotes_and_backticks(text: &str) -> impl Iterator + '_ { + outside_marks(text, &['"', '`']) +} + +/// Each character of `text` that is not one of `marks` or inside a span a mark opens and the same +/// mark closes, as [`outside_quotes`] counts them. +fn outside_marks<'a>(text: &'a str, marks: &'static [char]) -> impl Iterator + 'a { + let (mut depth, mut quote) = (0usize, None::); text.char_indices().filter_map(move |(i, ch)| { - if ch == '"' { - quoted = !quoted; + if let Some(q) = quote { + if ch == q { + quote = None; + } return None; } - if quoted { + if marks.contains(&ch) { + quote = Some(ch); return None; } let before = depth; diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index 92524f389a..6905879cd4 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -13,12 +13,17 @@ use crate::VectorcraftApp; mod held_tool; mod hold_keys; +mod labels; mod paste; mod presentation; mod typing; pub(crate) use held_tool::{HeldTool, note_tool_use}; pub(crate) use hold_keys::HoldKeys; +#[cfg(test)] +pub(crate) use labels::note_copied_in_window; +pub(crate) use labels::{leave_to_labels, take_copied_in_window}; +use labels::{left_to_labels, note_copies_before_labels, run_after_labels, take_command_after_labels, watch_label_copies}; use paste::unclip_chords; pub(crate) use paste::{PasteChord, paste_command}; pub(crate) use presentation::presentation_step; @@ -195,6 +200,14 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context) { return; } ctx.input(|i| crate::shortcut_editor::note_backtick_text(&i.events)); + // A Copy or Cut the last pass left to labels that copied nothing runs now, whatever this + // frame's keys do. The text it copies goes out now, so it is not taken for a label's copy. + watch_label_copies(ctx); + if let Some(c) = take_command_after_labels(ctx) { + run_after_labels(app, c); + app.flush_clipboard_out(ctx); + } + note_copies_before_labels(ctx); note_key_surfaces(app, ctx); forget_opening_key(ctx); let focused = ctx.input(|input| input.focused) || app.forwarded_frame && ctx.viewport_id() == egui::ViewportId::ROOT; @@ -341,7 +354,11 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context) { crate::ime::controls_without_editor(app, ctx); return; } - ctx.input_mut(unclip_chords); + // The Copy or Cut the menu bar left to the labels came from no key: unclipped, the menu's Cut + // would become a plain X press (Toggle Fill/Stroke Focus). + if left_to_labels(ctx).is_none() { + ctx.input_mut(unclip_chords); + } // Tab is ours when no field has the keyboard (it shows and hides the panels, or goes to the // Type tool): left to egui, it would also move the focus on to a field, and every key after it // would count as typing. @@ -357,7 +374,7 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context) { return; } crate::ime::controls_without_editor(app, ctx); - handle_clipboard(app, ctx, textless_paste); + let to_labels = handle_clipboard(app, ctx, textless_paste); if busy { busy_tool_keys(app, ctx, view); return; @@ -377,10 +394,12 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context) { }; // An Escape that ended a ruler-origin drag or floating Tools move runs no command bound to it. let gesture_escape = |chord: &craft_keymap::Chord| escape_ended_gesture && chord.is_plain() && chord.key == craft_keymap::Key::Escape; + // A Copy or Cut left to the labels runs neither command from the keymap. + let labels_clip = |hit: &Hit| to_labels && matches!(hit.command.id.as_str(), "edit.copy" | "edit.cut"); let hits = dispatch(app, ctx, |hit| { let chord = &hit.trigger.chord; let shifted_punctuation = chord.mods.shift && chord.key.name().chars().all(|c| !c.is_alphanumeric()); - !(chord.is_plain() && types_text(chord.key) && !shifted_punctuation || row_key(chord) || gesture_escape(chord)) + !(chord.is_plain() && types_text(chord.key) && !shifted_punctuation || row_key(chord) || gesture_escape(chord) || labels_clip(hit)) }); let ran = !hits.is_empty(); for hit in hits { @@ -767,8 +786,9 @@ fn nudge_and_clear(app: &mut VectorcraftApp, ctx: &egui::Context, rows_keys: boo } } -/// Route clipboard events to the system clipboard or the app's rich-format paste path. -fn handle_clipboard(app: &mut VectorcraftApp, ctx: &egui::Context, textless_paste: Option) { +/// Route clipboard events to the system clipboard or the app's rich-format paste path. → whether +/// a Copy or Cut is left to the labels, so no shortcut runs it. +fn handle_clipboard(app: &mut VectorcraftApp, ctx: &egui::Context, textless_paste: Option) -> bool { // A clipboard image (eframe's `clipboard` feature, 0.37): the host's text paste path never // carries it. With the app's rich-format `SystemClipboard`, it is only the signal that the // clipboard holds no text — the next tick invokes Paste, whose `adopt_system_clipboard` reads @@ -817,14 +837,30 @@ fn handle_clipboard(app: &mut VectorcraftApp, ctx: &egui::Context, textless_past let held = ctx.input(|i| i.modifiers); app.clipboard_in = Some(Flavour { mime: vectorcraft_engine::cmd::clipboard::PNG, data: png }); crate::menus::invoke(app, paste_command(held), json!({})); - return; + return false; } - // Clipboard keys arrive as events, not key presses; the chord held says which paste. + // Clipboard keys arrive as events, not key presses; the chord held says which paste. Copy and + // Cut with text selected in a label copy that text ([`leave_to_labels`]), unless another window + // sent them on (a floating document's): those copy the art. The menu bar's Copy and Cut have + // left theirs to the labels already and dropped the unwritten formats; dropping them again + // here does nothing more. let mut clip = vec![]; + let forwarded = app.forwarded_clipboard && ctx.viewport_id() == egui::ViewportId::ROOT; + let to_labels = |e: egui::Event, id| { + ctx.input(|i| i.events.contains(&e)) && (left_to_labels(ctx) == Some(id) || (!forwarded && leave_to_labels(app, ctx, id))) + }; + let (labels_copy, labels_cut) = (to_labels(egui::Event::Copy, "edit.copy"), to_labels(egui::Event::Cut, "edit.cut")); + // The labels' text, or the art copied in the next pass when they copy nothing, replaces what an + // earlier Copy or Cut has not written yet. + if labels_copy || labels_cut { + app.drop_unwritten_formats(); + } ctx.input_mut(|i| { let held = i.modifiers; i.events.retain(|e| { let (id, text) = match e { + egui::Event::Copy if labels_copy => return true, + egui::Event::Cut if labels_cut => return true, egui::Event::Copy => ("edit.copy", None), egui::Event::Cut => ("edit.cut", None), egui::Event::Paste(t) => (paste_command(held), Some(t.clone())), @@ -844,6 +880,34 @@ fn handle_clipboard(app: &mut VectorcraftApp, ctx: &egui::Context, textless_past app.clipboard_in = text.map(|t| Flavour { mime: TEXT, data: t.into_bytes() }); crate::menus::invoke(app, id, json!({})); } + labels_copy || labels_cut +} + +/// Copy or Cut (`id`) on a key that egui does not send as a Copy or Cut event (F3 and F2 off +/// macOS, a key of the user's own): with text selected in a label, the labels copy it, as they do +/// for Cmd/Ctrl+C and X ([`leave_to_labels`]) (→ true). When a key another window sent on in this +/// frame (a floating document's) runs `id`, the art is copied. +fn clipboard_key_to_labels(app: &mut VectorcraftApp, ctx: &egui::Context, id: &str) -> bool { + let (command, event) = match id { + "edit.copy" => ("edit.copy", egui::Event::Copy), + "edit.cut" => ("edit.cut", egui::Event::Cut), + _ => return false, + }; + if ctx.viewport_id() == egui::ViewportId::ROOT && forwarded_key_runs(app, command) || !leave_to_labels(app, ctx, command) { + return false; + } + ctx.input_mut(|i| i.events.push(event)); + app.drop_unwritten_formats(); + true +} + +/// Does a key press another window sent on in this frame run command `id`? +fn forwarded_key_runs(app: &VectorcraftApp, id: &str) -> bool { + let mirror = crate::shortcut_editor::current(); + let platform = crate::keymap::platform(); + app.forwarded_presses.iter().filter_map(|e| craft_keymap::KeyInput::from_egui(e, platform)).any(|input| { + app.dispatcher.layout().candidates(&input).iter().any(|chord| crate::keymap::lookup(&mirror.keymap, chord).is_some_and(|c| c.id == id)) + }) } /// Route arrows, digits and letters to a tool while a gesture is active. @@ -1130,6 +1194,8 @@ fn run_hit(app: &mut VectorcraftApp, ctx: &egui::Context, c: &CommandRef) { // With the Artboard tool, Select All's keys after a click on an Artboards panel row select // every artboard instead of the art. crate::panels::artboards::select_all(app); + } else if clipboard_key_to_labels(app, ctx, &c.id) { + // The labels copy their selected text at the end of the pass. } else { match menu_target(app, c) { Some(Ok((id, p))) => crate::menus::invoke(app, &id, p), diff --git a/crates/ui-egui/src/shortcuts/labels.rs b/crates/ui-egui/src/shortcuts/labels.rs new file mode 100644 index 0000000000..9f4f9466fc --- /dev/null +++ b/crates/ui-egui/src/shortcuts/labels.rs @@ -0,0 +1,179 @@ +use egui::text_selection::LabelSelectionState; +use serde_json::json; +use vectorcraft_doc::{NodeId, Selection}; + +use crate::VectorcraftApp; + +/// A Copy or Cut command left to the labels, with the active document (its `uid`) and the +/// selection it was given then. +#[derive(Clone, Default)] +pub(super) struct LeftToLabels { + id: &'static str, + given: Option<(u64, Selection)>, +} + +/// The Copy or Cut command left to the labels of viewport `viewport` in this pass. +fn waiting_id(viewport: egui::ViewportId) -> egui::Id { + egui::Id::unique(("copy-waits-for-labels", viewport)) +} + +/// How many texts viewport `viewport` had copied in this pass before its labels could copy theirs. +fn copies_before_labels_id(viewport: egui::ViewportId) -> egui::Id { + egui::Id::unique(("copies-before-labels", viewport)) +} + +/// The texts copied in this pass of the current viewport so far. +fn copies(ctx: &egui::Context) -> usize { + ctx.output(|o| o.commands.iter().filter(|c| matches!(c, egui::OutputCommand::CopyText(_))).count()) +} + +/// Note the texts copied in this pass so far (the art's, by a Copy or Cut that labels left to this +/// pass): a copy at the end of the pass beyond them is the labels'. +pub(super) fn note_copies_before_labels(ctx: &egui::Context) { + let (id, n) = (copies_before_labels_id(ctx.viewport_id()), copies(ctx)); + ctx.data_mut(|d| d.insert_temp(id, n)); +} + +/// The Copy or Cut command to run in the next pass: the labels it was left to copied nothing. +fn after_labels_id() -> egui::Id { + egui::Id::unique("copy-after-labels") +} + +/// Set when a label in a window of its own (a floating panel's) copied its selected text: the +/// window then sends the Copy or Cut on to the main window ([`crate::panel_docking::forward_keys`]). +/// It lasts until the main window's next pass starts. +fn copied_in_window_id() -> egui::Id { + egui::Id::unique("labels-copied-in-window") +} + +/// Watch the labels' copies from the next pass on ([`leave_to_labels`]). egui runs a plugin only +/// from the pass after the one that adds it. +pub(super) fn watch_label_copies(ctx: &egui::Context) { + if ctx.plugin_opt::().is_none() { + ctx.add_plugin(CopyAfterLabels); + } +} + +/// Copy or Cut `command` (`edit.copy`, `edit.cut`) while text is selected in a label, such as a +/// Document Info value or an Info panel readout: egui copies that text when the Copy or Cut event +/// reaches the labels, so the event is left in the input for them (→ true). When no label of this +/// viewport copies anything in this pass (the selected text is in another window, or its label is +/// not drawn), `command` runs in the next pass ([`take_command_after_labels`]), on the selection of +/// `app`'s active document now ([`run_after_labels`]). +pub(crate) fn leave_to_labels(app: &VectorcraftApp, ctx: &egui::Context, command: &'static str) -> bool { + let selected = ctx.with_plugin(|s: &mut LabelSelectionState| s.has_selection()).unwrap_or(false); + if !selected || ctx.plugin_opt::().is_none() { + return false; + } + let id = waiting_id(ctx.viewport_id()); + let given = active_selection(app); + ctx.data_mut(|d| d.insert_temp(id, LeftToLabels { id: command, given })); + true +} + +/// The `uid` of `app`'s active document and its selection. +fn active_selection(app: &VectorcraftApp) -> Option<(u64, Selection)> { + app.session.active().map(|st| (st.uid, st.selection.clone())) +} + +/// The Copy or Cut command left to this viewport's labels in this pass, if any. +pub(super) fn left_to_labels(ctx: &egui::Context) -> Option<&'static str> { + let id = waiting_id(ctx.viewport_id()); + ctx.data(|d| d.get_temp::(id)).map(|c| c.id) +} + +/// The Copy or Cut command an earlier pass left to labels that copied nothing. +pub(super) fn take_command_after_labels(ctx: &egui::Context) -> Option { + ctx.data_mut(|d| d.remove_temp::(after_labels_id())) +} + +/// Run Copy or Cut `c`, which labels left to this pass, on the selection it was given. A selection +/// made in the same frame after it (a Select All) comes back after it, without the objects a Cut +/// removed and with the pieces it left of a path it split. With another document active by now, +/// or none, it does not run. +pub(super) fn run_after_labels(app: &mut VectorcraftApp, c: LeftToLabels) { + let Some((doc, given)) = c.given else { + crate::menus::invoke(app, c.id, json!({})); + return; + }; + match active_selection(app) { + None => {} + Some((active, _)) if active != doc => {} + Some((_, now)) if now != given => { + if let Err(e) = app.session.select(|_, sel| *sel = given.clone()) { + app.status(e.to_string()); + return; + } + let before = app.session.active().map(|st| st.doc.clone()); + crate::menus::invoke(app, c.id, json!({})); + // The pieces a Cut left of a path it split are new objects: they join the later + // selection when it held an object the Cut acted on. + let acted_on = given.objects.iter().any(|id| now.contains(*id)); + let pieces: Vec = match (before, app.session.active()) { + (Some(before), Some(st)) if acted_on => st.selection.objects.iter().copied().filter(|id| before.node(*id).is_none()).collect(), + _ => vec![], + }; + if let Err(e) = app.session.select(|_, sel| { + *sel = now; + sel.add_all(pieces); + }) { + app.status(e.to_string()); + } + } + _ => crate::menus::invoke(app, c.id, json!({})), + } +} + +/// Note that a floating panel's window copied its label text, as [`CopyAfterLabels`] does. +#[cfg(test)] +pub(crate) fn note_copied_in_window(ctx: &egui::Context) { + ctx.data_mut(|d| d.insert_temp(copied_in_window_id(), true)); +} + +/// Did a label in another window copy its selected text since the last call? The Copy or Cut that +/// window sends on is then its own and copies nothing more. +pub(crate) fn take_copied_in_window(ctx: &egui::Context) -> bool { + ctx.data_mut(|d| d.remove_temp::(copied_in_window_id())).unwrap_or(false) +} + +/// Runs after egui's label text selection at the end of each pass, when the labels have copied +/// their selected text. +struct CopyAfterLabels; + +impl egui::Plugin for CopyAfterLabels { + fn debug_name(&self) -> &'static str { + "CopyAfterLabels" + } + + /// The windows of their own run their passes inside the main window's pass, and their Copy or + /// Cut is sent on in that pass: a copy noted before it is not theirs. + fn on_begin_pass(&mut self, ui: &mut egui::Ui) { + if ui.ctx().viewport_id() == egui::ViewportId::ROOT { + take_copied_in_window(ui.ctx()); + } + } + + fn on_end_pass(&mut self, ui: &mut egui::Ui) { + let ctx = ui.ctx(); + // The art a Copy or Cut copied earlier in this pass is not the labels' copy. + let before_id = copies_before_labels_id(ctx.viewport_id()); + let before = ctx.data_mut(|d| d.remove_temp::(before_id)).unwrap_or(0); + let copied = copies(ctx) > before; + // A field with the keyboard copies its own text, and its window sends nothing on. + if ctx.viewport_id() != egui::ViewportId::ROOT + && copied + && ctx.memory(|m| m.focused().is_none()) + && ctx.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::Copy | egui::Event::Cut))) + { + ctx.data_mut(|d| d.insert_temp(copied_in_window_id(), true)); + } + let id = waiting_id(ctx.viewport_id()); + let Some(command) = ctx.data_mut(|d| d.remove_temp::(id)) else { + return; + }; + if !copied { + ctx.data_mut(|d| d.insert_temp(after_labels_id(), command)); + ctx.request_repaint(); + } + } +} diff --git a/crates/ui-egui/src/shortcuts/tests.rs b/crates/ui-egui/src/shortcuts/tests.rs index 5dbdc46a14..336af45e3d 100644 --- a/crates/ui-egui/src/shortcuts/tests.rs +++ b/crates/ui-egui/src/shortcuts/tests.rs @@ -1398,6 +1398,82 @@ fn copy_and_paste_events_use_the_system_clipboard() { assert_eq!(app.session.doc().unwrap().doc.layers[0].children().unwrap().len(), 8); } +/// #8432: a window of its own (a floating panel's) notes that its labels copied the text a Copy +/// asked for, so that the Copy it sends on to the main window copies nothing more. A field with +/// the keyboard copying its own text is not noted, and a note lasts only until the main window's +/// next pass, so it never drops a later Copy from another window. +#[test] +fn a_window_notes_only_its_labels_copies_until_the_next_main_window_pass() { + let ctx = egui::Context::default(); + watch_label_copies(&ctx); + let main_window_pass = || ctx.run_ui(egui::RawInput::default(), |_| {}).drop_without_applying_deltas(); + main_window_pass(); + let window = egui::ViewportId::from_hash_of("floating panel"); + let mut window_input = egui::RawInput { viewport_id: window, events: vec![egui::Event::Copy], ..Default::default() }; + window_input.viewports.insert(window, egui::ViewportInfo { parent: Some(egui::ViewportId::ROOT), ..Default::default() }); + // `field`: the text is copied by a field with the keyboard instead of a label. + let copy_in_window = |field: bool| { + ctx.run_ui(window_input.clone(), |ui| { + if field { + let mut text = String::from("234 pt"); + ui.text_edit_singleline(&mut text).request_focus(); + } + ui.ctx().copy_text("234 pt".into()); + }) + .drop_without_applying_deltas(); + }; + copy_in_window(false); + assert!(take_copied_in_window(&ctx), "the window's label copied the text"); + assert!(!take_copied_in_window(&ctx), "once"); + copy_in_window(false); + main_window_pass(); + assert!(!take_copied_in_window(&ctx), "the main window's next pass forgets the note"); + copy_in_window(true); + assert!(!take_copied_in_window(&ctx), "a field's copy is not noted"); +} + +/// #8432: text selected by a drag across a label in a window of its own, then copied there, is +/// noted as that window's labels' copy. +#[test] +fn a_window_notes_a_copy_of_text_dragged_across_its_label() { + let ctx = egui::Context::default(); + watch_label_copies(&ctx); + ctx.run_ui(egui::RawInput::default(), |_| {}).drop_without_applying_deltas(); + let window = egui::ViewportId::from_hash_of("floating panel"); + let rect = std::cell::Cell::new(egui::Rect::NOTHING); + let time = std::cell::Cell::new(0.0); + // One pass of the window with `events`: the texts it copied. + let pass = |events: Vec| { + time.set(time.get() + 0.1); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(400.0, 200.0)); + let mut input = egui::RawInput { viewport_id: window, events, time: Some(time.get()), screen_rect: Some(screen), ..Default::default() }; + input.viewports.insert(window, egui::ViewportInfo { parent: Some(egui::ViewportId::ROOT), ..Default::default() }); + let out = ctx.run_ui(input, |ui| rect.set(ui.label("234 pt").rect)); + let copied: Vec = out + .platform_output + .commands + .iter() + .filter_map(|c| if let egui::OutputCommand::CopyText(t) = c { Some(t.clone()) } else { None }) + .collect(); + out.drop_without_applying_deltas(); + copied + }; + pass(vec![]); + let (from, to) = (rect.get().left_center() + egui::vec2(1.0, 0.0), rect.get().right_center() - egui::vec2(1.0, 0.0)); + let button = + |at, pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + pass(vec![egui::Event::PointerMoved(from)]); + pass(vec![button(from, true)]); + for k in 1..=4 { + pass(vec![egui::Event::PointerMoved(from + (to - from) * k as f32 / 4.0)]); + } + pass(vec![button(to, false)]); + pass(vec![]); + assert!(!take_copied_in_window(&ctx), "nothing copied yet"); + assert_eq!(pass(vec![egui::Event::Copy]), ["234 pt"], "the label copies its selected text"); + assert!(take_copied_in_window(&ctx), "the window's label copy is noted"); +} + /// While a grid is dragged out, ↑/↓ change its rows and ←/→ its columns. #[test] fn arrows_while_dragging_a_grid_change_its_rows_and_columns() { diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index d2bc85ba9a..774adc3234 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -274,6 +274,10 @@ pub struct ViewFlags { pub trim_view: bool, /// View → Hide/Show Corner Widget (live corner widgets on rectangles). pub corner_widgets: bool, + /// The Control bar's Hide/Show Shape Widgets with a shape tool: selected live shapes' corner, pie + /// and side widgets with the Selection tool and the shape tools. + #[serde(default = "yes")] + pub shape_widgets: bool, /// View → Snap to Pixel. pub snap_to_pixel: bool, /// View → Snap to Glyph. @@ -314,6 +318,7 @@ impl Default for ViewFlags { edges: true, trim_view: false, corner_widgets: true, + shape_widgets: true, snap_to_pixel: false, snap_to_glyph: false, text_threads: true, @@ -733,6 +738,9 @@ pub struct UiState { /// Engine preferences (Edit → Preferences), persisted alongside the UI state. #[serde(default)] pub engine_prefs: Value, + /// Native-picker-only raster editor; never exposed as an engine preference or dialog field. + #[serde(default)] + pub original_editor: crate::OriginalEditorChoice, /// Color Guide panel: variation kind, steps and amount (Color Guide Options). #[serde(default)] pub color_guide: vectorcraft_color::harmony::GuideOptions, @@ -844,6 +852,9 @@ pub struct UiState { /// The EPS Options chosen last (`document.exportEps` options; null: never used). #[serde(default)] pub eps_options: Value, + /// The HP-GL Options chosen last (`document.export` HP-GL options; null: never used). + #[serde(default)] + pub hpgl_options: Value, /// The Offset Path fields confirmed last (offset, joins, miterLimit; null: never used): its /// dialog opens on them (#1152). #[serde(default)] @@ -858,6 +869,10 @@ pub struct UiState { /// `preserveGrays`; null: never used): its dialog opens with them (#2960). #[serde(default)] pub recolor_preserve: Value, + /// The open Recolor Artwork dialog's own history of color edits (Undo Changes and Redo + /// Changes), empty again each time the dialog opens. + #[serde(skip)] + pub recolor_history: crate::dialogs::recolor::History, /// The Simplify dialog's fields confirmed last with "Open this dialog with these settings next /// time" ticked (null: not ticked): Object › Path › Simplify opens the dialog on them instead /// of the Simplify slider. @@ -1293,6 +1308,7 @@ impl Default for UiState { recent_commands: vec![], favorite_fonts: vec![], engine_prefs: Value::Null, + original_editor: Default::default(), color_guide: Default::default(), library_panels: vec![], flattener_preview: Default::default(), @@ -1321,10 +1337,12 @@ impl Default for UiState { links_search: None, dxf_options: Value::Null, eps_options: Value::Null, + hpgl_options: Value::Null, offset_path: Value::Null, smart_punctuation: Value::Null, average_join: Value::Null, recolor_preserve: Value::Null, + recolor_history: Default::default(), simplify: Value::Null, move_options: Value::Null, transform_each: Value::Null, diff --git a/crates/ui-egui/src/stylus.rs b/crates/ui-egui/src/stylus.rs index 9791839c85..0b27d24127 100644 --- a/crates/ui-egui/src/stylus.rs +++ b/crates/ui-egui/src/stylus.rs @@ -11,6 +11,9 @@ //! where winit drops which end of the pen is down, the app reads the pressure and the end from //! each pointer message of a pen before winit handles it. The canvas uses the pressure when a //! frame's events carry no touch force, and the tilt and rotation for each press, drag and release. +//! An airbrush pen's finger wheel comes with the tilt and rotation ([`PenPose::wheel`]) where the +//! host reads it: from XInput2 on X11 and from AppKit on macOS. The app does not read it on +//! Windows, whose pointer messages have no field for it, or in the web build. //! //! The feed also says which end of the pen moved. Turning the pen to its eraser end selects the //! Eraser tool, and turning it back to the tip selects the tool used before @@ -48,7 +51,7 @@ pub struct PenSample { pub pressure: f32, /// The pen is turned to its eraser end. pub eraser: bool, - /// The tilt and rotation the pen read, if any. + /// The tilt, rotation and finger wheel the pen read, if any. pub pose: PenPose, } @@ -342,19 +345,22 @@ mod tests { let feed = StylusFeed::default(); assert_eq!(feed.pose(), None); let pen = |pose| Some(PenSample { pressure: 0.4, pose, ..PenSample::default() }); - let leaning = PenPose { tilt: Some([-120.0, 30.0]), rotation: Some(-90.0) }; + let leaning = PenPose { tilt: Some([-120.0, 30.0]), rotation: Some(-90.0), wheel: None }; feed.set_sample(pen(leaning)); - assert_eq!(feed.pose(), Some(PenPose { tilt: Some([-90.0, 30.0]), rotation: Some(270.0) })); + assert_eq!(feed.pose(), Some(PenPose { tilt: Some([-90.0, 30.0]), rotation: Some(270.0), wheel: None })); assert_eq!(feed.held(), Some(0.4), "the pressure as before"); // Not a number: left out. A tiny negative rotation is 0, not 360. - feed.set_sample(pen(PenPose { tilt: Some([f32::NAN, 0.0]), rotation: Some(-1e-9) })); - assert_eq!(feed.pose(), Some(PenPose { tilt: None, rotation: Some(0.0) })); - feed.set_sample(pen(PenPose { tilt: None, rotation: Some(f32::INFINITY) })); - assert_eq!(feed.pose(), None, "a pen that reads neither"); + feed.set_sample(pen(PenPose { tilt: Some([f32::NAN, 0.0]), rotation: Some(-1e-9), wheel: None })); + assert_eq!(feed.pose(), Some(PenPose { rotation: Some(0.0), ..PenPose::default() })); + feed.set_sample(pen(PenPose { rotation: Some(f32::INFINITY), wheel: Some(f32::NAN), ..PenPose::default() })); + assert_eq!(feed.pose(), None, "a pen that reads none of them"); assert!(PenPose { rotation: Some(725.0), ..Default::default() }.sanitized().rotation == Some(5.0)); + // An airbrush pen's finger wheel, clamped to 0..1. + feed.set_sample(pen(PenPose { wheel: Some(1.25), ..PenPose::default() })); + assert_eq!(feed.pose(), Some(PenPose { wheel: Some(1.0), ..PenPose::default() })); // The eraser end reads them too. feed.set_sample(Some(PenSample { pressure: 0.4, eraser: true, pose: leaning })); - assert_eq!((feed.eraser(), feed.pose()), (Some(true), Some(PenPose { tilt: Some([-90.0, 30.0]), rotation: Some(270.0) }))); + assert_eq!((feed.eraser(), feed.pose()), (Some(true), Some(PenPose { tilt: Some([-90.0, 30.0]), rotation: Some(270.0), wheel: None }))); // A pen that reads no tilt (`set`), or a mouse: none. feed.set_sample(pen(leaning)); feed.set(Some(0.5)); @@ -383,7 +389,7 @@ mod tests { #[test] fn the_feed_keeps_the_pressure_of_each_move() { let feed = StylusFeed::default(); - let leaning = PenPose { tilt: Some([20.0, -10.0]), rotation: Some(400.0) }; + let leaning = PenPose { tilt: Some([20.0, -10.0]), rotation: Some(400.0), wheel: Some(0.75) }; for (p, pose) in [(0.2, PenPose::default()), (1.5, leaning), (0.4, PenPose::default())] { feed.set_move(PenSample { pressure: p, pose, ..PenSample::default() }); } diff --git a/crates/ui-egui/src/sysclip.rs b/crates/ui-egui/src/sysclip.rs index 1ef9a20e6a..eb5a258e12 100644 --- a/crates/ui-egui/src/sysclip.rs +++ b/crates/ui-egui/src/sysclip.rs @@ -343,11 +343,17 @@ impl VectorcraftApp { /// dropped, and the system clipboard keeps that copy. pub(crate) fn drop_formats_after_egui_copy(&mut self, ctx: &egui::Context) { let copied = ctx.output(|o| o.commands.iter().any(|c| matches!(c, egui::OutputCommand::CopyText(_) | egui::OutputCommand::CopyImage(_)))); - let publishing = &mut self.clipboard_publishing; if copied { - publishing.unwritten = None; + self.drop_unwritten_formats(); } - if copied && publishing.pending { + } + + /// Drop the formats of an earlier Copy or Cut that are not written yet: something else is + /// being copied (text through egui, the text selected in a label). + pub(crate) fn drop_unwritten_formats(&mut self) { + let publishing = &mut self.clipboard_publishing; + publishing.unwritten = None; + if publishing.pending { publishing.latest.fetch_add(1, Ordering::SeqCst); publishing.pending = false; } diff --git a/crates/ui-egui/src/tests/recolor.rs b/crates/ui-egui/src/tests/recolor.rs index 0d5bacd77c..9eda6674fe 100644 --- a/crates/ui-egui/src/tests/recolor.rs +++ b/crates/ui-egui/src/tests/recolor.rs @@ -1586,6 +1586,224 @@ fn row_context_menu_pick_from_swatches_and_limit_to_library() { } } +/// Whether the dialog's button `name` is disabled. +fn disabled(h: &egui_kittest::Harness<'_, VectorcraftApp>, name: &str) -> bool { + h.get_by_role_and_label(egui::accesskit::Role::Button, name).accesskit_node().is_disabled() +} + +/// Undo Changes and Redo Changes step back and forward through the dialog's own color edits, and +/// the art previews each step; the document's undo history is unchanged until OK, which records +/// one step. Both buttons start disabled, and a new edit after Undo Changes leaves nothing to redo. +#[test] +fn undo_and_redo_changes_step_through_the_dialogs_own_edits() { + let mut h = edit_harness(&["#ff0000", "#00ff00", "#0000ff"]); + let undo = h.state().session.doc().unwrap().history.undo.len(); + h.get_by_role_and_label(egui::accesskit::Role::Button, "Assign").click(); + h.run_steps(3); + assert!(disabled(&h, "Undo Changes") && disabled(&h, "Redo Changes"), "nothing to step to on opening"); + let state = |h: &egui_kittest::Harness<'_, VectorcraftApp>| (field(h.state(), "rows"), fills(h.state())); + let start = state(&h); + h.get_by_label("Randomly change color order").click(); + h.run_steps(3); + let first = state(&h); + assert_ne!(first, start, "the order changed and previews"); + h.get_by_label("Randomly change saturation and brightness").click(); + h.run_steps(3); + let second = state(&h); + assert_ne!(second, first); + assert!(!disabled(&h, "Undo Changes") && disabled(&h, "Redo Changes")); + for (button, want) in [("Undo Changes", &first), ("Undo Changes", &start), ("Redo Changes", &first), ("Redo Changes", &second)] { + h.get_by_role_and_label(egui::accesskit::Role::Button, button).click(); + h.run_steps(3); + assert_eq!(&state(&h), want, "{button}"); + } + assert_eq!(h.state().session.doc().unwrap().history.undo.len(), undo, "the dialog's steps leave the document's history alone"); + h.get_by_role_and_label(egui::accesskit::Role::Button, "Undo Changes").click(); + h.run_steps(3); + assert_eq!(state(&h), first); + assert!(!disabled(&h, "Redo Changes")); + h.get_by_label("Randomly change saturation and brightness").click(); + h.run_steps(3); + assert!(disabled(&h, "Redo Changes"), "a new edit leaves nothing to redo"); + let last = state(&h); + h.get_by_label("OK").click(); + h.run_steps(2); + let app = h.state_mut(); + assert!(app.ui.dialog.is_none()); + assert_eq!(fills(app), last.1, "OK keeps the edits"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1, "as one undo step"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(fills(app), start.1); + // A new opening has nothing to undo. + app.run("select.all", json!({})).unwrap(); + app.run("ui.recolorDialog", json!({})).unwrap(); + h.run_steps(3); + assert!(disabled(&h, "Undo Changes") && disabled(&h, "Redo Changes"), "nothing to step to on a new opening"); + h.get_by_label("Cancel").click(); + h.run_steps(2); +} + +/// A drag is one step from press to release: Undo Changes after dragging the Edit tab's Brightness +/// slider across several frames gives the rows the drag started on, with nothing left to undo. +#[test] +fn a_drag_is_one_step_of_undo_changes() { + let mut h = edit_harness(&["rgb 200 100 100", "rgb 100 200 200"]); + let rows = field(h.state(), "rows"); + let slider = widget_of_size(&h, vec2(220.0, 22.0)); + let v = new_hsb(h.state())[0][2]; + let at = egui::pos2(slider.left() + 4.0 + v * (slider.width() - 8.0), slider.center().y); + h.hover_at(at); + h.run_steps(1); + h.drag_at(at); + h.run_steps(1); + for k in 1..=6 { + h.hover_at(egui::pos2(at.x + 12.0 * k as f32, at.y)); + h.run_steps(1); + } + h.drop_at(egui::pos2(at.x + 72.0, at.y)); + h.run_steps(2); + assert_ne!(field(h.state(), "rows"), rows, "the drag changed the colors"); + h.get_by_role_and_label(egui::accesskit::Role::Button, "Undo Changes").click(); + h.run_steps(3); + assert_eq!(field(h.state(), "rows"), rows, "one Undo Changes goes back to before the drag"); + assert!(disabled(&h, "Undo Changes"), "the drag was one step"); + assert!(!disabled(&h, "Redo Changes")); +} + +/// Reset is a step of its own: Undo Changes gives back the rows Reset discarded. +#[test] +fn undo_changes_reverses_reset() { + let mut app = app(); + art(&mut app, &["#ff0000", "#00ff00", "#0000ff"]); + let mut h = assign_harness(app, json!({})); + let start = field(h.state(), "rows"); + h.get_by_label("Randomly change saturation and brightness").click(); + h.run_steps(3); + let edited = field(h.state(), "rows"); + assert_ne!(edited, start); + h.get_by_role_and_label(egui::accesskit::Role::Button, "Reset the rows to the artwork's colors").click(); + h.run_steps(3); + assert_eq!(field(h.state(), "rows"), start, "Reset reads the art's colors"); + h.get_by_role_and_label(egui::accesskit::Role::Button, "Undo Changes").click(); + h.run_steps(3); + assert_eq!(field(h.state(), "rows"), edited, "Undo Changes gives back the rows before Reset"); + h.get_by_role_and_label(egui::accesskit::Role::Button, "Redo Changes").click(); + h.run_steps(3); + assert_eq!(field(h.state(), "rows"), start, "Redo Changes resets them again"); +} + +/// `ui.recolorUndo` and `ui.recolorRedo` step the open dialog as its buttons do, also through a +/// field set without a frame between, and a new count of Colors is one step that restores the count +/// and the rows; outside the dialog they are an error, and a new opening has nothing to undo. +#[test] +fn the_recolor_undo_and_redo_commands_step_the_open_dialog() { + let mut app = app(); + let ctx = context(); + art(&mut app, &["#ff0000", "#e01010", "#0000ff", "#1010e0"]); + assert!(app.run("ui.recolorUndo", json!({})).is_err(), "no dialog open"); + // A field set before the dialog's first frame is a step back to the fields it opened with. + app.run("ui.recolorDialog", json!({})).unwrap(); + set(&mut app, "colors", json!(2)); + assert!(dialogs::recolor::can_step(&app, true) && !dialogs::recolor::can_step(&app, false), "Undo Changes can run before the first frame"); + let r = app.run("ui.recolorUndo", json!({})).unwrap(); + assert_eq!(r, json!({"changed": true, "canUndo": false, "canRedo": true})); + assert_eq!(field(&app, "colors"), Value::Null); + assert_eq!(field(&app, "rows").as_array().unwrap().len(), 4, "the rows of the art as it opened"); + dialogs::cancel(&mut app); + app.run("select.all", json!({})).unwrap(); + app.run("ui.recolorDialog", json!({})).unwrap(); + dialog_frame(&mut app, &ctx); + assert!(!dialogs::recolor::can_step(&app, true) && !dialogs::recolor::can_step(&app, false)); + let start = field(&app, "rows"); + assert_eq!(start.as_array().unwrap().len(), 4); + set(&mut app, "colors", json!(2)); + dialog_frame(&mut app, &ctx); + assert_eq!(field(&app, "rows").as_array().unwrap().len(), 2); + let two = field(&app, "rows"); + set(&mut app, "globalAdjust", json!({"saturation": -50})); + dialog_frame(&mut app, &ctx); + let r = app.run("ui.recolorUndo", json!({})).unwrap(); + assert_eq!(r, json!({"changed": true, "canUndo": true, "canRedo": true})); + assert_eq!((field(&app, "globalAdjust"), field(&app, "rows")), (Value::Null, two.clone())); + app.run("ui.recolorUndo", json!({})).unwrap(); + dialog_frame(&mut app, &ctx); + assert_eq!((field(&app, "colors"), field(&app, "rows")), (Value::Null, start.clone()), "the count and its rows, not reduced again"); + assert!(!dialogs::recolor::can_step(&app, true)); + assert_eq!(app.run("ui.recolorUndo", json!({})).unwrap()["changed"], json!(false)); + app.run("ui.recolorRedo", json!({})).unwrap(); + assert_eq!((field(&app, "colors"), field(&app, "rows")), (json!(2), two)); + // A field set without a frame between is a step before Undo Changes goes back. + set(&mut app, "method", json!("exact")); + assert_eq!(app.run("ui.recolorUndo", json!({})).unwrap()["changed"], json!(true)); + assert_eq!(field(&app, "method"), json!("scaleTints")); + dialogs::cancel(&mut app); + assert!(app.run("ui.recolorRedo", json!({})).is_err(), "Cancel closed the dialog"); + app.run("select.all", json!({})).unwrap(); + app.run("ui.recolorDialog", json!({})).unwrap(); + dialog_frame(&mut app, &ctx); + assert!(!dialogs::recolor::can_step(&app, true) && !dialogs::recolor::can_step(&app, false), "a new opening"); +} + +/// An edit made while the pointer is held from the dialog's first frame is a step from the fields +/// the dialog opened with, not where Undo Changes starts. +#[test] +fn an_edit_with_the_pointer_down_from_the_first_frame_is_a_step() { + let mut app = app(); + let ctx = context(); + art(&mut app, &["#ff0000", "#e01010", "#0000ff", "#1010e0"]); + app.run("ui.recolorDialog", json!({})).unwrap(); + let at = Pos2::new(2.0, 2.0); + let button = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + frame(&mut app, &ctx, vec![Event::PointerMoved(at), button(true)], 1.0, |app, ui| dialogs::show(app, ui.ctx())); + let start = field(&app, "rows"); + assert_eq!(start.as_array().unwrap().len(), 4); + set(&mut app, "colors", json!(2)); + frame(&mut app, &ctx, vec![], 2.0, |app, ui| dialogs::show(app, ui.ctx())); + frame(&mut app, &ctx, vec![button(false)], 3.0, |app, ui| dialogs::show(app, ui.ctx())); + assert_eq!(field(&app, "rows").as_array().unwrap().len(), 2); + let r = app.run("ui.recolorUndo", json!({})).unwrap(); + assert_eq!(r, json!({"changed": true, "canUndo": false, "canRedo": true})); + assert_eq!((field(&app, "colors"), field(&app, "rows")), (Value::Null, start)); +} + +/// Rows or weights set before the first frame, which the art's reduction then replaces or drops, +/// are no step: Undo Changes is not available and changes nothing. +#[test] +fn rows_and_weights_set_before_the_art_is_read_are_no_step() { + for (k, v) in [("rows", json!([{"to": "#123456"}])), ("weights", json!([25, 75]))] { + let mut app = app(); + art(&mut app, &["#ff0000", "#0000ff"]); + app.run("ui.recolorDialog", json!({})).unwrap(); + set(&mut app, k, v); + assert!(!dialogs::recolor::can_step(&app, true), "{k}: Undo Changes is not available"); + let r = app.run("ui.recolorUndo", json!({})).unwrap(); + assert_eq!(r, json!({"changed": false, "canUndo": false, "canRedo": false}), "{k}"); + assert!(!app.session.in_interaction(), "{k}: a step that changes nothing previews nothing"); + assert_eq!(field(&app, "rows").as_array().unwrap().len(), 2, "{k}: the rows of the art"); + } +} + +/// `ui.recolorUndo` and `ui.recolorRedo` preview the step they go to at once, without a frame +/// between, as the buttons do. +#[test] +fn the_recolor_undo_and_redo_commands_preview_the_step() { + let mut app = app(); + let ctx = context(); + art(&mut app, &["#ff0000", "#e01010", "#0000ff", "#1010e0"]); + app.run("ui.recolorDialog", json!({})).unwrap(); + dialog_frame(&mut app, &ctx); + let start = fills(&app); + set(&mut app, "globalAdjust", json!({"saturation": -100})); + dialog_frame(&mut app, &ctx); + let adjusted = fills(&app); + assert_ne!(adjusted, start, "the adjustment previews"); + app.run("ui.recolorUndo", json!({})).unwrap(); + assert_eq!(fills(&app), start, "Undo Changes previews the step before"); + app.run("ui.recolorRedo", json!({})).unwrap(); + assert_eq!(fills(&app), adjusted, "Redo Changes previews the step after"); + dialogs::cancel(&mut app); +} + /// With the Color Groups list shown, the Color Picker opened from a row and closed with Cancel /// leaves Recolor Artwork the size it was and where it was, in every frame. #[test] diff --git a/crates/ui-egui/src/tests/selectall.rs b/crates/ui-egui/src/tests/selectall.rs index e5efd535cd..238d49803e 100644 --- a/crates/ui-egui/src/tests/selectall.rs +++ b/crates/ui-egui/src/tests/selectall.rs @@ -1,7 +1,8 @@ //! Select All (Cmd+A) follows the keyboard, from the window and from the system menu bar (macOS): //! a focused text field selects its own text, the Type tool editing selects the text being edited, //! the Artboards panel selects every artboard after a click on one of its rows with the Artboard -//! tool, and only otherwise are all the objects selected. +//! tool, and only otherwise are all the objects selected. The clipboard keys follow it too: Copy +//! and Cut copy the text selected in a field or in a panel's label before the art. use egui::{Event, Key, Modifiers, PointerButton, Pos2, Rect, vec2}; use serde_json::json; @@ -14,6 +15,8 @@ struct App { app: VectorcraftApp, ctx: egui::Context, time: f64, + /// The window has the keyboard. + focused: bool, } impl App { @@ -23,7 +26,7 @@ impl App { app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); app.run("shape.rectangle", json!({"x": 200, "y": 150, "width": 20, "height": 20})).unwrap(); app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 37, "height": 40})).unwrap(); - let mut a = Self { app, ctx: egui::Context::default(), time: 0.0 }; + let mut a = Self { app, ctx: egui::Context::default(), time: 0.0, focused: true }; for _ in 0..3 { a.frame(vec![]); } @@ -34,12 +37,19 @@ impl App { /// host dispatches it before the app's logic. fn frame_with(&mut self, events: Vec, menu: Option<&str>) -> egui::FullOutput { self.time += 0.1; - let raw = egui::RawInput { + let mut raw = egui::RawInput { events, time: Some(self.time), + focused: self.focused, screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 850.0))), ..Default::default() }; + // As the hosts do: the keys another window sent on join this frame's input, and the frame + // after them goes back to the keyboard's modifiers. + let app = &self.app; + if !app.forwarded.is_empty() || app.forwarded_frame || app.forwarded_modifiers_held { + self.app.raw_input_hook(&self.ctx, &mut raw); + } let app = &mut self.app; let mut out = self.ctx.run_ui(raw, |ui| { if let Some(id) = menu { @@ -88,6 +98,10 @@ fn press(key: Key, modifiers: Modifiers) -> Event { Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers } } +fn release(key: Key) -> Event { + Event::Key { key, physical_key: None, pressed: false, repeat: false, modifiers: Modifiers::NONE } +} + fn click(at: Pos2, pressed: bool) -> Event { Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE } } @@ -260,6 +274,269 @@ fn the_clipboard_keys_in_a_focused_field_edit_its_text() { } } +/// The rectangle of the text `text` painted last in a frame's output. +fn text_rect(out: &egui::FullOutput, text: &str) -> Rect { + out.shapes + .iter() + .rev() + .find_map(|s| match &s.shape { + egui::Shape::Text(t) if t.galley.text() == text => Some(t.galley.rect.translate(t.pos.to_vec2())), + _ => None, + }) + .unwrap_or_else(|| panic!("no {text:?} painted")) +} + +/// Document Info open on its Objects category, after a few frames to lay it out: the last frame. +fn show_document_info(a: &mut App) -> egui::FullOutput { + a.app.run("window.panel", json!({"panel": "docInfo"})).unwrap(); + crate::panels::set_pstate(&a.ctx, "docinfo-category", "objects".to_string()); + let mut out = a.frame(vec![]); + for _ in 0..3 { + out = a.frame(vec![]); + } + out +} + +/// Drag across the label text `text` painted in `out`, selecting it: the frame after the drag. +fn select_label_text(a: &mut App, out: &egui::FullOutput, text: &str) -> egui::FullOutput { + let r = text_rect(out, text); + let (from, to) = (r.left_center() + vec2(1.0, 0.0), r.right_center() - vec2(1.0, 0.0)); + a.frame(vec![Event::PointerMoved(from)]); + a.frame(vec![click(from, true)]); + for k in 1..=4 { + a.frame(vec![Event::PointerMoved(from + (to - from) * k as f32 / 4.0)]); + } + a.frame(vec![click(to, false)]); + a.frame(vec![]) +} + +/// Cmd+C or Cmd+X (`e`): the chord's frame, then the frame after it, when the keys are let go. +fn clipboard_chord(a: &mut App, e: Event) -> (egui::FullOutput, egui::FullOutput) { + let out = a.frame(vec![Event::ModifiersChanged(Modifiers::COMMAND), e]); + (out, a.frame(vec![Event::ModifiersChanged(Modifiers::NONE)])) +} + +/// #8432: with a Document Info value's text selected, Copy and Cut (Cmd+C and Cmd+X, F3 and F2, +/// or the menu bar's items) copy that text and leave the art. When the selected label is not +/// drawn, Copy copies the art. +#[test] +fn copy_and_cut_copy_the_text_selected_in_a_panel_label() { + let mut a = App::new(); + let out = show_document_info(&mut a); + // The two rectangles' outlines: 2 × (20 + 20) + 2 × (37 + 40). + let length = "234 pt"; + let select = |a: &mut App, out: &egui::FullOutput| select_label_text(a, out, length); + let chord = clipboard_chord; + let out = select(&mut a, &out); + let (copy, after) = chord(&mut a, Event::Copy); + assert_eq!(copied(©), [length], "Copy copies the selected value"); + assert!(copied(&after).is_empty(), "and nothing after it"); + assert!(a.app.session.clipboard.is_empty(), "no art copied"); + let (cut, after) = chord(&mut a, Event::Cut); + assert_eq!(copied(&cut), [length], "Cut copies the selected value"); + assert!(copied(&after).is_empty(), "and nothing after it"); + assert_eq!(a.selected(), 1, "and leaves the art"); + assert!(a.app.session.clipboard.is_empty(), "no art cut"); + // Cut on a chord of the user's own that no other command has, which egui also sends as Cut: the + // keymap does not cut the art after the label. + let overrides = a.app.ui.shortcut_overrides.clone(); + crate::keymap::set_override(&mut a.app.ui.shortcut_overrides, "edit.cut", "Cmd+Alt+Shift+X"); + let cut = a.frame(vec![Event::ModifiersChanged(Modifiers::COMMAND | Modifiers::ALT | Modifiers::SHIFT), Event::Cut]); + a.frame(vec![Event::ModifiersChanged(Modifiers::NONE)]); + assert_eq!(copied(&cut), [length], "Cut on the user's chord copies the selected value"); + assert_eq!(a.selected(), 1, "and leaves the art"); + assert!(a.app.session.clipboard.is_empty(), "no art cut"); + // Copy and Cut on keys egui sends as key presses (F3 and F2, their keys off macOS). + crate::keymap::set_override(&mut a.app.ui.shortcut_overrides, "edit.copy", "F3"); + crate::keymap::set_override(&mut a.app.ui.shortcut_overrides, "edit.cut", "F2"); + for (key, what) in [(Key::F3, "Copy"), (Key::F2, "Cut")] { + let out = a.frame(vec![press(key, Modifiers::NONE)]); + let after = a.frame(vec![release(key)]); + assert_eq!(copied(&out), [length], "{what} on {key:?} copies the selected value"); + assert!(copied(&after).is_empty(), "and nothing after it"); + assert_eq!(a.selected(), 1, "{what} on {key:?} leaves the art"); + assert!(a.app.session.clipboard.is_empty(), "no art copied or cut"); + } + // The menu bar's Edit › Copy and Edit › Cut (macOS). + for (id, what) in [("edit.copy", "Copy"), ("edit.cut", "Cut")] { + let menu = a.menu(id); + let after = a.frame(vec![]); + assert_eq!(copied(&menu), [length], "the menu's {what} copies the selected value"); + assert!(copied(&after).is_empty(), "and nothing after it"); + assert_eq!(a.selected(), 1, "the menu's {what} leaves the art"); + assert!(a.app.session.clipboard.is_empty(), "no art copied or cut"); + } + a.app.ui.shortcut_overrides = overrides; + // Tab hides the panels: the selected value is not drawn, so Copy copies the art, a frame later, + // even when the window has lost the keyboard by then. + select(&mut a, &out); + a.app.ui.dock = false; + let copy = a.frame(vec![Event::ModifiersChanged(Modifiers::COMMAND), Event::Copy]); + a.focused = false; + let after = a.frame(vec![Event::ModifiersChanged(Modifiers::NONE)]); + a.focused = true; + assert!(copied(©).is_empty(), "no label copied {length}"); + assert!(copied(&after).iter().any(|t| t.starts_with("| { + a.time += 0.1; + let screen = Rect::from_min_size(Pos2::ZERO, vec2(400.0, 200.0)); + let mut input = egui::RawInput { viewport_id: window, events, time: Some(a.time), screen_rect: Some(screen), ..Default::default() }; + input.viewports.insert(window, egui::ViewportInfo { parent: Some(egui::ViewportId::ROOT), ..Default::default() }); + a.ctx.run_ui(input, |ui| rect.set(ui.label("234 pt").rect)).drop_without_applying_deltas(); + }; + pass(a, vec![]); + let (from, to) = (rect.get().left_center() + vec2(1.0, 0.0), rect.get().right_center() - vec2(1.0, 0.0)); + pass(a, vec![Event::PointerMoved(from)]); + pass(a, vec![click(from, true)]); + for k in 1..=4 { + pass(a, vec![Event::PointerMoved(from + (to - from) * k as f32 / 4.0)]); + } + pass(a, vec![click(to, false)]); + pass(a, vec![]); +} + +/// The objects of the first layer of the active document. +fn objects(a: &App) -> usize { + a.app.session.active().unwrap().doc.layers[0].children().unwrap().len() +} + +/// #8432: with text selected in another window's label, Copy and then Cut in the main window's next +/// frame copy the art and then cut it: the art Copy runs in the Cut's frame, and its text is not +/// taken for a label's copy of the Cut. +#[test] +fn copy_then_cut_with_text_selected_in_another_window_copy_and_cut_the_art() { + let mut a = App::new(); + select_label_text_in_another_window(&mut a); + let copy = a.frame(vec![Event::ModifiersChanged(Modifiers::COMMAND), Event::Copy]); + let cut = a.frame(vec![Event::ModifiersChanged(Modifiers::COMMAND), Event::Cut]); + a.frame(vec![Event::ModifiersChanged(Modifiers::NONE)]); + assert!(copied(©).is_empty(), "no label of the main window copied the text"); + assert!(copied(&cut).iter().any(|t| t.starts_with(", modifiers: Modifiers| { + crate::panel_docking::forward_keys(&mut a.app, &a.ctx, keys, Some(modifiers)); + (a.frame(vec![]), a.frame(vec![])) + }; + crate::shortcuts::note_copied_in_window(&a.ctx); + let (copy, after) = forward(&mut a, vec![Event::Copy], Modifiers::COMMAND); + assert!(copied(©).is_empty() && copied(&after).is_empty(), "the window copied its own text"); + assert!(a.app.session.clipboard.is_empty(), "no art copied"); + let (copy, _) = forward(&mut a, vec![Event::Copy], Modifiers::COMMAND); + assert!(copied(©).iter().all(|t| t != length), "{length} was copied from the other window"); + assert!(!a.app.session.clipboard.is_empty(), "Copy from the other window copied the art"); + // F3 sent on from another window copies the art too. + let (copy, after) = forward(&mut a, vec![press(Key::F3, Modifiers::NONE), release(Key::F3)], Modifiers::NONE); + assert!(copied(©).iter().chain(&copied(&after)).all(|t| t != length), "{length} was copied by F3 from the other window"); + assert!(copied(©).iter().chain(&copied(&after)).any(|t| t.starts_with(" Pos2 { diff --git a/crates/ui-egui/src/tests/sysclip.rs b/crates/ui-egui/src/tests/sysclip.rs index c44bd24c03..6ae55087b8 100644 --- a/crates/ui-egui/src/tests/sysclip.rs +++ b/crates/ui-egui/src/tests/sysclip.rs @@ -164,6 +164,11 @@ pub(super) fn copy_rect(app: &mut VectorcraftApp) { run(app, "edit.copy", json!({})); } +/// How many times the app wrote the clipboard. +pub(super) fn writes(board: &Rc>) -> usize { + board.borrow().writes +} + pub(super) fn written(board: &Rc>) -> Vec<&'static str> { board.borrow().flavours.iter().map(|f| f.mime).collect() } @@ -579,6 +584,21 @@ fn text_copied_before_the_formats_are_written_stays_on_the_clipboard() { assert_eq!(t.plain_text(), "Words copied in a field"); } +/// Text a floating panel's label copies after Copy, before the formats are written: its window +/// keeps the Copy, the formats are not written, and the system clipboard keeps the text. +#[test] +fn label_text_copied_before_the_formats_are_written_stays_on_the_clipboard() { + let (mut app, board, hold) = app_with_busy_worker(""); + copy_rect(&mut app); + let ctx = egui::Context::default(); + crate::shortcuts::note_copied_in_window(&ctx); + crate::panel_docking::forward_keys(&mut app, &ctx, vec![egui::Event::Copy], Some(egui::Modifiers::COMMAND)); + assert!(app.forwarded.is_empty(), "the window's Copy stays there"); + drop(hold); + background::wait_all(&mut app); + assert_eq!(board.borrow().writes, 0); +} + /// The Edit menu's Paste into a text field after Copy of type, before the formats are written: it /// waits for them, not for a save started after them, and pastes the type's text, not what /// another app copied before. diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 80c82a6283..3b58363dc7 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", "circle"], + &["ellipse", "circle", "curvatureCircle"], &["polygon"], &["shaper"], ], @@ -352,7 +352,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, cols: usize, floating: Option Id { + Id::unique("tool-card-prefs") +} + +/// The button whose card a press, key or scroll put away, until the pointer leaves it. +fn quiet_id() -> Id { + Id::unique("tool-card-quiet") +} + +pub(crate) fn set_prefs(ctx: &Context, prefs: CardPrefs) { + ctx.data_mut(|d| d.insert_temp(prefs_id(), prefs)); +} + +fn prefs(ctx: &Context) -> CardPrefs { + ctx.data(|d| d.get_temp(prefs_id())).unwrap_or_default() +} + +/// Where a card goes beside its button: right of it (left when there is no room), or below it +/// (above when there is no room) for a row of buttons. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Side { + Beside, + Below, + /// Right of a flyout's row, clear of the grab bar down the flyout's right side. + Row, +} + +/// The hover help of the button `resp` for `tool`: its card with Show Tool Cards on when the tool +/// has a description and the window has room for the card beside the button, else `tip` as a +/// one-line tool tip (none: no tool tip). While a group's flyout +/// or the All Tools drawer is open, only the flyout's own rows show cards: a card beside another +/// button could sit over the flyout. +pub(crate) fn hover(resp: Response, tool: &ToolInfo, side: Side, tip: Option) -> Response { + let ctx = resp.ctx.clone(); + let prefs = prefs(&ctx); + let allowed = side == Side::Row || !flyout_drawn(&ctx); + let description = if prefs.on && allowed { tool_description(tool.id) } else { None }; + // A button the pointer is not on shows neither a card nor a tool tip. Its quiet mark goes, with + // the cards off too, so the next rest on it shows its card; and its card is not measured. + if !pointer_on(&ctx, &resp) { + forget_quiet(&ctx, &resp); + if description.is_some() { + return resp; + } + } + let place = description.and_then(|d| placement(&ctx, resp.rect, side, height(tool.id, prefs.animated_zoom)).map(|p| (d, p))); + let Some((description, (align, others, gap))) = place else { + return match tip { + Some(tip) => resp.on_hover_text(tip), + None => resp, + }; + }; + if quiet(&ctx, &resp) { + return resp; + } + let mut tooltip = egui::Tooltip::for_enabled(&resp).gap(gap); + tooltip.popup = tooltip.popup.align(align).align_alternatives(others).width(WIDTH); + tooltip.show(|ui| card(ui, tool, description, prefs.animated_zoom)); + resp +} + +/// Where the card of the button at `rect` goes: its alignment, the alignments to try when it does +/// not fit, and its gap from the button. None when the window has no room for it beside the button, +/// or above or below a row of buttons for a card about `height` tall (a card pushed back into the +/// window would cover the button or its flyout). +fn placement(ctx: &Context, rect: egui::Rect, side: Side, height: f32) -> Option<(RectAlign, &'static [RectAlign], f32)> { + let screen = ctx.content_rect(); + let right = |gap: f32| screen.right() - rect.right() - gap >= ROOM; + let left = |gap: f32| rect.left() - gap - screen.left() >= ROOM; + let below = screen.bottom() - rect.bottom() - GAP >= height; + let above = rect.top() - GAP - screen.top() >= height; + match side { + Side::Beside if right(GAP) => Some((RectAlign::RIGHT_START, &[RectAlign::RIGHT_END], GAP)), + Side::Beside if left(GAP) => Some((RectAlign::LEFT_START, &[RectAlign::LEFT_END], GAP)), + Side::Beside => None, + // On the side the flyout opened toward, never back over the button that opened it. + Side::Row if flyout_opens_left(ctx) => left(GAP).then_some((RectAlign::LEFT_START, &[RectAlign::LEFT_END], GAP)), + Side::Row => right(GAP + super::BAR).then_some((RectAlign::RIGHT_START, &[RectAlign::RIGHT_END], GAP + super::BAR)), + Side::Below if below => Some((RectAlign::BOTTOM_START, &[RectAlign::BOTTOM_END], GAP)), + Side::Below if above => Some((RectAlign::TOP_START, &[RectAlign::TOP_END], GAP)), + Side::Below => None, + } +} + +/// A generous estimate of a card's height, before it is laid out: the icon row, a description of +/// up to three lines and each hint line wrapped once, with the frame's margins. +fn height(tool: &str, animated_zoom: bool) -> f32 { + let hints = lines(tool, animated_zoom).len() as f32; + let hint_rows = if hints > 0.0 { 8.0 + hints * 2.0 * LINE } else { 0.0 }; + ICON + 20.0 + 3.0 * LINE + hint_rows +} + +/// Whether a tool group's flyout or the All Tools drawer drew in this pass or the one before. The +/// tool buttons draw before the flyout, so in a pass they read the mark of the pass before. +fn flyout_drawn(ctx: &Context) -> bool { + let pass = ctx.cumulative_pass_nr(); + ctx.data(|d| d.get_temp::(super::flyout_open_pass_id())).is_some_and(|p| p.saturating_add(1) >= pass) +} + +/// Whether the open flyout sits left of the button that opened it (a toolbar docked right). +fn flyout_opens_left(ctx: &Context) -> bool { + let anchor = ctx.data(|d| d.get_temp::(Id::unique("flyout-anchor"))); + let menu = ctx.memory(|m| m.area_rect(Id::unique("tool-flyout"))); + anchor.zip(menu).is_some_and(|(a, m)| m.center().x < a.center().x) +} + +/// Whether the card of `resp` stays away: the pointer is not resting on the button, a button or a +/// modifier key is held, or a press, key, modifier, scroll or pinch came since it arrived. +fn quiet(ctx: &Context, resp: &Response) -> bool { + let quiet_for: Option = ctx.data(|d| d.get_temp(quiet_id())); + if !pointer_on(ctx, resp) { + forget_quiet(ctx, resp); + return true; + } + let busy = ctx.input(|i| { + i.pointer.any_down() + || i.pointer.any_pressed() + || i.pointer.any_released() + || i.modifiers.any() + // The frame's raw events: the shortcuts, which run before the toolbar draws, take the + // keys they handle (such as the arrows that nudge the selection) out of `i.events`. + || i.raw.events.iter().any(|e| { + matches!( + e, + Event::Key { pressed: true, .. } + | Event::Text(_) + | Event::MouseWheel { .. } + | Event::ModifiersChanged(_) + | Event::Zoom(_) + | Event::Rotate(_) + ) + }) + }); + if busy { + ctx.data_mut(|d| d.insert_temp(quiet_id(), resp.id)); + return true; + } + quiet_for == Some(resp.id) +} + +/// Whether the pointer rests on the button `resp`. +fn pointer_on(ctx: &Context, resp: &Response) -> bool { + resp.hovered() && ctx.input(|i| i.pointer.hover_pos()).is_some_and(|p| resp.rect.contains(p)) +} + +/// Drops the quiet mark of `resp`, once the pointer has left it. +fn forget_quiet(ctx: &Context, resp: &Response) { + if ctx.data(|d| d.get_temp::(quiet_id())) == Some(resp.id) { + ctx.data_mut(|d| d.remove::(quiet_id())); + } +} + +/// The card: icon, name and shortcut; what the tool does; one line per action of its hint. +fn card(ui: &mut Ui, tool: &ToolInfo, description: &str, animated_zoom: bool) { + let t = Tokens::get(ui.ctx()); + // Every line wraps inside the width `placement` keeps free, long translated names included. + ui.set_max_width(WIDTH); + ui.horizontal(|ui| { + let (r, _) = ui.allocate_exact_size(vec2(ICON, ICON), Sense::hover()); + icons::paint(ui, icons::tool_icon(tool.icon), r, t.icon); + ui.add_space(4.0); + ui.add(egui::Label::new(RichText::new(super::tip(tool)).strong().color(t.text_strong)).wrap()); + }); + ui.add(egui::Label::new(RichText::new(tl!(description)).color(t.text)).wrap()); + let lines = lines(tool.id, animated_zoom); + if !lines.is_empty() { + ui.separator(); + } + for line in lines { + let mut job = egui::text::LayoutJob::default(); + job.wrap.max_width = ui.available_width(); + for (text, bold) in line { + let font = if bold { crate::theme::semibold(12.0) } else { egui::FontId::proportional(12.0) }; + job.append(&text, 0.0, egui::TextFormat { font_id: font, color: if bold { t.text_strong } else { t.text }, ..Default::default() }); + } + ui.label(job); + } +} + +/// The hint bar's segments for `tool`, one line per action: a line ends at a `|` in the hint's text. +pub(crate) fn lines(tool: &str, animated_zoom: bool) -> Vec> { + let mut lines = vec![]; + let mut line: Vec<(String, bool)> = vec![]; + for (text, bold) in crate::chrome::tool_hint(tool, animated_zoom).unwrap_or_default() { + if bold { + line.push((text.into_owned(), true)); + continue; + } + let mut parts = text.split('|').peekable(); + while let Some(part) = parts.next() { + let part = if line.is_empty() { part.trim_start() } else { part }; + let part = if parts.peek().is_some() { part.trim_end() } else { part }; + if !part.is_empty() { + line.push((part.to_string(), false)); + } + if parts.peek().is_some() && !line.is_empty() { + lines.push(std::mem::take(&mut line)); + } + } + } + if !line.is_empty() { + lines.push(line); + } + lines +} diff --git a/crates/ui-egui/src/toolbar/tests.rs b/crates/ui-egui/src/toolbar/tests.rs index 708e5e9807..4c8c25392d 100644 --- a/crates/ui-egui/src/toolbar/tests.rs +++ b/crates/ui-egui/src/toolbar/tests.rs @@ -989,6 +989,388 @@ fn a_floating_flyouts_buttons_have_tool_tips_when_tool_tips_are_on() { assert!(hovered_texts(&mut app, &ctx, 30.0, star).contains(&tip), "on again"); } +/// The window of the tool card tests. +const WINDOW: egui::Vec2 = vec2(400.0, 1200.0); + +/// One frame with the preferences applied, as the app runs it, in a window `size` points big: the +/// texts it paints, each with its rect. +fn painted_in(app: &mut VectorcraftApp, ctx: &egui::Context, time: f64, events: Vec, size: egui::Vec2) -> Vec<(String, egui::Rect)> { + painted_after(app, ctx, time, events, size, None) +} + +/// [`painted_in`], with `taken` (a key the shortcuts handle before the toolbar draws) taken out of +/// the frame's input first, as the shortcuts take it. +fn painted_after( + app: &mut VectorcraftApp, + ctx: &egui::Context, + time: f64, + events: Vec, + size: egui::Vec2, + taken: Option, +) -> Vec<(String, egui::Rect)> { + fn texts(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| texts(s, out)), + _ => {} + } + } + let raw = egui::RawInput { events, time: Some(time), screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, size)), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| { + crate::prefs_dialog::apply_runtime(app, ui.ctx()); + if let Some(key) = taken { + assert!(ui.ctx().input_mut(|i| i.consume_key(egui::Modifiers::NONE, key)), "{key:?} taken"); + } + show(app, ui); + }); + out.textures_delta.clear(); + let mut shown = vec![]; + out.shapes.iter().for_each(|c| texts(&c.shape, &mut shown)); + shown +} + +/// [`painted_in`] in [`WINDOW`], the texts alone. +fn painted_texts(app: &mut VectorcraftApp, ctx: &egui::Context, time: f64, events: Vec) -> Vec { + painted_in(app, ctx, time, events, WINDOW).into_iter().map(|(s, _)| s).collect() +} + +/// The description of the tool `id`, as its card shows it. +fn described(id: &str) -> String { + vectorcraft_tools::catalog::tool_description(id).unwrap_or_else(|| panic!("{id} has no description")).to_string() +} + +/// Rest the pointer on `at` from `t0`, in a window `size` points big, until the card of the tool +/// `id` shows; returns the time and the rect of the card's description. +fn until_card_in(app: &mut VectorcraftApp, ctx: &egui::Context, t0: f64, at: Pos2, id: &str, size: egui::Vec2) -> (f64, egui::Rect) { + let text = described(id); + painted_in(app, ctx, t0, vec![Event::PointerGone], size); + painted_in(app, ctx, t0 + 0.1, vec![Event::PointerMoved(at)], size); + let mut last = vec![]; + for i in 2..30 { + let time = t0 + f64::from(i) * 0.1; + last = painted_in(app, ctx, time, vec![], size); + if let Some((_, rect)) = last.iter().find(|(s, _)| *s == text) { + return (time, *rect); + } + } + last.retain(|(s, _)| !s.starts_with('⚠')); + panic!("no card for {id} on {at:?}: {last:?}"); +} + +/// Rest the pointer on `at` from `t0` for three seconds, in a window `size` points big: the texts of +/// each frame. +fn hovered_in(app: &mut VectorcraftApp, ctx: &egui::Context, t0: f64, at: Pos2, size: egui::Vec2) -> Vec> { + painted_in(app, ctx, t0, vec![Event::PointerGone], size); + let moved = painted_in(app, ctx, t0 + 0.1, vec![Event::PointerMoved(at)], size); + std::iter::once(moved).chain((2..30).map(|i| painted_in(app, ctx, t0 + f64::from(i) * 0.1, vec![], size))).collect() +} + +/// [`until_card_in`] in [`WINDOW`]. +fn until_card(app: &mut VectorcraftApp, ctx: &egui::Context, t0: f64, at: Pos2, id: &str) -> (f64, egui::Rect) { + until_card_in(app, ctx, t0, at, id, WINDOW) +} + +/// General › Show Tool Cards: a tool's tool tip becomes a card with its name and shortcut, what it +/// does, and one line per action of its hint, the modifier keys named for the platform. +#[test] +fn a_tool_card_shows_what_the_tool_does_and_what_its_keys_do() { + let lines = card::lines("selection", false); + let plain = |line: &Vec<(String, bool)>| line.iter().map(|(s, _)| s.as_str()).collect::(); + assert_eq!(lines.len(), 3, "{lines:?}"); + assert_eq!(plain(&lines[0]), "Click the object to select"); + let shift = crate::menus::shown_shortcut("Shift+Click"); + assert_eq!(lines[1], vec![(shift.clone(), true), (" to select multiple objects".to_string(), false)]); + assert!(plain(&lines[2]).ends_with(" the object to duplicate"), "{lines:?}"); + // A segment that runs on past a key keeps its pieces on one line. + let warp = card::lines("warp", false); + assert_eq!(warp.len(), 2, "{warp:?}"); + assert!(plain(&warp[1]).ends_with(" keeps its proportions)"), "{warp:?}"); + // The Zoom tool's card follows the animated zoom's hint. + assert_ne!(card::lines("zoom", false), card::lines("zoom", true)); + + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.run("prefs.set", json!({"key": "showToolCards", "value": true})).unwrap(); + let ctx = egui::Context::default(); + let selection = frame(&mut app, &ctx, 0.0, vec![])[0]; + let shown = hovered_texts(&mut app, &ctx, 1.0, selection.center()); + assert!(shown.contains(&described("selection")), "{shown:?}"); + assert!(shown.contains(&tip(tool_info("selection").unwrap())), "{shown:?}"); + assert!(shown.contains(&format!("{shift} to select multiple objects")), "{shown:?}"); + // The card sits beside its button, inside the window. + let (_, text) = until_card(&mut app, &ctx, 10.0, selection.center(), "selection"); + let window = egui::Rect::from_min_size(Pos2::ZERO, WINDOW); + assert!(text.left() >= selection.right() && window.contains_rect(text), "{text:?} beside {selection:?}"); +} + +/// A tool without a description keeps its one-line tool tip with the cards on; with the cards off +/// (the default), or tool tips off, no card shows. +#[test] +fn tool_cards_are_off_by_default_and_fall_back_to_the_tool_tip() { + assert!(!Session::new().prefs.show_tool_cards, "off by default"); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + let ctx = egui::Context::default(); + let rects = frame(&mut app, &ctx, 0.0, vec![]); + let (selection, lasso) = (rects[0].center(), rects[2].center()); + let selection_tip = tip(tool_info("selection").unwrap()); + let off = hovered_texts(&mut app, &ctx, 1.0, selection); + assert!(off.contains(&selection_tip) && !off.contains(&described("selection")), "off: the tool tip, {off:?}"); + + app.run("prefs.set", json!({"key": "showToolCards", "value": true})).unwrap(); + assert_eq!(vectorcraft_tools::catalog::tool_description("lasso"), None); + let lasso_tip = tip(tool_info("lasso").unwrap()); + assert!(hovered_texts(&mut app, &ctx, 10.0, lasso).contains(&lasso_tip), "no description: the tool tip"); + + app.session.prefs.show_tool_tips = false; + let none = hovered_texts(&mut app, &ctx, 20.0, selection); + assert!(!none.contains(&described("selection")) && !none.contains(&selection_tip), "tool tips off: {none:?}"); +} + +/// A card that is showing goes away when tool tips are turned off, while the pointer stays on its +/// button. +#[test] +fn a_shown_tool_card_goes_away_when_tool_tips_are_turned_off() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.run("prefs.set", json!({"key": "showToolCards", "value": true})).unwrap(); + let ctx = egui::Context::default(); + let selection = frame(&mut app, &ctx, 0.0, vec![])[0].center(); + let (time, _) = until_card(&mut app, &ctx, 1.0, selection, "selection"); + app.run("prefs.set", json!({"key": "showToolTips", "value": false})).unwrap(); + let after: Vec = (1..5).flat_map(|i| painted_texts(&mut app, &ctx, time + f64::from(i) * 0.1, vec![])).collect(); + assert!(!after.contains(&described("selection")), "{after:?}"); + + // A card a click put away stays away while the pointer rests on its button, and shows again on + // the next rest when the pointer left and came back while tool tips were off. + app.run("prefs.set", json!({"key": "showToolTips", "value": true})).unwrap(); + let (t, _) = until_card(&mut app, &ctx, 10.0, selection, "selection"); + let b = |pressed| Event::PointerButton { pos: selection, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + painted_texts(&mut app, &ctx, t + 0.1, vec![b(true)]); + painted_texts(&mut app, &ctx, t + 0.15, vec![b(false)]); + // Tool tips off and on again while the pointer stays: the card stays away. + app.run("prefs.set", json!({"key": "showToolTips", "value": false})).unwrap(); + painted_texts(&mut app, &ctx, t + 0.2, vec![]); + app.run("prefs.set", json!({"key": "showToolTips", "value": true})).unwrap(); + let stayed: Vec = (3..30).flat_map(|i| painted_texts(&mut app, &ctx, t + f64::from(i) * 0.1, vec![])).collect(); + assert!(!stayed.contains(&described("selection")), "{stayed:?}"); + let t = t + 3.0; + app.run("prefs.set", json!({"key": "showToolTips", "value": false})).unwrap(); + painted_texts(&mut app, &ctx, t + 0.2, vec![Event::PointerGone]); + // Back onto the button. + painted_texts(&mut app, &ctx, t + 0.3, vec![Event::PointerMoved(selection + vec2(2.0, 2.0))]); + painted_texts(&mut app, &ctx, t + 0.35, vec![Event::PointerMoved(selection)]); + app.run("prefs.set", json!({"key": "showToolTips", "value": true})).unwrap(); + let again: Vec = (4..30).flat_map(|i| painted_texts(&mut app, &ctx, t + f64::from(i) * 0.1, vec![])).collect(); + assert!(again.contains(&described("selection")), "{again:?}"); +} + +/// A card never gets in the way: a press with it showing picks the tool and puts the card away at +/// once, it stays away until the pointer leaves, a key (one the shortcuts take first too), a +/// modifier key alone and a scroll put it away, a long press with it showing still opens a group's flyout on time, while that flyout is +/// open the other buttons show their one-line tool tips and the flyout's rows show cards past its +/// bar, and a press held from off the toolbar (as a drag on the canvas holds one) shows none. +#[test] +fn a_tool_card_never_gets_in_the_way() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.run("prefs.set", json!({"key": "showToolCards", "value": true})).unwrap(); + let ctx = egui::Context::default(); + let rects = frame(&mut app, &ctx, 0.0, vec![]); + let (selection, direct, shapes) = (rects[0].center(), rects[1].center(), rects[3].center()); + let has_card = |shown: &Vec, id: &str| shown.contains(&described(id)); + let b = |pos, pressed| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + + // A click with the card showing picks the tool and does nothing else. + assert_eq!(app.session.tool_id(), "selection"); + let (t, _) = until_card(&mut app, &ctx, 1.0, direct, "directSelection"); + assert!(!has_card(&painted_texts(&mut app, &ctx, t + 0.1, vec![b(direct, true)]), "directSelection"), "gone on the press"); + assert!(!has_card(&painted_texts(&mut app, &ctx, t + 0.15, vec![b(direct, false)]), "directSelection")); + assert_eq!(app.session.tool_id(), "directSelection", "the click picked the tool"); + assert_eq!(app.ui.flyout, None, "and did nothing else"); + for i in 0..20 { + let shown = painted_texts(&mut app, &ctx, t + 0.2 + f64::from(i) * 0.1, vec![]); + assert!(!has_card(&shown, "directSelection"), "stays away while the pointer rests there"); + } + + // A key, a modifier key alone and a scroll each put a showing card away. + let key = Event::Key { key: egui::Key::X, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; + let scroll = wheel(selection, 10.0).pop().unwrap(); + for (k, event) in [key, Event::ModifiersChanged(egui::Modifiers::SHIFT), scroll].into_iter().enumerate() { + let what = format!("{event:?}"); + let (t, _) = until_card(&mut app, &ctx, 10.0 + 10.0 * k as f64, selection, "selection"); + assert!(!has_card(&painted_texts(&mut app, &ctx, t + 0.1, vec![event]), "selection"), "gone on {what}"); + // The key or the modifier comes up again. + let up = Event::Key { key: egui::Key::X, physical_key: None, pressed: false, repeat: false, modifiers: Default::default() }; + painted_texts(&mut app, &ctx, t + 0.2, vec![up, Event::ModifiersChanged(egui::Modifiers::NONE)]); + } + // So does an arrow key that the shortcuts take before the toolbar draws (it nudges the selection). + let (t, _) = until_card(&mut app, &ctx, 45.0, selection, "selection"); + let arrow = Event::Key { key: egui::Key::ArrowLeft, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; + let shown = painted_after(&mut app, &ctx, t + 0.1, vec![arrow], WINDOW, Some(egui::Key::ArrowLeft)); + assert!(!shown.iter().any(|(s, _)| *s == described("selection")), "gone on an arrow key the shortcuts took"); + + // A long press on a group's button with its card showing still opens its flyout on time. + let (t, _) = until_card(&mut app, &ctx, 50.0, shapes, "rectangle"); + assert!(!has_card(&painted_texts(&mut app, &ctx, t + 0.1, vec![b(shapes, true)]), "rectangle"), "gone on the press"); + painted_texts(&mut app, &ctx, t + 0.1 + LONG_PRESS + 0.01, vec![]); + assert!(app.ui.flyout.is_some(), "the long press opened the flyout"); + assert_eq!(app.session.tool_id(), "directSelection"); + painted_texts(&mut app, &ctx, t + 1.0, vec![b(shapes, false)]); + assert!(app.ui.flyout.is_some()); + + // While it is open, another button shows its one-line tool tip instead of a card ... + let shown = hovered_texts(&mut app, &ctx, 60.0, selection); + assert!(!has_card(&shown, "selection") && shown.contains(&tip(tool_info("selection").unwrap())), "{shown:?}"); + // ... and its rows show theirs beside it, past its bar, when the window has room there; when + // it has none, a row shows no card rather than one pushed over the flyout. + let menu = ctx.memory(|m| m.area_rect(egui::Id::unique("tool-flyout"))).expect("the flyout is shown"); + let row = pos2(menu.left() + 60.0, menu.top() + 45.0); + let narrow = vec2(menu.right() + 100.0, WINDOW.y); + for (k, shown) in hovered_in(&mut app, &ctx, 65.0, row, narrow).into_iter().enumerate() { + assert!(!shown.iter().any(|(s, _)| *s == described("roundedRectangle")), "no room: no card (frame {k})"); + } + let (_, text) = until_card_in(&mut app, &ctx, 70.0, row, "roundedRectangle", vec2(menu.right() + 400.0, WINDOW.y)); + assert!(text.left() >= menu.right(), "{text:?} beside {menu:?}"); + let away = pos2(300.0, 1000.0); + painted_texts(&mut app, &ctx, 80.0, vec![Event::PointerMoved(away), b(away, true)]); + painted_texts(&mut app, &ctx, 80.05, vec![b(away, false)]); + assert_eq!(app.ui.flyout, None); + + // A press held from off the toolbar, moved over a tool button, shows no card. + painted_texts(&mut app, &ctx, 90.0, vec![Event::PointerMoved(away), b(away, true)]); + painted_texts(&mut app, &ctx, 90.1, vec![Event::PointerMoved(selection)]); + for i in 2..30 { + let shown = painted_texts(&mut app, &ctx, 90.0 + f64::from(i) * 0.1, vec![]); + assert!(!has_card(&shown, "selection"), "no card while a button is held"); + } + painted_texts(&mut app, &ctx, 93.0, vec![b(selection, false)]); +} + +/// A floating flyout's buttons show cards below the strip, except while a group's flyout is open: +/// then they show their one-line tool tips. +#[test] +fn a_floating_flyouts_cards_give_way_to_an_open_flyout() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let tools: Vec = ["rectangle", "roundedRectangle", "star"].map(String::from).to_vec(); + app.ui.floating_flyouts.push(crate::state::FloatingFlyout { tools, pos: [150.0, 600.0] }); + let ctx = egui::Context::default(); + shapes_button(&mut app, &ctx); + app.run("prefs.set", json!({"key": "showToolCards", "value": true})).unwrap(); + let rects = frame(&mut app, &ctx, 1.0, vec![]); + let strip = ctx.memory(|m| m.area_rect(floating_area("rectangle"))).unwrap(); + let star = pos2(strip.left() + STRIP_BUTTON.x * 2.5, strip.center().y); + let (_, text) = until_card(&mut app, &ctx, 10.0, star, "star"); + let window = egui::Rect::from_min_size(Pos2::ZERO, WINDOW); + assert!(text.top() >= strip.bottom() && window.contains_rect(text), "{text:?} below {strip:?}"); + // A right-click on the Direct Selection group's button opens its flyout. + let direct = rects[1].center(); + let r = |pressed| Event::PointerButton { pos: direct, button: PointerButton::Secondary, pressed, modifiers: Default::default() }; + frame(&mut app, &ctx, 20.0, vec![Event::PointerMoved(direct), r(true)]); + frame(&mut app, &ctx, 20.05, vec![r(false)]); + assert!(app.ui.flyout.is_some()); + let shown = hovered_texts(&mut app, &ctx, 30.0, star); + assert!(!shown.contains(&described("star")) && shown.contains(&tl!("Star Tool").to_string()), "{shown:?}"); +} + +/// A floating flyout's card goes above the strip when the window has no room below it, and when it +/// has room neither above nor below, the button keeps its one-line tool tip. +#[test] +fn a_floating_flyouts_card_goes_above_or_gives_way_in_a_short_window() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let tools: Vec = ["rectangle", "roundedRectangle", "star"].map(String::from).to_vec(); + app.ui.floating_flyouts.push(crate::state::FloatingFlyout { tools, pos: [150.0, 600.0] }); + let ctx = egui::Context::default(); + shapes_button(&mut app, &ctx); + app.run("prefs.set", json!({"key": "showToolCards", "value": true})).unwrap(); + frame(&mut app, &ctx, 1.0, vec![]); + let strip = ctx.memory(|m| m.area_rect(floating_area("rectangle"))).unwrap(); + let star = pos2(strip.left() + STRIP_BUTTON.x * 2.5, strip.center().y); + let low = vec2(WINDOW.x, strip.bottom() + 40.0); + let (_, text) = until_card_in(&mut app, &ctx, 10.0, star, "star", low); + assert!(text.bottom() <= strip.top(), "{text:?} above {strip:?}"); + + app.ui.floating_flyouts[0].pos = [150.0, 150.0]; + let short = vec2(WINDOW.x, 360.0); + painted_in(&mut app, &ctx, 20.0, vec![], short); + let strip = ctx.memory(|m| m.area_rect(floating_area("rectangle"))).unwrap(); + let star = pos2(strip.left() + STRIP_BUTTON.x * 2.5, strip.center().y); + let frames = hovered_in(&mut app, &ctx, 30.0, star, short); + let shown: Vec<&String> = frames.iter().flatten().map(|(s, _)| s).collect(); + assert!(!shown.contains(&&described("star")) && shown.contains(&&tl!("Star Tool").to_string()), "{shown:?}"); +} + +/// A flyout that opens left of its button (a toolbar docked right) shows its rows' cards on its +/// left, clear of the button. +#[test] +fn a_flyout_opened_to_the_left_shows_its_cards_on_the_left() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.run("prefs.set", json!({"key": "showToolCards", "value": true})).unwrap(); + let ctx = egui::Context::default(); + let size = vec2(800.0, 1200.0); + let anchor = egui::Rect::from_min_size(pos2(760.0, 100.0), vec2(36.0, PITCH - 1.0)); + app.ui.flyout = Some(0); + ctx.data_mut(|d| { + d.insert_temp(egui::Id::unique("flyout-anchor"), anchor); + d.insert_temp(egui::Id::unique("flyout-tools"), ["rectangle", "roundedRectangle", "ellipse"].map(String::from).to_vec()); + d.insert_temp(flyout_toolbar_id(), None::); + }); + painted_in(&mut app, &ctx, 0.0, vec![], size); + painted_in(&mut app, &ctx, 0.1, vec![], size); + let menu = ctx.memory(|m| m.area_rect(egui::Id::unique("tool-flyout"))).expect("the flyout is shown"); + assert!(menu.right() <= anchor.left(), "the flyout opened left: {menu:?}"); + let row = pos2(menu.left() + 60.0, menu.top() + 45.0); + let (_, text) = until_card_in(&mut app, &ctx, 1.0, row, "roundedRectangle", size); + assert!(text.right() <= menu.left() && !text.intersects(anchor), "{text:?} left of {menu:?}"); +} + +/// A long translated tool name wraps inside the card's width, so the card keeps to the room its +/// placement checked. +#[test] +fn a_long_translated_name_wraps_inside_the_card() { + let ru = crate::i18n::Lang::from_code("ru").unwrap(); + crate::i18n::set_current(ru); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.run("prefs.set", json!({"key": "showToolCards", "value": true})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let anchor = egui::Rect::from_min_size(pos2(760.0, 100.0), vec2(36.0, PITCH - 1.0)); + app.ui.flyout = Some(0); + ctx.data_mut(|d| { + d.insert_temp(egui::Id::unique("flyout-anchor"), anchor); + d.insert_temp(egui::Id::unique("flyout-tools"), ["rectangle", "roundedRectangle", "ellipse"].map(String::from).to_vec()); + d.insert_temp(flyout_toolbar_id(), None::); + }); + let size = vec2(800.0, 1200.0); + painted_in(&mut app, &ctx, 0.0, vec![], size); + painted_in(&mut app, &ctx, 0.1, vec![], size); + let menu = ctx.memory(|m| m.area_rect(egui::Id::unique("tool-flyout"))).expect("the flyout is shown"); + let row = pos2(menu.left() + 60.0, menu.top() + 45.0); + let name = tip(tool_info("roundedRectangle").unwrap()); + let english = described("roundedRectangle"); + let description = tl!(english.as_str()).to_string(); + assert_ne!(description, english, "the description has a Russian row"); + painted_in(&mut app, &ctx, 1.0, vec![Event::PointerGone], size); + painted_in(&mut app, &ctx, 1.1, vec![Event::PointerMoved(row)], size); + let mut card = None; + for i in 2..30 { + let shown = painted_in(&mut app, &ctx, 1.0 + f64::from(i) * 0.1, vec![], size); + if shown.iter().any(|(s, _)| *s == description) { + card = Some(shown); + break; + } + } + crate::i18n::set_current(crate::i18n::Lang::EN); + let shown = card.expect("the Russian card shows"); + let heading = shown.iter().filter(|(s, _)| *s == name).map(|(_, r)| *r).max_by(|a, b| a.left().total_cmp(&b.left()).reverse()); + let heading = heading.expect("the card shows the name"); + // The name sits right of the icon, inside the card's width. + assert!(heading.width() <= card::WIDTH - card::ICON, "{name}: {heading:?}"); + assert!(heading.right() <= menu.left(), "{heading:?} left of {menu:?}"); +} + /// Screen readers name a flyout's rows and a floating strip's buttons by their tools' tool tips, /// with the active tool's pressed, and name the strip's close box and both tear-off bars. #[test] diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index d6a0f7c50e..3ec5d25613 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -37,10 +37,10 @@ pub(crate) use buttons::{ use chips::gradient_chip_colors; pub use chips::{ProxyClicks, chip_button, chip_button_named, fill_stroke_proxy, gradient_chip, paint_chip, proxy_chip, swatch_tile}; pub use color::{ - FieldAxis, Live, RingResponse, SliderValue, WheelAxes, WheelResponse, channel_slider, channel_slider_named, channel_slider_stepped, - channel_slider_valued, color_field, color_mesh, color_slider, color_slider_named, color_slider_stepped, color_slider_valued, harmony_wheel, - hex_field, hex_field_named, hsb32, hue_ring, region_texture, ring_square, segment_color, segment_color_on, segmented_wheel, stepped_area, - wheel_of, + FieldAxis, Live, MarkerResponse, RingResponse, SliderValue, WheelAxes, WheelResponse, channel_slider, channel_slider_named, + channel_slider_stepped, channel_slider_valued, color_field, color_mesh, color_slider, color_slider_named, color_slider_stepped, + color_slider_valued, harmony_wheel, hex_field, hex_field_named, hsb32, hue_ring, region_texture, ring_markers, ring_square, segment_color, + segment_color_on, segmented_wheel, stepped_area, wheel_of, }; pub(crate) use color::{HEX_FIELD_CHARS, focus_by_pointer, hex_text, pointer_phase}; pub use drag::{ diff --git a/crates/ui-egui/src/widgets/color.rs b/crates/ui-egui/src/widgets/color.rs index 54d52a6ccf..882e236363 100644 --- a/crates/ui-egui/src/widgets/color.rs +++ b/crates/ui-egui/src/widgets/color.rs @@ -972,6 +972,68 @@ pub fn hue_ring(ui: &mut Ui, id: impl std::hash::Hash, name: &str, size: f32, hu out } +/// What [`ring_markers`] did this frame. +#[derive(Clone, Copy, Debug, Default)] +pub struct MarkerResponse { + /// The index of the marker that was picked. + pub picked: Option, + /// A press on a marker is held with the pointer still on the marker. The caller then ignores + /// the drag that the ring under it reports. + pub held: bool, +} + +/// Markers on a [`hue_ring`] drawn in `rect`, one for each HSB of `colors` at its hue, filled with +/// its color and smaller than the ring's own marker. Each marker is a button that screen readers +/// read as `name` with the color's hex value. A click gives it the keyboard focus. A click, a +/// press released on the marker however long it was held, Enter or Space on the focused marker, +/// or a screen reader's click picks it. A drag that leaves the marker moves the ring's hue as a +/// drag on the band does. +pub fn ring_markers(ui: &mut Ui, id: &str, rect: Rect, colors: &[[f32; 3]], name: &str) -> MarkerResponse { + let t = Tokens::get(ui.ctx()); + let c = rect.center(); + let mid = rect.width().min(rect.height()) / 2.0 - RING_MARGIN - RING_WIDTH / 2.0; + let radius = RING_WIDTH / 2.0 - 2.0; + let painter = ui.painter_at(rect); + let press_id = id_with(ui.scope_id(), (id, "press")); + let (pos, down, pressed, released) = + ui.input(|i| (i.pointer.latest_pos(), i.pointer.primary_down(), i.pointer.primary_pressed(), i.pointer.primary_released())); + let mut held_on: Option = ui.data(|d| d.get_temp(press_id)).flatten(); + let mut picked = None; + for (i, hsb) in colors.iter().enumerate() { + let p = wheel_pos(c, mid, hsb[0], 1.0); + let area = Rect::from_center_size(p, Vec2::splat(RING_WIDTH)); + let resp = ui.interact(area, id_with(ui.scope_id(), (id, i)), Sense::click()); + focus_on_press(&resp); + if pressed && resp.is_pointer_button_down_on() { + held_on = Some(i); + } + let on = pos.is_some_and(|p| area.contains(p)); + if held_on == Some(i) && !on { + held_on = None; + } + let fill = hsb32(*hsb); + painter.circle(p, radius, fill, Stroke::new(1.0, Color32::WHITE)); + painter.circle_stroke(p, radius + 1.0, Stroke::new(1.0, Color32::BLACK)); + if ui.memory(|m| m.has_focus(resp.id)) { + painter.circle_stroke(p, radius + 3.0, Stroke::new(1.0, t.accent)); + } + let hex = format!("#{:02x}{:02x}{:02x}", fill.r(), fill.g(), fill.b()); + resp.widget_info(|| egui::WidgetInfo { + current_text_value: Some(hex.clone()), + ..egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), name) + }); + if resp.clicked() || (held_on == Some(i) && released && on) { + picked = Some(i); + } + } + if held_on.is_some_and(|i| i >= colors.len()) { + held_on = None; + } + let held = down && held_on.is_some(); + ui.data_mut(|d| d.insert_temp(press_id, if down { held_on } else { None })); + MarkerResponse { picked, held } +} + /// Hue sectors and rings of the [`segmented_wheel`]: patches 15° of hue by 20% saturation (or /// brightness) wide, the sectors centered on red at 0°. const WHEEL_SECTORS: u32 = 24; diff --git a/docs/control-protocol.md b/docs/control-protocol.md index a6e64b1be5..2872068930 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -1,6 +1,6 @@ # Control protocol -> **Last updated:** 2026-11-15 · **Change:** completed the `ui.resize` and `ui.focus` entries and removed a duplicate `ui.render` row; previously: text style commands take a feature with a value (`"features": ["salt=2"]`), the font's alternate number, and shape runs that differ only in features as one piece of text; previously: Confining file access refuses a `:` in a name after the drive on Windows, an NTFS alternate data stream such as `x.svg:evil` (#3604); previously: Object → Expand… dimmed while the selection has an appearance Expand Appearance expands (`object.expand.info`'s `appearance`, #3089); previously: brush library panels (`window.brushLibrary`, `window.brushLibrary.other`, `ui.saveBrushLibrary`); previously: Transform Each opens on the values it was last confirmed with; its Copy button confirms with `copy: true` (#1732); previously: panel docking on craft-ui's layout: `ui.docking`, the parameters of `window.panel.float` and `window.panel.dock`; previously: `ui.screenshot`'s 64 MiB inline-PNG cap and its path-plus-data downgrade; symbol library panels (`window.symbolLibrary`, `window.symbolLibrary.other`, `ui.saveSymbolLibrary`); synthetic input budgets (#1709); bounded transport waits (#1726). +> **Last updated:** 2026-11-19 · **Change:** #5804 native-picked raster editor merged with main; scores and estimates unchanged; previously: completed the `ui.resize` and `ui.focus` entries and removed a duplicate `ui.render` row; previously: text style commands take a feature with a value (`"features": ["salt=2"]`), the font's alternate number, and shape runs that differ only in features as one piece of text; previously: Confining file access refuses a `:` in a name after the drive on Windows, an NTFS alternate data stream such as `x.svg:evil` (#3604); previously: Object → Expand… dimmed while the selection has an appearance Expand Appearance expands (`object.expand.info`'s `appearance`, #3089); previously: brush library panels (`window.brushLibrary`, `window.brushLibrary.other`, `ui.saveBrushLibrary`); previously: Transform Each opens on the values it was last confirmed with; its Copy button confirms with `copy: true` (#1732); previously: panel docking on craft-ui's layout: `ui.docking`, the parameters of `window.panel.float` and `window.panel.dock`; previously: `ui.screenshot`'s 64 MiB inline-PNG cap and its path-plus-data downgrade; symbol library panels (`window.symbolLibrary`, `window.symbolLibrary.other`, `ui.saveSymbolLibrary`); synthetic input budgets (#1709); bounded transport waits (#1726). `vectorcraft --control ` listens on `127.0.0.1:` (loopback only). The port must be a number from 1 to 65535 (`--control=` works too), given once; otherwise the app prints an error and exits @@ -110,7 +110,7 @@ the two can still win that race. | `app.open` / `app.save` / `app.export` / `app.quit` | `{path, importer?, params?}` / `{path?}` / `{path?, format?, artboard?, range?, scale?, …}` | `app.open` reads every format `document.open` reads (see `document.formats`) and returns its result (`{index, title, format, warnings, …}`; `warnings` say what didn't come in as it was, such as an EPS shown as its preview image and why its PostScript couldn't be read), or null when a dialog asks first or a library loads. The status bar (`ui.inspect` → `ui.status`), after a line about the document's linked files when there is one (Missing linked files below), counts the `warnings` and names the first that says reading the file left something out (the notes that make Save ask before writing over it), else the first; with several, hovering it lists them in that order, as many as fit in the window (at most 30), then how many more. After `app.save`, and `app.export` with a `path`, the status bar counts the reply's `warnings` and names the first, and with several, hovering it lists them in the reply's order (a save's notes start with what the format loses). With `importer` (an importer plug-in's format id, `plugin.`) it runs `file.openWith`: the file opens with that importer, also when a built-in format reads its extension, with the importer's parameters `params` (their defaults when omitted; no dialog asks for them). Without `importer`, `params` go to the importer that opens the file, and a built-in format does not read them. `app.export` encodes through the engine's `document.export` (same options; the document keeps its path) and writes `path` through the host; without `path` it returns `{dataBase64, format, bytes}`, as headless mode does. It refuses a key that no format takes, and an unknown key inside a PDF or EPS option object, before it writes anything (`docs/mcp.md`, Parameter keys). It accepts a key that only another format takes and does not use it: the reply's `warnings` and the status bar name the key ("`quality` was not used: PDF files don't read it"). `app.save` refuses a key that no save format takes, beside the path or in `options`, the same way. `app.quit`, `file.close` and `file.closeAll` first open a `saveChanges` dialog for each modified document (they return `{"pending": "saveChanges"}`): `ui.dialog.confirm` saves, `ui.dialog.set {field: "discard", value: true}` then confirm discards, `ui.dialog.cancel` cancels the whole close or quit | | `app.export` with `useArtboards` | `{path, useArtboards: true, range? \| artboards?, …}` | Export As: PNG, JPEG and WebP write one file per chosen artboard (default all; SVG does so for a `range`), `-.`, and return `{path, files: [path…]}`; a PDF keeps them as pages of `path`. `useArtboards: false` covers the bounds of the visible art. The menu's Export As… is `file.exportAs`: the `exportAs` dialog (`format`, `useArtboards`, `all`, `range`), then a save dialog and the format's options: `pngOptions` / `jpgOptions` / `webpOptions`, `svgOptions`, or `savePdf` for a PDF | | `ui.dialog.*` on `gradientStop` | `{field: "color" \| "opacity" \| "location", value}` | double-clicking a stop on the Gradient tool's annotator opens its popover (fields `index`, `x`, `y`, `tab`); set `color` (hex), `opacity` or `location` (percentages) and `ui.dialog.confirm` to apply them to the selected stop. `gradient.selectStop {index}` picks the stop the annotator, the panels and Delete/←/→ (`ui.key`) act on | -| `engine.execute` `ui.savePdfDialog` | `{path?, preset?, range?, …document.exportPdf options}` | opens the Save PDF dialog (`file.export.pdf` with no params opens it too). Its fields are the `document.exportPdf` options: set `compatibility` with `ui.dialog.set {field: "compatibility", value: "1.5"}`, a whole section with `{field: "compression", value: {…}}`, the artboards with `__allArtboards: false` and `range`, the visible section with `__section` (General, Compression, Marks and Bleeds, Output, Advanced, Security, Summary), and the bleed link with `__bleedLinked` (true gives every side the top value; any value other than true or false is an error; setting `bleed` turns the link on when its four sides are equal and off when they differ). `useArtboards: false` opens it for one page of the visible art's bounds, as Export As with Use Artboards off does: the dialog has no Artboards section and its `__artBounds` field is true. `ui.dialog.confirm` writes `path` (else asks for one), returns `{path, bytes, warnings}` and opens the file when `viewAfterSaving` is set. With `useArtboards: false` it writes the page as `app.export` does and returns `{path, warnings}`, or `{background: true, status}` while Background Export writes it | +| `engine.execute` `ui.savePdfDialog` | `{path?, preset?, range?, …document.exportPdf options}` | opens the Save PDF dialog (`file.export.pdf` with no params opens it too). Its fields are the `document.exportPdf` options: set `compatibility` with `ui.dialog.set {field: "compatibility", value: "1.5"}`, a whole section with `{field: "compression", value: {…}}`, the artboards with `__allArtboards: false` and `range`, the visible section with `__section` (General, Compression, Marks and Bleeds, Output, Advanced, Security, Summary), and the bleed link with `__bleedLinked` (true gives every side the top value; any value other than true or false is an error; setting `bleed` turns the link on when its four sides are equal and off when they differ). In Advanced, Custom… beside Flattener preset (enabled when the file is flattened: PDF 1.3, PDF/X-1a, PDF/X-3) opens the `pdfFlattenerOptions` dialog over Save PDF on the flattener options the save would use; its fields are those options, with `clipComplexRegions`, `preserveAlpha` and `preserveOverprints` set by the writer and Overprint. Its `ui.dialog.confirm` sets `flattener` (the preset then shows [Custom]; options equal to the preset's leave it unset) and goes back to Save PDF, and `ui.dialog.cancel` goes back unchanged. Setting `flattenerPreset` drops `flattener`. `useArtboards: false` opens it for one page of the visible art's bounds, as Export As with Use Artboards off does: the dialog has no Artboards section and its `__artBounds` field is true. `ui.dialog.confirm` writes `path` (else asks for one), returns `{path, bytes, warnings}` and opens the file when `viewAfterSaving` is set. With `useArtboards: false` it writes the page as `app.export` does and returns `{path, warnings}`, or `{background: true, status}` while Background Export writes it | | `file.save` / `file.saveAs` / `file.saveCopy` / `file.saveAsTemplate` (via `engine.execute`) | `{path?, format?, options?, svg?}` | Save writes the document's own file in its own format (a document opened from or saved as SVG/PDF saves as that again; the result's `warnings` say what the format loses). With `path` the file is written at once (Save As or a Copy to an SVG path without SVG options first opens SVG Options, below). Without one (never saved, a converted older file, Save As, a Copy, a Template) the app shows a save panel with one file type per save format (`vectorcraft`, `template`, `pdf`, `svg`, `svgz`, `ai`; for a Template, `template` and `ait`), then the format's options: SVG opens the `svgOptions` dialog (below; returns `{"pending": "svgOptions", "path"}`), PDF the `savePdf` dialog (its `__save` field names the save command); `ui.dialog.confirm` finishes the save. A name typed in the panel without the file type's extension gets it, and a name the panel returns with the extension of a format the panel does not list has it replaced (in a native save, `card.png` and `card.ait` are saved as `card.vectorcraft`, and `notes.v2`, whose extension names no format, is saved as `notes.v2.vectorcraft`); when a file of that name exists, which the panel did not ask about, the save (and every export or other write through a save panel) answers `cancelled` and opens a `replaceFile` dialog (fields `message`, `detail`, `path`): `ui.dialog.confirm` writes that file, `ui.dialog.cancel` writes nothing. A save or export that writes other files beside that path (a file per artboard, linked images, image maps) checks them before it writes anything: when any of them exists, it writes nothing and opens a `replaceFiles` dialog (fields `message`, `detail` (each file's name when there are several), `files`, `__command`, `__params`; the reply is `{"pending": "replaceFiles"}`, or comes once a Background Save or Export ends): `ui.dialog.confirm` runs the save or export again and replaces them, `ui.dialog.cancel` writes nothing; a dialog open when a background job asks stays open, and the question follows it. A save does not ask about the files the document's last Save or Save As in this session wrote. On the web a `saveOptions` dialog (fields `path`, `format`) first names the file and picks the format. `file.formatOptions {format?}` reads the options a save would use. `file.revert` opens a `confirm` dialog (`{"pending": "confirm"}`); `ui.dialog.confirm` reloads the saved file in the same tab. Location refusals return `READ_ONLY_LOCATION: ` without a fallback panel for automation; see [Save location errors](#save-location-errors). | | SVG Options (`engine.execute` of `file.export.svg`, `file.saveAs`, `file.saveCopy`) | `{}` / `{path?, svg?: {…}}` | `file.export.svg` without params, and Save As or Save a Copy to an `.svg`/`.svgz` path without SVG options, open the `svgOptions` dialog (`ui.dialog.set` its fields: `styling`, `outlineText`, `images`, `objectIds`, `decimals`, `minify`, `responsive`, `fewerTspans`, `metadata`, `preserveEditing`, `useArtboards`, `allArtboards`, `range`, `showCode`, `profile` (`svg11`/`tiny12`), `encoding` (`utf8`/`utf16`/`latin1`), `embedFonts`; `ui.dialog.confirm` exports or saves and remembers the choices). The dialog's Show in Browser button (`file.export.svg.browser`) writes the SVG of the current choices for one page to a temporary folder and opens it in the default browser, leaving the dialog open; a request through `engine.execute` is refused because it opens another app. With `svg: {…}` (the `document.formats` SVG options) they run directly. `app.save {path?, svg?}` takes the same options; a document saved as SVG saves as SVG again with the same options | | `engine.execute` `file.place` | `{paths?}` / `{path \| name+dataBase64, …file.place params}` | with no file, picks files and opens the `place` dialog; with `paths`, opens it for them (fields `files`, `link`, `template`, `replace`; `__replace` says whether Replace applies, `__info` describes each file). `ui.dialog.confirm` places one file centered in the view (or in place of the selected object) and loads the place cursor with several (`file.place.queue`). In the desktop app the dialog reads its files off the UI thread: `__info` is empty until they are read, `ui.dialog.confirm` returns `{background: true, status}`, `ui.inspect` lists the files still being read in `placing`, and the file is placed (or the cursor loaded) once it is read. With a file, it runs `file.place` centered in the view, at once. Files dropped on the window with no document open open. On the web, files dropped on the canvas are placed at the drop point (linked; Shift embeds) and files dropped off it (the tab bar) open, as in Illustrator; desktop drops carry no pointer position, so documents (native, SVG, PDF, `.ai`, EPS, DXF, EMF/WMF) open as tabs of their own and pictures and text are placed in the middle of the view. Swatch libraries and color books (`.vcswatches`, `.gpl`, `.ase`, `.acb`), graphic style libraries (`.vcstyles`), Libraries panel files (`.vclibrary`), presets (`.vcflattener`, `.vcpdfpresets`, `.vcprintpresets`, `.vcperspective`, `.vcexportpresets`), plug-ins (`.wasm`) and shortcut sets (`.kys`, in Import Shortcut Set) open wherever they are dropped, as File › Open opens them. With the cursor loaded (`ui.inspect` → `tool: "place"`, `toolOptions: {count, current, name, names}`), `ui.pointer` clicks and drags place files (in the desktop app each file is read off the UI thread and placed once it is read, and `ui.inspect` lists it in `placing` until then) and `ui.key` ←/→/↑/↓ and Escape cycle and discard them | @@ -150,7 +150,11 @@ those rows with `layer.delete` in the document the question was asked in. `layer New swatches and colour groups: `ui.newSwatch {spot?, global?, group?}` opens the `newSwatch` dialog prefilled from the active fill or stroke (fields as in `swatchOptions` plus `group`; a gradient or pattern only takes `name`) and `ui.newColorGroup {swatches?}` opens `newColorGroup` (fields `name`, `fromArtwork`, `toGlobal`, `includeTints`, -`swatches`); `ui.dialog.confirm` runs `swatch.new` / `swatch.newGroup`. +`swatches`); `ui.dialog.confirm` runs `swatch.new` / `swatch.newGroup`. `ui.colorGroupOptions {group?}` opens +`colorGroupOptions` (fields `name`, `__group`, `__swatches`, `__index` and `__doc`) for `group`, or without it for the +color group selected alone in the Swatches panel; its `ui.dialog.confirm` runs `swatch.renameGroup`. A refused name keeps +the dialog open; when another document is active, or the color group at the group's place in the list no longer has the +name and swatches it opened with, the confirm closes the dialog and renames nothing. The Color Picker is a dialog too: `engine.execute {command: "ui.colorPicker", params: {stroke?, color?}}` opens it for the fill (or stroke) proxy; `ui.dialog.set {field: "hex", value: "00FF00"}` (or `color`, `channel`, `webOnly`, `swatches`) then `ui.dialog.confirm` applies the colour through `paint.setFill` / `paint.setStroke`. @@ -268,9 +272,10 @@ My Themes tab lists the saved themes; every action runs a command (`colorTheme.s Color Wheel panel (`window.panel {panel: "colorWheel"}`): a hue ring around a saturation and brightness square. A pick runs the commands the Color panel's sliders run: `paint.setFill` or `paint.setStroke` with `keepModel`, `paint.editGradient` for a gradient's selected stop, and `paint.freeform.setPoint` for a freeform gradient's selected -point (the first stop or point when none is selected). `ui.colorWheel {view?, channel?, vision?}` shows the wheel or -the box (a color field with a channel strip at its right), picks the box's channel and shows or hides the color vision -row; it returns the settings, and `ui.inspect` reports them as `ui.color_wheel`. +point (the first stop or point when none is selected). `ui.colorWheel {view?, channel?, harmony?, harmonyRule?, vision?}` +shows the wheel or the box (a color field with a channel strip at its right), picks the box's channel, shows the +other colors of a harmony rule as markers on the wheel's ring, and shows or hides the color vision row; it returns +the settings, and `ui.inspect` reports them as `ui.color_wheel`. Edit Colors dialogs: `ui.colorBalanceDialog` opens Adjust Colors (`colorBalance`: fields `mode` `gray`/`rgb`/`cmyk`/ `global`, the channels `r` `g` `b` / `c` `m` `y` `k` / `gray` / `tint` (global mode) from −100 to 100, `convert`, `fill`, `stroke`, @@ -607,6 +612,20 @@ value: true}` then confirm (the Delete button) removes the point with `stroke.wi 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. +`ui.widthPointEdit {id, indices: [i…]}` opens it on several existing width points, as double-clicking one of several +Shift-selected width points does. `indices` must be a nonempty array of profile indices; repeated indices count once, +either half of a discontinuous point brings the other, and an index that is not a nonnegative whole number or not a +width point of the stroke is an error, as is giving more than one of `index`, `indices` and `t`. When the indices name one width point +(both halves of a discontinuous point count as one) it opens as `index` would. The fields are `indices` (every profile entry edited, in order), `side1`, `side2` and +`totalWidth` (null where the points differ), `linked` and `adjustAdjoining`, and with a discontinuous point among them +`outSide1`, `outSide2`, `outTotalWidth` and `outLinked` for the outgoing halves; the continuous points take both sets. +A side width set there replaces that side of every point (both sides with `linked`), and leaves each point's other side +as it was; `totalWidth` scales each point's own two sides to that total; a null field changes nothing. Confirm runs one +`stroke.widthProfile.set` (one undo step), or nothing when no width changed, and Delete removes every point with +`stroke.widthPoint.remove {id, indices}`. With `adjustAdjoining`, each changed point changes the nearest unselected +point at another place before and after it in proportion to its change since the dialog opened; a point next to two +changed points takes both changes. These rules for several points are VectorCraft's own. Confirm and Delete on existing +points, one or several, are refused when those points changed since the dialog opened or another document is active. 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`, @@ -812,6 +831,8 @@ PhotoCraft, looked for only where it installs (the Applications folders on macOS registers under App Paths, then `ArtCraft\PhotoCraft` in the per-user and per-machine program folders, then the `PATH`; the `PATH` elsewhere), and any other file, or a raster image without PhotoCraft installed, in the system's default app. +Draft #5804 adds a local, native-picker-only raster editor override when Use System Defaults is off. Its saved choice and Preferences draft are outside engine preferences and `Dialog::fields`: `prefs.set` (including bulk values), `ui.dialog.set` and `ui.set` cannot assign it. The chooser refuses control requests and synthetic input. If the chosen application is missing, Edit Original tries PhotoCraft and then the system default; validation or launch errors are reported. The existing refusal of automated external Edit Original remains. No executable arguments or shell command are accepted. + Package: File → Package… (`ui.packageDialog`) opens the `package` dialog for a saved document (a document never saved gets a `confirm` dialog whose OK runs `file.saveAs`). Fields: `folder` (the location), `name` (the package folder), `copyLinks`, `linksFolder`, `relink`, `copyFonts`, `report`. `ui.dialog.confirm` saves unsaved changes (when that save @@ -879,8 +900,20 @@ EMF and WMF: Export As… lists both formats (`file.exportAs {format: "emf"}` or dialog, so `ui.dialog.confirm` asks for the path and writes the file (one per artboard with Use Artboards). Open and Place read `.emf` and `.wmf`; a paste of `image/emf` from a system clipboard service runs `clipboard.importEmf`. -HP-GL: Export As… lists it (`file.exportAs {format: "hpgl"}`); it has no options dialog, so `ui.dialog.confirm` asks -for the path and writes the `.plt` file with the default options (one per artboard with Use Artboards). +HP-GL Options: Export As… with the HP-GL format (`file.exportAs {format: "hpgl"}`, then the save dialog), or +`ui.hpglOptionsDialog {path?, …HP-GL options}` for agents, opens the `hpglOptions` dialog. Its fields are +`document.export` params: `hpglVersion` (`hpgl`, `hpgl2`), `curveTolerance` (points, 0.01 to 10), `origin` +(`bottomLeft`, `center`), `pens` (null for One Pen per Color, or the pen table's `"#rrggbb"` colors, pen 1's first), +`sortPaths` and `insideFirst`, plus `path` and the artboard choice (`useArtboards`, `range`). A typed Curve +Tolerance is kept within 0.01 to 10. Choosing Pen Table fills the table with the table set aside when One Pen per +Color was chosen, else with the pens One Pen per Color gives the art this export plots (its artboards, the art's +bounds, or the selection from Export Selection or with `selectedOnly`), or one black pen when that art draws nothing; +when the export refuses the options or the artboard choice, `pens` stays null and the dialog shows the error. +`ui.dialog.confirm` checks the options and the artboard choice (one the export refuses keeps the dialog open), +remembers the options for the next HP-GL Options (not `exportSelection`) and writes the `.plt` file(s), asking for a +path when there is none (one per artboard with Use Artboards). A canceled save dialog writes nothing and keeps the +options remembered before; a save dialog shown in line (not as a sheet or off the UI thread) also keeps HP-GL +Options open. TIFF, BMP and Targa Options: Export As… with the TIFF, BMP or Targa format (`file.exportAs {format: "tiff"}`, then the save dialog) opens `tiffOptions`, `bmpOptions` or `tgaOptions`: the raster rows of PNG Options (`ppi`, diff --git a/docs/development.md b/docs/development.md index 50e5cbb972..5a4d90966e 100644 --- a/docs/development.md +++ b/docs/development.md @@ -308,7 +308,7 @@ other `sv-*` locale resolve to it), Georgian (`ka`, complete; `ka-GE` and `ka_GE ``[{j}] `{_1}`: {why}``, so its reason is translated while a JSON array stays as it is. A literal brace in a row is written `{{` or `}}`, in the English and in the translation: a message made with `format!` keeps the doubled braces of its format string, and a plain string literal has each of its braces doubled, so the row for - `"expected {\"objects\": [...]}"` is `expected {{"objects": [...]}}`. Czech, German, Greek, Spanish, French, Georgian, Hindi, Hungarian, Italian, Japanese, Korean, Polish, Brazilian Portuguese, Russian, Simplified Chinese, Traditional Chinese, Swedish, Ukrainian, Vietnamese, Finnish, Turkish, Catalan, Dutch and Danish + `"expected {\"objects\": [...]}"` is `expected {{"objects": [...]}}`. Czech, German, Greek, Spanish, French, Georgian, Hindi, Hungarian, Italian, Japanese, Korean, Polish, Brazilian Portuguese, Russian, Simplified Chinese, Traditional Chinese, Swedish, Ukrainian, Vietnamese, Finnish, Turkish, Catalan, Dutch, Danish and Indonesian translate status and error messages (`COMPLETE_MESSAGES` in `i18n::tests`); the untranslated report lists the message literals the scan finds, and the phrases a parameter schema's error builds at run time (`SCHEMA_PHRASES`), that one of them has no row for. The scan covers the crates in `MESSAGE_CRATES`, the diff --git a/docs/dimensions.md b/docs/dimensions.md index b5a15d1f11..e90e4ecf20 100644 --- a/docs/dimensions.md +++ b/docs/dimensions.md @@ -71,8 +71,11 @@ The **Dimension Tool** is in the Modify section of the toolbar. Its strip offers turns has its line where the turn puts it, or, when that would put it between the points, as far past the outermost point as before. With Smart Guides on, a linear dimension placed with its line within the Smart Guides snapping - tolerance of the level of a parallel line of a visible, unlocked linear dimension already drawn - anywhere in the document has its line on that level. This is VectorCraft's own rule. With + tolerance of the level of a parallel line of a linear dimension already drawn has its line on + that level. The other dimension, and every layer and group it is in, must be visible and + unlocked. The tool reads at most 20,000 visible, unlocked layers, groups and objects, from the + frontmost back, so in a larger document a dimension past them is not a level. This is + VectorCraft's own rule. With Alignment Guides on, a guide runs along the level across both lines while the dimension is placed. - **Angular:** hover a corner where two straight segments meet and drag outwards. Or click two diff --git a/docs/effects-parity.md b/docs/effects-parity.md index d92dc159f7..1b0d755ff8 100644 --- a/docs/effects-parity.md +++ b/docs/effects-parity.md @@ -181,13 +181,13 @@ 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 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 | +| 3D (Classic): Extrude & Bevel, Revolve, Rotate | Extrude & Bevel (Classic) initial: live, round seam joins, Extrude Depth, Cap, five original bevel shapes with Height and Bevel Extent In or Out, Position presets and rotation gizmo, Perspective, Wireframe, No Shading, Diffuse and Plastic surfaces with one to ten lights, Light Intensity, Ambient Light, Highlight Intensity and Size, Blend Steps, Black, Custom, Black Overprint or no Shading Color ([Black Overprint](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=188)), Draw Hidden Faces ([create 3D objects](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/create-3d-objects.html)); Revolve (Classic) initial: live, round seam joins, Angle, Cap, Offset from the left or right edge, Position presets and rotation gizmo, Perspective, the same four surfaces, lights, highlight, Blend Steps and Shading Color, groups and layers revolved about one shared axis (same page); Rotate (Classic) initial: live, round seam joins, every fill and stroke turned as one plane, Position presets and rotation gizmo, Perspective, No Shading and Diffuse surfaces with lights, Ambient Light, Blend Steps and Shading Color ([rotate objects in 3D](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/rotate-objects-in-3d.html)); Preserve Spot Colors in all three, unavailable with a Custom Shading Color ([Preserve Spot Color](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=260)); all three: a lighting sphere on the Lighting tab whose lights drag, move to the back or front, and are added at the front center or deleted down to one ([lighting options](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=272)); all three: the track cube (face, edge, Shift and ring drags, keyboard steps; [three-d.md](three-d.md#track-cube)); Map Art for Extrude & Bevel (Classic) and Revolve (Classic): one document symbol on each numbered surface, surface navigation with visible and hidden marks and a red outline on the artboard, move, scale and rotate on the surface laid out flat, Scale to Fit, Clear, Clear All, Shade Artwork, Invisible Geometry, kept by Expand Appearance and exports, `threeD.mapArt` ([map artwork to a 3D object](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=189)) | | 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)) | The `three-d` crate (depends on `geom` and `pathops`, with no UI or GPU dependencies) builds, rotates, projects, shades and depth-sorts the surfaces; the effects crate turns them into art. What's left (materials and shadows, ray-traced rendering, -angular cut caps, exact visibility, the rest of 3D Classic (Map Art), Turntable) is 25–45 h. +angular cut caps, exact visibility, Turntable) is 25–45 h. ## Revision history diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index dc3a776cf1..f98784085f 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -297,7 +297,7 @@ private editing data. VectorCraft: ### Illustrator's private editing data -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, its clipping paths grouped in it, at any depth, included; 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. +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, its clipping paths grouped in it, at any depth, included; 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, Stylus Wheel, 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). 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. 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. @@ -321,7 +321,7 @@ Gradient meshes in the editing data keep each point's own color where a patch's | 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` | | SVG / SVGZ | open, place, save | yes | yes (SVG Options, Preserve Editing, symbols, filters, rich text) | strongest format; tests in `crates/svg/tests`; text on a path follows basic shapes as their SVG 2 equivalent paths (#1527); CSS transforms and the `font` shorthand (#1565), percentage lengths in symbols (#1596), Inkscape flowed text as area type (#1568) and Inkscape pages as artboards (#1601) import; an unsupported filter is named in its warning (#1598); an artboard exported on its own (Export As with Use Artboards, Export for Screens, Asset Export) has the artboard's name as ``, Save the document's (#3544); attributes in other applications' XML namespaces (`plotter:pen="2"`) kept on their objects from import to export, as `data-*` attributes are (`crates/svg/tests/it/foreign_attributes.rs`); simple shapes export as `<rect>`, `<circle>`, `<ellipse>`, `<line>`, `<polygon>` and `<polyline>` where they draw the same as the path (#4652, `crates/svg/tests/it/basic_shapes.rs`); the regions of exported masks and filters (opacity masks, inverted masks, knockout groups) cover the art they apply to, and over type keep a region that covers any artwork (#6401, `crates/svg/tests/it/blend_export.rs`); a masked group, or a knockout group's masked group, whose content has a shadow, glow, blur or feather starts with a hidden, unpainted rectangle over the mask's region, so readers that draw a masked group only inside the box of its shapes draw those effects too (`crates/svg/tests/it/blend_export.rs`); SVG Options › Include Variable Data writes the text variables, data sets and bound type objects, and opening the SVG reads them back (`tests::variables::an_svg_with_variable_data_opens_with_its_variables_data_sets_and_bindings`) | | DXF | open, export | yes | yes (R12–2018) | R13–2018 closed SPLINE flags and control-point closure on import verified (#1299); circular cubic paths export as native CIRCLE/ARC where stroke semantics permit; R12 weighted strokes remain POLYLINE while non-circular curves keep the existing fallback (`crates/cad/src/tests.rs`); [Autodesk group 70](https://help.autodesk.com/cloudhelp/2024/ENU/AutoCAD-DXF/files/GUID-E1F884F8-AA90-4864-A215-3182D47A9C74.htm). DXF 2000–2018 LAYOUT objects write the paper image origin as 148/149 (was a stray 158), the shade plot codes (2004+) and the model type flag, and the plot style placeholder carries no subclass marker (#3085; structure test `r2000_and_later_files_have_the_structure_cad_apps_require`, checked with ezdxf's audit; not yet confirmed in Autodesk Fusion). DXF Options' Preset menu and `document.exportDxf`'s `dxfPreset: "cnc"` set the CNC / CAM options (#5500); VCarve QA remains open | -| HP-GL/2 `.plt`, `.hpgl`, `.hgl`, `.hpg` | — | yes (pen moves, pens and widths, line types and attributes, circles, arcs, wedges and Bézier curves, filled and edged rectangles, wedges and polygons, encoded polylines, scaling and rotation; labels, symbol mode, raster images and hatching aren't drawn) | yes (`.plt`: each visible path once along its line, a pen per color or a pen table, type as outlines, clipping applied, HP-GL or HP-GL/2 with pen colors and encoded polylines) | recognized by its first instructions after any printer escapes, under its own extensions or one no other format reads; `crates/cad/src/hpgl/tests.rs`, `crates/cad/src/hpgl/write/tests.rs` (plots read back by the reader), `tests_hpgl.rs`, `import_fuzz.rs` | +| HP-GL/2 `.plt`, `.hpgl`, `.hgl`, `.hpg` | — | yes (pen moves, pens and widths, line types and attributes, circles, arcs, wedges and Bézier curves, filled and edged rectangles, wedges and polygons, encoded polylines, scaling and rotation; labels, symbol mode, raster images and hatching aren't drawn) | yes (`.plt`: each visible path once along its line, a pen per color or a pen table, type as outlines, clipping applied, HP-GL or HP-GL/2 with pen colors and encoded polylines; Export As opens HP-GL Options) | recognized by its first instructions after any printer escapes, under its own extensions or one no other format reads; `crates/cad/src/hpgl/tests.rs`, `crates/cad/src/hpgl/write/tests.rs` (plots read back by the reader), `tests_hpgl.rs`, `import_fuzz.rs` | | DWG | open, export | no | no | no open spec; DXF instead | | EMF / WMF | open, export | yes | yes | an oversized embedded PNG or JPEG is refused from its header, before any pixels are decoded (#1776); a picture cut short by a reader limit, images and pattern brushes that are not read, clips that are not applied and raster operations other than a plain copy come back as warnings; tests in `crates/metafile/src/tests/import.rs` | | PSD | open, place, export | yes (open: layers as layers, or the merged image with `layers: false`; place: merged image, or the layers embedded as a group of objects with `layers: true`; the merged image comes in clipped by the file's clipping path; every mode and depth; `.psd` and `.pdd`) | yes (layered, max editability, point type as editable type layers with `preserveText`; `tests_psd.rs`) | PSD Import Options on File › Open and on File › Place without Link (Convert Layers to Objects, Flatten Layers to a Single Image, Import Hidden Layers, Import Slices; `tests_psdlayers.rs`, `dialogs/psd_import.rs`); slices (image resource 1050, version 6 and the version 7 and 8 descriptor) open and embed as user slices with `importSlices` (`tests_psdslices.rs`); layer comps aren't read; the embedded ICC profile's tags are 4-byte aligned (#1584) | diff --git a/docs/gaps.md b/docs/gaps.md index a8ba004253..f2f836514f 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,8 @@ # Gaps -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (G4 and G13 Missing lists drop the shipped Touch Type, Snap to Glyph and Dimension tool, and G13's snapping entry keeps only what is still missing, the partial Snapping panel and the items not yet checked (#8387); G13 keeps one estimate (13–23 h); estimates unchanged; previously: Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: G4 type: modal Check Spelling dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: Type: the Middle Eastern & South Asian composers are done as a per-paragraph choice with the Standard composers (#4935); G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: G5: built-in Weather Icons symbol library (Sun, Moon, Cloud, Rain, Thunder, Snow); estimate 5–15 → 4–14 h; previously: 3D: the seams of white-light Extrude & Bevel, Inflate and Rotate, and the face seams of the 3D (Classic) effects, have round joins instead of miters; previously: PDF import: preserve Type 3 font text runs as named groups <g>, 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 (SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; G4 and G13 Missing lists drop the shipped Touch Type, Snap to Glyph and Dimension tool, and G13's snapping entry keeps only what is still missing, the partial Snapping panel and the items not yet checked (#8387); G13 keeps one estimate (13–23 h); estimates unchanged; previously: Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: G4 type: modal Check Spelling dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: Type: the Middle Eastern & South Asian composers are done as a per-paragraph choice with the Standard composers (#4935); G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: G5: built-in Weather Icons symbol library (Sun, Moon, Cloud, Rain, Thunder, Snow); estimate 5–15 → 4–14 h; previously: 3D: the seams of white-light Extrude & Bevel, Inflate and Rotate, and the face seams of the 3D (Classic) effects, have round joins instead of miters; previously: PDF import: preserve Type 3 font text runs as named groups <g>, or as live text in TextAs::Text mode if ToUnicode exists on non-colour fonts (TextAs::Outlines produces grouped outlines), #6740; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: oversized editing artboard import; Glyphs panel: Alternates for Current Selection applies an OpenType feature value (`salt=2`) to the selected letter alone, so an Arabic word stays joined, and Entire Font lists the unencoded glyphs, #5514; #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: G5: built-in Energy Beams brush library; estimate 5–15 → 4–14 h; previously minor: G5: built-in Skill Icons symbol library; estimate 6–16 → 5–15 h; previously minor: ruler double-click adds a guide at the pointer, #5239; G5: built-in Status Effects graphic style library; estimate 7–17 → 6–16 h; MCP docs catch-up for UI Frames and Map Markers; previously minor: G5: built-in Inventory Icons symbol library; estimate 8–18 → 7–17 h; previously minor: G9: `.ai` save names a variable font instance's design-space setting, #6388; previously minor: G5: built-in Game Trails brush library; estimate 9–19 → 8–18 h; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: G5: built-in Game HUD graphic style library; estimate 10–20 → 9–19 h; previously minor: G5: built-in Map Markers symbol library; estimate 11–21 → 10–20 h; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview; estimate 1–2 h → 0; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: built-in UI Frames symbol library with default 9-slice; estimate 11–21 h; previously minor: G5: dynamic symbol part on-canvas takes opacity, blend, gradient and pattern; docs Overlap/auto-corners sync; estimate 12–22 h; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap, Pattern brush auto corners and Global Edit Shift-click leave-out moved from Missing to Done (code already shipped); previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; G9: EPS gradients drawn as abutting strips import as one gradient, without seams; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; opening a slow file shows a progress window, part of #5930; Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) + +> Scissors snapping update (2026-11-11): with Alt released, hover and cuts use the Pen's path, alignment, intersection and anchor snaps (#6470). Scores and estimates unchanged. > 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. @@ -8,10 +10,16 @@ ## Feature submission evidence +Draft enhancement #5804: Preferences › File Handling can select a raster editor through the native picker, with a private draft outside engine preferences and generic dialog fields. OK saves it, Cancel discards it, and Reset restores PhotoCraft. With Use System Defaults off, a missing chosen editor falls back to PhotoCraft, then the system default; validation and launch failures are reported. Control/MCP and synthetic input cannot choose an application or run external Edit Original. Web behavior, parity scores and estimates are unchanged; macOS/Linux smoke tests remain pending. + +**2026-11-19 revision:** merged main while preserving the private raster-editor choice; no parity rescore. + > **Eraser fill update (2026-11-11):** filled open paths without a visible painted stroke retain fill outside the sweep or Alt-drag marquee (#6582); stroked paths retain main behavior; scores and estimates unchanged. **Feature evidence last updated:** 2026-11-15. +> **Text thread overlay update (2026-11-11):** repeated selection lookups share an index when needed (#6543); four focused output controls passed; scores and estimates unchanged. + Raster rendering fits and preflattens curved stroke outlines more tightly only below four times the raster tolerance, retaining thin-band coverage without changing stroke weight or vector export geometry. Current cached character/object outlines, cropped long strokes, gradient clips and effect rasters share the helper; cropped-region reuse and guarded flattening remain. The unchanged `fractional_curved_strokes_retain_coverage_between_notches` regression covers fractional weights, rotation, phase, opacity and f32-rounded endpoints. This is a quality/cost tradeoff, not a speed claim. Scores and estimates unchanged. Icon-strip flyouts resize from the canvas-side edge, the top, the bottom and the corners on the canvas side, keeping the icon-column edge anchored (#5713, storytold/craft-libs#1094); a top-edge resize keeps the bottom and saves the moved top per group in workspaces. Independent group heights and flyout widths persist in workspaces; saved heights override content fitting while untouched heights still fit content. Shared panel button bars and the Glyphs font row stay at the bottom after enlargement; the Artboards list grows into the extra space. Regressions: `panel_docking::tests::glyphs_and_artboards_flyouts_keep_user_sizes` and `expanded_panel_footers_stay_at_the_bottom_with_short_and_long_lists`. Scores and estimates unchanged. @@ -40,6 +48,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-18 | minor | G11: SVG export writes physical unit suffixes on the root <svg width="..." height="..."> for documents with physical units (mm, cm, in, pc), preventing drawings from scaling to 75% in external tools and preserving units across round-trips (#864; general unit preference on restart remains open under #864). Estimate 8–15 → 6–13 h. | | 2026-11-18 | minor | G12: Layers panel ruler guide and blend spine row context menus (#8592): Hide/Show, Lock/Unlock, Release Guides, Delete and Locate Object on guide rows; Select, Blend Options…, Reverse Spine, Reverse Front to Back, Expand, Release and Locate Object on blend spine rows. Scores and estimates unchanged. | | 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. | @@ -102,7 +111,7 @@ stage ([ROADMAP.md](../ROADMAP.md)). | 2 | [G9 Illustrator `.ai` and EPS files from real users](#g9-illustrator-ai-and-eps-files-from-real-users) | 10–20 | yes | [file-format-parity.md](file-format-parity.md) | | 3 | [G10 Launch and stability on real machines](#g10-launch-and-stability-on-real-machines) | 20–35 | yes | — | | 4 | [G8 Hardening at scale](#g8-hardening-at-scale) | 30–50 | yes (part) | — | -| 5 | [G11 Correctness bugs in core tools](#g11-correctness-bugs-in-core-tools) | 8–15 | yes | [target-app-parity.md](target-app-parity.md) | +| 5 | [G11 Correctness bugs in core tools](#g11-correctness-bugs-in-core-tools) | 6–13 | yes | [target-app-parity.md](target-app-parity.md) | | 6 | [G4 Advanced type](#g4-advanced-type) | 34–47 | core part | [type-parity.md](type-parity.md) | | 7 | [G12 Preferences and panels that don't act yet](#g12-preferences-and-panels-that-dont-act-yet) | 13–20 | yes | [ui-parity.md](ui-parity.md) | | 8 | [G2 Photoshop-style raster effects and the Effect Gallery](#g2-photoshop-style-raster-effects-and-the-effect-gallery) | 0 | no | [effects-parity.md](effects-parity.md) | @@ -341,6 +350,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Resolved redraw-bounds defect (#5179):** a curved-spine blend's renderer bounds include its rotated keys and steps after Replace Spine; `crates/engine/tests/blend_render_consistency.rs` keeps the straight-blend control and checks all changed pixels against the advertised area. Both focused CPU regressions pass; broader G11 scope and estimates unchanged. - **Improved (#6582), fill-only scope:** the Eraser subtracts its swept area or Alt-drag marquee from filled open contours with no visible painted stroke, preserving fill outside the sweep. Fill-only open compound members are cut together under their compound fill rule so holes stay empty. The result keeps the existing path/compound piece structure and whole appearance. Bounds-fitted gradients on ordinary paths, compounds, groups and layers keep their original evaluated placement when it can be reproduced in the stored paint. Effects that draw replacement artwork, effect plug-ins, Rasterize, gradients along or across a stroke, and flattened placements or placements that cannot reproduce the original appearance keep their existing fitted behavior. Hidden Rasterize rows and hidden strokes with gradients along or across their paths do not block preserving a visible gradient. Already placed gradients and live-effect settings are retained; changes to a live effect's geometry can still move its paint. Path or Compound clipping masks keep every surviving contour in the same mask node; full erasure leaves an empty mask without promoting clipped contents. The mask identity, fill rule, appearance and parent child order are retained. Path Eraser uses the same preservation of the clipping role. Filled-and-stroked open paths deliberately retain the outline-splitting behavior from main. Public reference semantics for those stroked paths were not established, and their fill behavior is not claimed fixed here. Focused engine integration tests cover fixed and varied tips and Alt-drag marquees on fill-only open/closed geometry and pixels, compound holes and self-crossing fill, plus painted-stroke paths that keep the outline route and clipping-mask split, empty-mask and Path Eraser controls. `crates/engine/tests/eraser_open_fill.rs` also includes container-own paint and evaluated-placement regression cases. Scores and estimates unchanged. +- **Implemented (#6470):** Scissors hover and cuts use the Pen's path, alignment, intersection and anchor snapping, following the existing Smart Guides, Snap to Point, Snap to Pixel and Snap to Grid options. Alt still adds an anchor without cutting, and a cut still leaves one new endpoint selected. Headless regressions are in `crates/tools/src/draw2/anchor/tests.rs`; broader G11 scope and estimates unchanged. + - **Export-only improvement (#6309):** 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. Broader G11 scope, scores and estimates unchanged. - **Done, deletion only (#3380):** deleting anchors or segments that disconnect an ordinary contour creates independent selected path objects, preserving appearance, baked transforms, sibling order and one-step Undo/Redo. Existing multi-subpath paths and compound members stay intact. A second Delete removes all selected survivors. Bounds-fitted gradients keep their original placement on the new objects; already placed gradients stay unchanged. Segment endpoint highlighting remains open; broader G11 scope, scores and estimates are unchanged. Evidence: `crates/engine/tests/it/delete_path_pieces.rs` and the Delete/Backspace frame regression in `crates/ui-egui/src/tests/removeanchors.rs`. @@ -403,7 +414,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi such stubs into one vertex (within 4× the sweep's tolerance up and down its frame and 1/16 of the 0.01 pt precision along it, bounded by each cluster's extent so a run of tiny level segments keeps its length); regression tests in `crates/pathops/src/planar.rs`. Estimate unchanged. -- **Missing:** SVG units reverting to points (#864). Shape Builder regions (#937, closed), PDF text placement +- **Done (#864):** SVG export writes physical unit suffixes on the root `<svg width="..." height="...">` for documents with physical units (`mm`, `cm`, `in`, `pc`), so external vector tools (Inkscape, LightBurn) and browsers render drawings at their intended physical scale rather than scaling to 75% under point-based user-unit assumptions; unitless user coordinates in `viewBox` and path geometry remain in 1:1 internal points per SVG 1.1 coords §7.10, preserving document units on round trips (`export_physical_units_writes_unit_suffixes`, `svg_round_trip_preserves_document_units`). General document unit preferences across restarts remain tracked under #864. +- **Missing:** general document unit preference on restart (#864; SVG export physical units done). Shape Builder regions (#937, closed), PDF text placement (#722, above), the bezier drag preview (#834, #3065, #3729) and deleting an interior anchor of an open path (above) are done. - **Done (#722):** PDF text opens where the file draws it. Each line used to come in as point type laid out by the @@ -415,7 +427,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi boxes come back as justified area type. Fixtures written from ISO 32000-1 §9 (`tests_text_placement`). A font that is neither embedded nor installed still draws in a stand-in with the old fit. - **Impact:** wrong output in everyday work. -- **Estimate:** 8–15 h. +- **Estimate:** 6–13 h. ## G4 Advanced type @@ -537,6 +549,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi their patterns; other languages stay whole apart from the Exceptions list (#394, #4947). - **Done (2026-11-18, #8592):** Layers panel guide and blend spine row context menus: right-clicking a ruler guide row shows Hide / Show, Lock / Unlock, Release Guides, Delete and Locate Object / Locate Layer (selecting an unselected editable guide or preserving a multi-guide selection); right-clicking a blend spine row selects the blend and shows Select, Blend Options…, Reverse Spine, Reverse Front to Back, Expand, Release and Locate Object / Locate Layer. Tests in `crates/ui-egui/src/panels/layers/tests.rs`. - **Done (2026-11-14):** Layers panel row context menu: right-clicking a layer, group, or object row shows a context menu (Options…, Duplicate, Delete, Lock Others / Unlock All, Hide Others / Show All, Locate Object, Collect for Export) with proper selection behavior and Undo/Redo tracking. Tests in `crates/ui-egui/src/panels/layers/tests.rs`. +- **Done (2026-11-18):** Layers panel guide row context menu: right-clicking a guide row presents specialized actions (Release Guide, Duplicate, Delete Guide, Lock/Unlock, Hide/Show). Clicking "Release Guide" converts the guide back to a normal unpainted path using `view.guides.release` in one undo step. Tests in `crates/ui-egui/src/panels/layers/tests.rs`. - **Missing:** 2 Preferences options stored but not acted on (#394), each waiting on a subsystem of its own: Plug-ins & Scratch Disks › Primary and Secondary (documents are kept in memory; nothing pages to disk), and Clipboard Handling › Legacy vector clipboard with its Preserve Paths / Preserve Appearance and @@ -691,8 +704,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi libraries ([public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html)): Window › Brush Libraries and the Brushes panel's Brush Libraries Menu open each library in a library panel of - its own (twelve original libraries generated in code: Art Ribbons, Ink and Wash, Calligraphic Nibs, Pressure Sensitive, Bristle Brushes (one - bristle brush for each tip shape), Pattern Borders, Scatter Shapes, Game Trails, Energy Beams, Dry Media (grainy chalk, pencil, crayon and charcoal art brushes), Tech Circuit (Circuit Trace, Bus Lines and Terminal Nodes) and Arrows (Solid, Open, Double, Chevron and Dashed Arrow); User Defined; Other Library… reads the brushes of any document VectorCraft opens); a + its own (thirteen original libraries generated in code: Art Ribbons, Ink and Wash, Calligraphic Nibs, Pressure Sensitive, Bristle Brushes (one + bristle brush for each tip shape), Pattern Borders, Scatter Shapes, Stipple (Fine, Dense, Soft and Bold dot textures), Game Trails, Energy Beams, Dry Media (grainy chalk, pencil, crayon and charcoal art brushes), Tech Circuit (Circuit Trace, Bus Lines and Terminal Nodes) and Arrows (Solid, Open, Double, Chevron and Dashed Arrow); User Defined; Other Library… reads the brushes of any document VectorCraft opens); a click adds a brush to the document's Brushes with the patterns, symbols and other resources its art uses, as one undo step (applied to the selected paths in the same step), dragging one onto a path adds and applies it and @@ -706,15 +719,16 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi Direct Selection of a path, compound path or type inside a dynamic instance also takes opacity and blend (`transparency.set`) and a gradient or pattern fill or stroke (`paint.setFill` / `paint.setStroke`, Eyedropper), for that instance only; - graphic style libraries (Window › Graphic Style Libraries; eleven original libraries generated in code, including + graphic style libraries (Window › Graphic Style Libraries; twelve original libraries generated in code, including Game HUD with Health Fill, Mana Glow, Damage Flash, Quest Outline, Coin Shine and Boss Alert, Status Effects with Poison Tint, Freeze Edge, Burn Aura, Stun Pulse, Stealth Fade and Shield Buff, Neon & Glow with Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet and Cobalt Phosphor, Painted and Sketched with Washed Blue, Bristle Ochre, Pastel Heather, Charcoal Shade, Ink Contour, Wet Ink and Fine Pen, and Textures with Fine Grain, Canvas Weave, Burlap Sack, Cracked Glaze, Mosaic Floor, Quilted Squares, Leaded Glass and Damp Paper, - painted with the texture effects; User Defined; Other Library…; `graphicStyle.libraries`, + painted with the texture effects, and Paper Cutouts with six original layered-paper styles, two colored cut edges + and crisp cast shadows; User Defined; Other Library…; `graphicStyle.libraries`, `graphicStyle.addFromLibrary`). -- **Missing:** more built-in brush libraries beyond the eleven shipped (and further graphic-style libraries beyond the eleven shipped, and further symbol libraries beyond Basic +- **Missing:** more built-in brush libraries beyond the eleven shipped (and further graphic-style libraries beyond the twelve shipped, and further symbol libraries beyond Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons and Weather Icons; original, generated in code, never Adobe's); dynamic symbols' `.ai` read and write. - **Estimate:** 3–13 h (estimated). @@ -723,9 +737,9 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Done:** an initial live Revolve in the `three-d` crate (#846, from the contributor who offered in #605), with automatic smooth vector shading, default-on circular caps and spike-free continuous rims; Extrude & Bevel, Inflate and Rotate with Position presets ([three-d.md](three-d.md), #1407). Colored Inflate has automatic smooth vector lighting from shared membrane normals. White-light Inflate keeps its polygon shading. Every 3D facet's seam has round joins ([three-d.md](three-d.md#seams)). All four take one to ten colored directional lights, with neutral ambient applied once, a light list and independent previewing controls. Standard, Diffuse, Top Left and Right select original rigs, shared with commands; manual settings show Custom. - **Missing:** materials (base, Substance, graphics), shadows, - ray-traced rendering, angular cut caps, exact visibility for intersecting and concave surfaces, the rest of 3D - Classic (Map Art), Turntable, and in 3D export the graphics on Revolve's side, materials and shading (graphics on - planes and Extrude & Bevel's caps are exported as textures). + ray-traced rendering, angular cut caps, exact visibility for intersecting and concave surfaces, Turntable, and in + 3D export the graphics on Revolve's side, materials and shading (graphics on planes and Extrude & Bevel's caps + are exported as textures). - **Impact:** specialist; Materials is the one menu stub left. - **Estimate:** 25–45 h; plan in `plan/` before coding. @@ -766,6 +780,11 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi ## G15 Performance budgets and a GPU renderer +- **Improved (#6543):** text thread overlays share an index for repeated selection membership checks, + keeping the first lookup and selections of one object direct. Four focused controls preserve thread + order, links, ports and perspective exclusions. With 512 two-frame threads and 512 unrelated selected paths, + 2,000 calls took 647.28 ms before and 160.94 ms after in matched quiet runs. The one-selected-path control + adds 1.45 µs per call. [All component figures and controls](target-app-parity.md#text-thread-overlay-filtering). - **Improved (2026-11-05):** after an edit, a long open stroke with an undashed width profile outlines the part near the view and keeps each point's original position along the profile. A 200,000-segment outline took 59.95 ms whole and 8.44 ms cropped in local median runs; this @@ -925,6 +944,7 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv | Date | Change | Summary | |---|---|---| +| 2026-11-18 | minor | G12: Layers panel context menu on guide rows (Release Guide, Duplicate, Delete Guide, Lock/Unlock, Hide/Show); regression tests in `crates/ui-egui/src/panels/layers/tests.rs`; scores and estimates unchanged. | | 2026-11-18 | minor | G4 type: Retype phase 1 (#4934), `type.retype` for outlined text that exactly matches an available font; near matches, the ranked font list and images remain. Scores and estimates unchanged | | 2026-11-18 | minor | Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged. See [production-preflight.md](production-preflight.md) for scope and limits. | | 2026-11-16 | 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. | @@ -948,7 +968,9 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv | 2026-11-11 | minor | Eraser: fixed and varied tips and the Alt-drag marquee cut fill-only open contours and compound holes as areas; stroked open paths retain main behavior (#6582). Scores and estimates unchanged. | | 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 | M5/G15: text thread overlay membership indexing, focused output controls and matched component timings (#6543); scores and 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-11 | minor | G11: Scissors shares the Pen's path/align/intersect/anchor snapping (#6470); existing options, Alt Add Anchor and cut endpoint selection retained. Prepared tool regressions referenced; scope 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/localization-parity.md b/docs/localization-parity.md index dcffe158ea..1f017520cb 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -15,7 +15,7 @@ translation never fails a test or a build: the interface shows the English text `cargo xtask ci` prints the untranslated report (`cargo xtask i18n-report` alone), which lists per language the strings missing from each catalog with the `complete_menus` flag and the messages missing from each language in the `COMPLETE_MESSAGES` list. Every non-English language marked "full" has the flag, and all of them except -Bosnian, Bulgarian and Indonesian are in the list. No language has help content: there is no translated (or +Bosnian and Bulgarian are in the list. No language has help content: there is no translated (or English) in-app help, and the docs are English. **Native review:** every catalog was written clean-room from the English meaning, most of it by agents @@ -36,7 +36,7 @@ Chinese by `imachus`). Georgian and the original Gujarati catalog are recorded a | Arabic | `ar` | 0 | none | document text: bidi layout and Paragraph Direction; interface: no right-to-left layout, no Arabic shaping in egui | no | none | 25–40 | | French | `fr` | 9,166 rows, 3,436 of them `@msg` and 48 `@msgplural` (counted 2026-11-13): the untranslated report lists 178 missing messages for it | all | Latin | no | full | — (review) | | Portuguese | `pt-br` | 9,378 rows, 3,563 of them `@msg` and 48 `@msgplural` (counted 2026-11-13): the untranslated report lists 55 missing messages for it, which open #7116, #7211, #7330, #7378 and #7405 translate; one/other plurals | all | Latin | contributor is a Brazilian Portuguese speaker; further native review welcome | full | — (review) | -| Indonesian | `id` | 6,825 rows, 1,036 of them `@msg` and 47 `@msgplural` (counted 2026-11-14 on `main` at `676f0524cc`): the untranslated report lists 60 missing menu strings, 35 `tl!` literals and 13 undo labels for it; not in `COMPLETE_MESSAGES`, and checked against the same scanned messages it lacks 2,508; one plural form | most dialogs and tooltips; status and error messages partial | Latin | no | full | — (review) | +| Indonesian | `id` | 7,553 rows, 1,682 of them `@msg` and 49 `@msgplural` (counted 2026-11-15 on `main` at `df984b2a02`): in `COMPLETE_MESSAGES`, and the untranslated report lists 50 missing menu strings, 35 `tl!` literals, 11 undo labels and 1,929 messages for it, the same sets as for Danish; one plural form | most dialogs and tooltips; status and error messages partial | Latin | no | full | — (review) | | Japanese | `ja` | 4,004 / 4,020 (99.6%) | partial (3,562 `@msg` and 49 `@msgplural` rows, counted 2026-11-14: the untranslated report lists 98 messages without a Japanese row, 77 of which every complete-message language lacks; open #7116 and #7211 translate 35 of them) | CJK UI font as above; Japanese IME; vertical type partial; Japanese crop marks and composition settings | no | full | — (review) | | German | `de` | 3,952 / 4,020 (98%; menus, literals and messages complete when counted) | all (3,563 `@msg` and 48 `@msgplural` rows, counted 2026-11-13: the untranslated report lists 52 missing messages for it, which open #7116, #7211 and #7378 translate) | Latin | contributor-written, not reviewed | full | — (review) | | Korean | `ko` | 4,870 rows (counted 2026-10-21): menus, `tl!` literals and messages complete when counted; one plural form | all (3,438 `@msg` and 48 `@msgplural` rows, counted 2026-11-13: the untranslated report lists 39 missing messages for it) | Hangul from an installed system font on the desktop (Apple SD Gothic Neo, Malgun Gothic, Noto Sans CJK KR…); the web build fetches NanumGothic from craft-fonts when the interface needs it; IME path exists | no (AI-drafted) | full | — (review) | diff --git a/docs/mcp.md b/docs/mcp.md index 5bc273289c..85b6421469 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -683,9 +683,12 @@ RGB fields in percent, as a double-click right of an RGB field does, and `false` and answers true when the fields show in percent. `ui.colorWheel {"view": "box", "channel": "red"}` shows the Color Wheel panel's box (a color field with the channel's strip at its right) in place of the wheel, as the panel menu's Box View and Box Channel do, and `"view": "wheel"` -shows the wheel again. Keys left out keep their values. Params that are not an object, another key or a value off -the list return an error and change nothing. The command returns `{view, channel, vision}`, and the settings are -kept with the preferences. +shows the wheel again. `{"harmony": true, "harmonyRule": "triad"}` puts a marker on the wheel's ring for each other +color of a Color Guide harmony rule, as Show Harmony and Harmony Rule do; the wheel takes the 15 rules whose colors +each have a hue of their own (not `monochromatic`, `shades`, `complementary2`, `triad2`, `triad3` or +`highContrast2`). Keys left out keep their values. Params that are not an object, another key or a value off +the list return an error and change nothing. The command returns `{view, channel, harmony, harmonyRule, vision}`, +and the settings are kept with the preferences. `ui.colorWheel {"vision": true}` turns on the Color Wheel panel's Show Color Vision Preview, as its panel menu does: a row of four chips under the wheel or the box shows the current color through the protanopia, deuteranopia and tritanopia simulations of `view.proofSetup`, and for achromatopsia as the gray with the color's CIE L*. Each @@ -713,8 +716,8 @@ ends the wait, so the sampler can be shown again. The BSDs and headless sessions | `inspect_document` | `{depth?, childLimit?, ids?, kind?, limit?, offset?}` | Artboards (with `color`, `#rrggbb`, for one with a background color), layer tree (ids, kinds, bounds, paint), selection, history, tool. A type node's `fill`, `stroke` and `strokeWidth` are the paint its characters show (its first run's); fills and strokes of the type object itself come as `objectFill`, `objectStroke` and `objectStrokeWidth`. Paint comes as a label (`"#ff0000"`, `"None"`, `"G1 40% (#ff9999)"` for a swatch at a tint); `paint.proxies` gives it as an object. | | `inspect_ui` | `{}` | UI state. Remote mode only. | | `select_tool` | `{tool}` | `selection`, `directSelection`, `pen`, `rectangle`, `ellipse`, `polygon`, `star`, `lineSegment`, … | -| `pointer_gesture` | `{events:[{kind,x,y,mods?,backquote?,pressure?,tiltX?,tiltY?,rotation?,holdMs?}], tool?, mods?, backquote?}` | `kind` is one of `down`, `drag`, `up`, `move`, `doubleclick`, `tripleclick` (`doubleclick` follows the second click's `up`, and `tripleclick` the third's). `backquote` is the held state for each event; the top-level value supplies its default, and a `backquote` that is not a boolean is an error. Events go through the same path as the mouse. Headless, a `move` replies after the tool's highlight under the pointer is ready, including the Shape Builder's and the Live Paint Bucket's regions of a large selection, which the desktop app finds off the UI thread and highlights after the reply. The release of a Shape Builder click or drag over such a selection replies once the merge is applied, headless and in the desktop app, which computes the merge off the UI thread. In the desktop app, a gesture sent before then is made after the merge, and its reply comes once it is made; a command that can edit, select, save or redraw the documents (a preference, the proof and separations views), sent before then, waits for the merge and runs after it. | -| `pointer_gesture` | `{events:[{kind,x,y,mods?,backquote?,pressure?,tiltX?,tiltY?,rotation?,holdMs?}], tool?, mods?, backquote?}` | `kind` is one of `down`, `drag`, `up`, `move`, `doubleclick`, `tripleclick` (`doubleclick` follows the second click's `up`, and `tripleclick` the third's). `backquote` is the held state for each event; the top-level value supplies its default. Events go through the same path as the mouse. Headless, a `move` replies after the tool's highlight under the pointer is ready, including the Shape Builder's and the Live Paint Bucket's regions of a large selection, which the desktop app finds off the UI thread and highlights after the reply. Remote, the events wait until the keys and other input sent before them (`press_key`, `type_text`) have reached the app, so a key pressed between two calls of one drag applies before the release. When that input is dropped because the document, a dialog or the focus changed first, the call fails and its events are not sent. The release of a Shape Builder click or drag over such a selection replies once the merge is applied, headless and in the desktop app, which computes the merge off the UI thread. In the desktop app, a gesture sent before then is made after the merge, and its reply comes once it is made; a command that can edit, select, save or redraw the documents (a preference, the proof and separations views), sent before then, waits for the merge and runs after it. | +| `pointer_gesture` | `{events:[{kind,x,y,mods?,backquote?,pressure?,tiltX?,tiltY?,rotation?,wheel?,holdMs?}], tool?, mods?, backquote?}` | `kind` is one of `down`, `drag`, `up`, `move`, `doubleclick`, `tripleclick` (`doubleclick` follows the second click's `up`, and `tripleclick` the third's). `backquote` is the held state for each event; the top-level value supplies its default, and a `backquote` that is not a boolean is an error. Events go through the same path as the mouse. Headless, a `move` replies after the tool's highlight under the pointer is ready, including the Shape Builder's and the Live Paint Bucket's regions of a large selection, which the desktop app finds off the UI thread and highlights after the reply. The release of a Shape Builder click or drag over such a selection replies once the merge is applied, headless and in the desktop app, which computes the merge off the UI thread. In the desktop app, a gesture sent before then is made after the merge, and its reply comes once it is made; a command that can edit, select, save or redraw the documents (a preference, the proof and separations views), sent before then, waits for the merge and runs after it. | +| `pointer_gesture` | `{events:[{kind,x,y,mods?,backquote?,pressure?,tiltX?,tiltY?,rotation?,wheel?,holdMs?}], tool?, mods?, backquote?}` | `kind` is one of `down`, `drag`, `up`, `move`, `doubleclick`, `tripleclick` (`doubleclick` follows the second click's `up`, and `tripleclick` the third's). `backquote` is the held state for each event; the top-level value supplies its default. Events go through the same path as the mouse. Headless, a `move` replies after the tool's highlight under the pointer is ready, including the Shape Builder's and the Live Paint Bucket's regions of a large selection, which the desktop app finds off the UI thread and highlights after the reply. Remote, the events wait until the keys and other input sent before them (`press_key`, `type_text`) have reached the app, so a key pressed between two calls of one drag applies before the release. When that input is dropped because the document, a dialog or the focus changed first, the call fails and its events are not sent. The release of a Shape Builder click or drag over such a selection replies once the merge is applied, headless and in the desktop app, which computes the merge off the UI thread. In the desktop app, a gesture sent before then is made after the merge, and its reply comes once it is made; a command that can edit, select, save or redraw the documents (a preference, the proof and separations views), sent before then, waits for the merge and runs after it. | | `draw_path` | `{points \| d, closed?, fill?, stroke?, strokeWidth?, dash?, cap?, join?, opacity?, name?, effects?}` | `points` is `[[x,y],…]` or `[{x,y,in?,out?,smooth?},…]`. `d` is SVG path data. The options are below. | | `draw_shape` | `{shape, …geometry, fill?, stroke?, strokeWidth?, dash?, cap?, join?, opacity?, name?, effects?}` | `rectangle`/`ellipse`: `x,y,width,height` (plus `radius` for corners; an ellipse takes `anchors`, 2–1000, default 4). `polygon`: `cx,cy,radius,sides`. `star`: `cx,cy,radius1,radius2,points`. Polygons and stars take `rotation` in degrees clockwise (0: a corner or point straight up). `line`: `x1,y1,x2,y2`. | | `set_paint` | `{fill?, stroke?, strokeWidth?, ids?}` | Applies to the selection (or `ids`) and becomes the default for new art. Returns `{applied, objects}`: `objects` is the number of objects painted, as the `objects` of the `paint.setFill`, `paint.setStroke` and `stroke.set` replies (the largest of them): a selected group counts the objects inside it. When it is 0, a `note` says that only the paint for new art changed. | @@ -1101,7 +1104,9 @@ in the app runs `paint.setFill` (or `paint.setStroke`, the active proxy) with `i The Swatches panel menu's commands: `swatch.addUsedColors {selection?, global?}`, `swatch.unused` (a query: the names Select All Unused selects; a spot swatch counts as used while an image placed from a DCS file has a plate of its ink), `swatch.merge {names}` (the first is kept; gradient stops linked to the others drop their process -plates), `swatch.ungroup {name}` and +plates), `swatch.ungroup {name}`, `swatch.renameGroup {group, name}` (Color Group Options: renames the group alone +in one undo step; the name is trimmed, and a name that is empty or that another color group or a swatch has is an +error; the group's own name records no undo step, and a drag still in progress becomes an undo step of its own first) and `swatch.sortByKind`. `brush.move {name | names, to?, type?}` reorders brushes among the brushes of their type, as dragging one onto another of its type in the Brushes panel does. `to` is an index among the brushes of that type in `brush.list` @@ -1408,15 +1413,26 @@ PDF/X-4, where an image in the output intent's profile is DeviceCMYK): a CMYK JP 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. +The Summary section's Save Summary… button writes what the section shows to a text file (UTF-8 without a byte order +mark, LF line endings), and its save panel suggests `<document> PDF Summary.txt` in the document's folder; the web +downloads the file under that name. `ui.pdfSummary.save {path}` writes the same text for the open Save PDF dialog or +PDF preset editor to `path` and returns `{path, bytes}`. It uses the Summary the section last drew for the same fields, +document, saved PDF and flattener presets, loaded color profiles and available fonts, and computes the settings only +when there is none. No such dialog open, a `path` that is missing, empty +or not a string, a path outside the automation write roots and settings that +`document.pdfSettings` refuses are errors that write nothing. The dialog stays open and the document does not change. `thumbnails: true` embeds each page drawn small (106 px on its long side, without the layers the page leaves out) as its `/Thumb` image. `fastWebView: true` writes a linearised file (the linearization dictionary first, then the first page with hint tables saying where every other page's objects are), which stays linearised when a password encrypts it. `compatibility: "1.3"` writes a PDF 1.3 file, which has no transparency: a copy of the document is flattened first with `flattenerPreset` (empty: High Resolution; `high`, `medium`, `low` or a saved preset, `flattener.presets.list`) and `flattener` options over it (as `object.flattenTransparency` takes them); images with see-through pixels count as -transparency and rasterized areas are clipped to their regions. Layers the file leaves out (non-printing ones, unless +transparency and rasterized areas are clipped to their regions, with no alpha (`clipComplexRegions` and `preserveAlpha` +given in `flattener` are not used). Layers the file leaves out (non-printing ones, unless `includeNonPrinting` or `createLayers` is set) are left out of the flattening. A file that would still have transparency fails the -export. PDF/X-1a and PDF/X-3 files are PDF 1.3 files too. +export. PDF/X-1a and PDF/X-3 files are PDF 1.3 files too. In the Save PDF dialog, the Custom… button beside Flattener +preset sets `flattener` (`ui.savePdfDialog` keeps a `flattener` it is given, and refuses one it can't read). PDF +presets (`pdf.preset.save`) keep `flattenerPreset` but not `flattener`. In PDF/A-2b files, `.ai` saves and files written with `longPagesInPoints: false`, a page with a side longer than 14,400 pt is written with a `UserUnit` (PDF 1.6): its longer side divided by 14,400, rounded up to the next thousandth, with the page's sizes and coordinates in those units, so that no side is longer than @@ -1873,6 +1889,31 @@ preferences (the folder the desktop app uses, so both see the same ones; `VECTOR 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, 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. +- **Profile Mismatches and Missing Profiles** (`edit.colorSettings {askMismatchOpen, askMismatchPaste, + askMissingOpen}`, all off by default and kept in `Color Settings.json`): with `askMismatchOpen` on, the desktop + app's File › Open asks before a document opens when the profile of its color mode is not the working space (use + the embedded profile, convert the colors to the working space, or discard the profile); with `askMissingOpen` on, + it asks when the document has no profile of its color mode (leave it, assign the working space, or assign a + profile). Each question starts on what the model's policy does, and Cancel leaves the file closed. Files opened + together ask one at a time, each opening only after its own answer. When Color Settings change the question + while it is open (another working space), OK asks the new question instead of opening. `document.open` never + asks: `profileChoice` (`useEmbedded`, `convert`, `discard`; `leave`, `assignWorking`, `assign` with + `assignProfile`) states the answer, else the policy applies. The reply's `profileChoice` names the choice given + for the document's question, not what it did: `convert` from a profile that is not available keeps the profile, + and a warning says the colors were not converted. Copy remembers the profiles the colors showed through (a + document's assigned profile that was removed since counts as the working space it draws through); pasting them + into a document with another RGB or CMYK profile keeps their numbers or converts them, as `profileMismatch` on the + paste commands and `edit.dropSelection` says (`preserveNumbers` or `convert` for both models, or `{rgb?, cmyk?}` + with one for each; `null` is the same as leaving it out), else as the model's policy does (`convert` converts, the + others keep the numbers). Colors whose source or destination profile is not available keep their numbers, also + with `convert`. `clipboard.profileMismatch` lists the models that differ, only those whose colors the copied + objects use (with `sourceDocument` and `ids`, the objects a drop brings; with `allArtboards: true`, without the + background colors of copied artboards, which Paste on All Artboards leaves behind), and gives `convertible: false` + for a model whose colors can't convert. With `askMismatchPaste` on, the desktop app asks first on Paste and on a + drag between documents, and offers only Preserve Numbers for a model that can't convert. A question about both + models has a choice for each, each starting on its model's policy. When the profiles a paste brings or the swatch + conflicts it raises change while the paste question or Swatch Conflict is open, OK asks again about them. New from + Template and File › Revert follow the policies without asking. 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 @@ -2002,7 +2043,7 @@ control channel's `ui.key`, `ui.move`, `ui.wheel`, `ui.click`, `ui.drag`, `ui.po `ui.render` and `ui.set` for their numbers, switches and `mods`, and the headless session's key, pointer and screenshot calls. Omitting a param or giving null keeps its default, with two exceptions: `ui.click`'s `count` and `ui.drag`'s `count` and `steps` refuse null, and a headless pointer event needs its `x` and `y`. A pointer event's `pressure`, -`holdMs`, `tiltX`, `tiltY` and `rotation` must be numbers and its `space` must be `doc` or `screen`. A pointer packet +`holdMs`, `tiltX`, `tiltY`, `rotation` and `wheel` must be numbers and its `space` must be `doc` or `screen`. A pointer packet with one malformed event sends none of its events: ```json @@ -2258,7 +2299,7 @@ and `text.createInPath`; `underline`, `strikethrough`, `allCaps`, `proportionalM in `text.setRangeStyle` and `text.setFormat`, which also checks `hyphenate`, `hyphenateCapitalized` and `romanHangingPunctuation`; `effective` and `story` in `text.getRange`; `story` in `text.setRangeStyle`; `on` in `type.opticalMarginAlignment`, `type.dynamicText`, `type.systemLayout` and `type.fractionalWidths`; `flip` in `type.dynamicTextPreset`; `remove` and `overhang` in `type.ruby`; `expandInstances` in `symbol.delete`; `alt` in -`symbol.spray` and `symbol.adjust`; `spot` and `global` in `swatch.new` and `swatch.edit`; `unlink` in +`symbol.spray` and `symbol.adjust`; `usePressure`, `proportional` and `affectsDensity` in `symbol.adjust`; `spot` and `global` in `swatch.new` and `swatch.edit`; `unlink` in `swatch.delete`; `fromArtwork`, `toGlobal` and `includeTints` in `swatch.newGroup`; `global` and `selection` in `swatch.addUsedColors`; `visible` in `appearance.setItem`; `copy` in `appearance.transfer`; `reverse` and `append` in `appearance.copyFrom`; `reverse` and `stroke` in `paint.editGradient`; `stroke` in `paint.setGradientGeom` and in @@ -3778,6 +3819,45 @@ already walks Image Trace. Short agent entry points: symbol's scale are left as they are, and no undo step is added when nothing changes; an id that names no object, or objects without a symbol instance, is an error. It returns `{ids}`, the instances it changed. The menu item and the button are enabled only while a selected instance would change. +- The symbolism tools' options ([Symbolism tool options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbolism-tool-options.html), + [the archived manual](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=118)): + `symbol.adjust` takes `method` (`userDefined`, `average` or `random`; not used by `shift`), `usePressure` with + `points` as `[x, y, pressure]` (each point's pen pressure, 0..1, is the intensity there), and for `size` + `proportional` (true) and `affectsDensity` (false). `symbol.spray` takes `attributes` + `{scrunch?, size?, spin?, screen?, stain?, style?}`, each `average` or `userDefined`, with `color`, `keepModel` and + `style` for the User Defined stain and style (with `style: userDefined`, a `style` the document does not have is an + error). `symbol.setDensity {from, to, ids?|id?}` gives the selected symbol + sets a new Symbol Set Density. VectorCraft's own rules: + - `random` gives each instance its own share of the tool's change for the whole stroke, from none of it to twice + it (the Spinner: a turn either way), the same each time the stroke is applied. + - `average` moves each instance's value toward the mean of the instances within the brush at that point: the + Scruncher its distance from their middle toward their mean distance, the Sizer the geometric mean of their sizes + on the page, whatever their symbols, the Spinner their mean direction, the Stainer and the Styler their mean amount, the Screener their mean opacity. + `alt` does not reverse it. An instance already at the mean is left as it is, and no undo step is added when + no instance changes. The Screener's average, and the opacity a sprayed instance takes as its average, can be + below the 5% that the Screener otherwise stops at. + - With `userDefined` the Styler gives each instance under the brush the whole style, whatever the intensity or the + pen pressure; `random` scales each instance's share by the brush strength there. + - With `proportional` false a drag resizes along its own direction (a level drag the width, an upright one the + height) and one point resizes both. With `affectsDensity` an instance also moves away from the point as it grows + and toward it as it shrinks. + - A sprayed instance's `average` values are the means of the selected set's instances within `radius` of the + stroke point: their spacing, size on the page (of any symbol), rotation and opacity, and the stain or style of + the nearest one that has one, at the mean amount. With no instance there it has the symbol's own size (not + `scale`), no rotation, full opacity and no stain or style. New instances are spaced by the size they are placed + at. `attributes` left out means `average` for all six. + - `symbol.setDensity` moves each instance of a set along the line from the middle of the set's instances, to + (1.15 − 0.1·`to`) / (1.15 − 0.1·`from`) of its distance from it (each factor at least 0.1), as one undo step, and + adds none when no instance moves and every set already has density `to`. `from` is the density each set was + created at or last given, and the `from` passed applies only to a set without one (a group named "Symbol Set" by + hand); every set then has density `to`, also one whose instances do not move (one instance, or each locked). A + locked or hidden instance stays where it is. It returns `{ids, count}`: the sets changed and the + instances moved. + - A `method` or an attribute outside these values, a point's third number that isn't a number (in `symbol.spray` + too, which does not use it), a `from` or `to` of `symbol.setDensity` outside 1..10, or no symbol set among its + objects, is an error and changes nothing. + - Average leaves an instance without a size (a scale of 0) as it is; the other methods change it. A stroke that + changes no instance counts none and adds no undo step. - Dynamic symbols: an instance of a symbol whose `type` is `dynamic` changes the appearance of objects in the symbol's art for itself only and stays linked. `symbol.instance.setAppearance {id?, path, fill?, stroke?, opacity?, blend?}` names the object by `path`, child indices in paint order from the art's root down through its groups (`[]` is the @@ -3953,6 +4033,18 @@ already walks Image Trace. Short agent entry points: Tilt goes from its first value with the pen lying flat to its second upright, and on Bearing or Rotation from its first value at −180° to its second at 180°. A stroke without that input draws the brush's own value (a Scatter brush's value half way between the two). +- Airbrush finger wheel: `path.freehand` and `brush.freehand` take a point's wheel seventh, + `[x, y, pressure, tiltX, tiltY, rotation, wheel]`, or as `{…, wheel?}`, and a `pointer_gesture` event takes `wheel`, + which the Paintbrush records. The wheel is 0..1 from one end of the wheel's travel to the other. In a point, a + value outside it, or one that is neither a number nor null, is refused; a `pointer_gesture` event's wheel outside + it is clamped, as its pressure is. The stroke keeps it as `wheel` (a point without + one counts as half way). Calligraphic and Scatter `modes` and an Art brush's `width_mode` take `stylusWheel`: the + value goes from the value less the variation (a Scatter brush's first value, an Art brush's `width`) at 0 to the + value plus the variation (the second value, `width_max`) at 1, and a stroke without a wheel draws the value half + way. Brush Options offers Stylus Wheel for a Calligraphic or Scatter brush's Size and an Art brush's Width. The + desktop app reads the wheel from XInput2 (`Abs Wheel`) under X11 and from AppKit (`tangentialPressure`) on macOS; + it does not read it on Windows or in the web build. `.ai` brush definitions read and write the wheel as variation + code 3. - Freehand Fidelity: the `fidelity` of `path.freehand` and `brush.freehand` is in points, 1.5 pt when left out. A value must be from 0.000015625 pt (0.01 / 640) to 100 / 0.0313 pt (about 3194.89 pt), and a value outside that range is rejected with an error. The Pencil and the Paintbrush give Fidelity in screen pixels, 0.01 to 100 px, and send it @@ -4408,6 +4500,13 @@ already walks Image Trace. Short agent entry points: - Image Trace: `imageTrace.presets`, `imageTrace.make {id?, preset?, params?, view?}` (or `imageTrace.makeAndExpand`), `imageTrace.setView`, `imageTrace.expand`, `imageTrace.release`. A key inside `params` that is not one of the trace settings, such as `colours`, is an error that names it and the nearest setting (`colors`), as for a command's own keys. + `imageTrace.setView {view: "split", split?}` is VectorCraft's own view: the window shows the source image on the part of + the image left of a divider across it and the tracing result everywhere else. `split` (0 to 1, default 0.5) is the fraction of the source + image's width, measured from its left edge in its own pixels, that shows the image, so the divider turns with the + image; a value outside 0 to 1, or one that is not a number, is an error. The object keeps `split` when another view is + set and when it is traced again, and the result names it. Exports, printing and Expand draw the tracing result. With + one such object selected, the Selection tool drags the divider (one undo step), and the Image Trace and Properties + panels show a Divider slider that the arrow keys move a percent at a time. With `byColor: true`, `imageTrace.expand` and `imageTrace.makeAndExpand` put each color's paths in a group of their own, named by the global swatch the color links to (a tint with its percentage, as `Sky 50%`) or as `#rrggbb`; gradient fills share a group named `Gradients`. The groups stack in the order of the lowest path in each, and each @@ -5062,6 +5161,52 @@ another shading color is refused with an error and the document is not changed. {"name":"run_command","arguments":{"command":"effect.apply","params":{"effect":"threeD.classicRotate","item":null,"params":{"rotationX":0,"rotationY":40,"rotationZ":0,"surface":"diffuse","blendSteps":64}}}} ``` +## Map Art + +`threeD.mapArt {surface?, symbol?, x?, y?, scaleX?, scaleY?, rotation?, fit?, clearAll?, shade?, invisible?, index?, item?, ids?|id?}` +is the Map Art… button of the Extrude & Bevel (Classic) and Revolve (Classic) dialogs. It maps a document symbol onto +one numbered surface of each selected object's classic 3D effect, edits that map or removes it, in one undo step +([Map artwork to a 3D object](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=189)). +Rotate (Classic) and the other 3D effects take no map. + +- `surface` is a whole number from 1 to the object's surface count. Extrude & Bevel (Classic) numbers the surfaces + through the object's solids in the order they are built: each solid's front cap and back cap, then each side wall + from corner to corner of the outline, then the bevel above each wall. A hollow solid (`cap` false) has no caps, so + its numbering starts at its first side wall, and a solid whose bevel is as deep as the solid has no walls, so its + bevels follow its caps. A side wall is laid out at its own length, and a bevel at the length of + the wall below it. Revolve (Classic) has one surface, its swept + side; on a group it is the side of the member with the longest profile, and the other members take no map. The + numbering is VectorCraft's own. +- `symbol` names the symbol mapped onto the surface, and `null` removes the surface's map, also a map kept past the + object's surface count; `null` with `x`, `y`, + `scaleX`, `scaleY`, `rotation` or `fit: true` is refused. Omitted, the surface keeps its map's symbol, even one the + document no longer has; a surface with no map then is refused. A symbol the document does not have is refused when + `symbol` names it. +- `x` and `y` (points, -1000000..1000000) place the center of the art from the center of the surface laid out flat, + `scaleX` and `scaleY` (1..10000%) scale it from the symbol's own size, and `rotation` (-360..360 degrees) turns it + counterclockwise. A new map starts at 0, 0, 100%, 100% and 0°. +- `fit` (Scale to Fit) centers the art and scales it to fill the surface. +- `clearAll` (Clear All) removes every map first, so with `surface` only that surface's map is left. +- `shade` (Shade Artwork) gives the mapped art the tone and highlight of its face, and `invisible` (Invisible + Geometry) draws only the mapped art. + +One of `surface`, `clearAll`, `shade` and `invisible` is required. Without `index` each object's first Extrude & +Bevel (Classic) or Revolve (Classic) is edited, its own before its fills' and strokes'; `item` needs `index`. A surface +past the count (except to remove a map kept there), an unknown symbol, a value out of range, an unknown key or an object without one of the two effects is +refused, and nothing changes. When nothing changes, no undo step is recorded. It returns `{ids, maps}`: the objects +changed and the first object's maps. + +The maps are the effects' `mapArt` (up to 64 `{surface, symbol, x, y, scaleX, scaleY, rotation}` objects), +`mapShade` and `mapInvisible` parameters, which `effect.setParams` also edits. A map past the object's surface count +draws nothing, as the archived reference describes; the Wireframe surface draws no mapped art. The canvas, exports and +`effect.expandAppearance` draw the mapped art the same way, and renaming a symbol renames it in the maps. The limits +and the shading of the mapped art are VectorCraft's own; see [three-d.md](three-d.md#map-art). + +```json +{"name":"run_command","arguments":{"command":"threeD.mapArt","params":{"surface":1,"symbol":"Label","fit":true}}} +{"name":"run_command","arguments":{"command":"threeD.mapArt","params":{"surface":3,"symbol":null}}} +``` + ## Edit Colors and Recolor Artwork @@ -5275,6 +5420,24 @@ dimmed, so art that mixes colors dims only its other colors, and nothing is dimm selected. Find changes only what the canvas shows: it records no undo step, Cancel leaves the art as it was, and OK applies every row to the art as it does with Find off. +The Undo Changes and Redo Changes buttons beside the Color Theme Picker (`ui.recolorUndo` and `ui.recolorRedo`) go +back and forward one color edit made in the open dialog; Undo Changes has nothing to undo after the dialog is opened +again ([Recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/recolor-options-overview.html)). +A step restores the rows, `colors`, `method`, the Preserve options, `limitTo`, `rule`, `globalAdjust`, `themePicks` +and `weights`, and the art previews the result. Both commands return `{changed, canUndo, canRedo}` and are an error +when Recolor Artwork is not open. VectorCraft's own rules: the dialog's history is separate from the document's undo +history, which changes when OK records the recolor as one undo step and when a color group is saved (below); Cancel +discards the history with the edits. A change is one step once the pointer is released, so a drag on the wheel, a +slider or the Prominent Colors bar is one step, and an action that changes none of those fields is no step. Fields set +with `ui.dialog.set` become a step at the dialog's next frame with the pointer up or the next `ui.recolorUndo` or +`ui.recolorRedo`, so fields set before either are one step together, also across frames drawn while the pointer is +down. Reset is a step of its own, which Undo +Changes reverses. A new edit after Undo Changes leaves nothing to redo. Switching tabs, displays or slider modes, +selecting rows, Find and Preview make no step. The dialog keeps at most 64 steps and 4 MiB of them as JSON, dropping +the oldest first, and always keeps the newest step. A button with no step to go to is disabled. Selecting another color group (or no group) and Save +Changes leave nothing to undo or redo, and an edit after either is a step back to the fields as they were then. Save All Colors and Save Prominent Colors add a color +group to the document at once, as its own undo step, and Cancel and Undo Changes leave that group in place. + The `recolor.*` commands refuse parameters of the wrong form. A `limitTo` or `method` that is not a string gets the error for an unknown library or method. Other wrong-form parameters get an error that names them. `includeImages`, `includePatterns`, a row's `exclude`, `order`, `saturationBrightness` and the `white`, `black` and @@ -5415,7 +5578,7 @@ as a value left out. ## Graphic style libraries Graphic style libraries are read-only sets of graphic styles generated in code (Shadows and Glows, Outlines and -Rules, Hand-Drawn, Textures, Painted and Sketched, Gradient Finishes, Shape Effects, Blends and Transparency, Game HUD, Status Effects). Textures +Rules, Hand-Drawn, Textures, Painted and Sketched, Paper Cutouts, Gradient Finishes, Shape Effects, Blends and Transparency, Game HUD, Status Effects, Neon & Glow). Textures (`textures`) paints its fills and strokes with the texture effects: Fine Grain (`texture.grain`), Canvas Weave and Burlap Sack (`texture.texturizer`), Cracked Glaze (`texture.craquelure`), Mosaic Floor (`texture.mosaicTiles`), Quilted Squares (`texture.patchwork`), Leaded Glass (`texture.stainedGlass`) and Damp Paper (`sketch.waterPaper`). `graphicStyle.libraries` lists them @@ -5435,6 +5598,10 @@ effect that repaints fill and stroke together: `artistic.watercolor`, `artistic. colors and effect settings are VectorCraft's own. These are raster effects, so the document's raster effects resolution sets how fine they draw. +Paper Cutouts (`paper-cutouts`) holds Coral Layers, Mint Layers, Midnight Layers, Sunflower Sheet, +Rose Layers and Monochrome Stack. Each original style paints a solid paper face with two colored +cut edges and a hard, unblurred cast shadow. The colors and shadow offsets are VectorCraft's own. + ```json {"name":"run_command","arguments":{"command":"graphicStyle.library","params":{"library":"hand-drawn"}}} {"name":"run_command","arguments":{"command":"graphicStyle.addFromLibrary","params":{"library":"hand-drawn","name":"Crosshatch","apply":true}}} @@ -5478,8 +5645,8 @@ error. ## Brush libraries -Brush libraries are read-only sets of brushes: twelve generated in code (Art Ribbons, Ink and Wash, Calligraphic Nibs, Pressure Sensitive with Flex Ribbon, Pulse Stroke, Round Flow and Chisel Flow, Bristle -Brushes with one bristle brush for each tip shape, Pattern Borders, Scatter Shapes, Game Trails, Energy Beams, and Dry Media with the Chalk Grain, Graphite Pencil, Wax Crayon and +Brush libraries are read-only sets of brushes: thirteen generated in code (Art Ribbons, Ink and Wash, Calligraphic Nibs, Pressure Sensitive with Flex Ribbon, Pulse Stroke, Round Flow and Chisel Flow, Bristle +Brushes with one bristle brush for each tip shape, Pattern Borders, Scatter Shapes, Stipple with Fine, Dense, Soft and Bold dot textures, Game Trails, Energy Beams, and Dry Media with the Chalk Grain, Graphite Pencil, Wax Crayon and Charcoal Dust art brushes, id `dry-media`, Tech Circuit with Circuit Trace (art), Bus Lines and Terminal Nodes (pattern), id `tech-circuit`, and Arrows with Solid, Open, Double, Chevron and Dashed Arrow art brushes, id `arrows`), the `.vectorcraft` files in the user library folder of the desktop app (User Defined) and the brushes of any document loaded with `brush.loadLibrary` (a document without brushes of its own has the default ones). `brush.libraries` lists them (`id`, `name`, `category`: `builtIn`, `user` or `loaded`, `count`) and @@ -5873,13 +6040,19 @@ and `layerRows`, the rows highlighted in the panel. Selection, and Delete or Backspace on highlighted rows: when a layer or sublayer among the rows holds art, hidden, 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), + Cancel keeps them; an empty layer, a layer with only guides, and groups or objects alone are deleted at once; in + isolation mode, with no row highlighted, a current layer outside the isolated art is an error and nothing is deleted, + and so is a row outside it, given as `ids` or `id`, dropped on the trash or asked about before isolation mode + started), `layer.locate {id?, layersOnly?}` (highlights the selected object's row, or with several selected the row of the one frontmost in the stacking order, whatever order they were selected in; an `id` locates that object instead; the panel opens the rows around it; - it scrolls to it on every call, also when the row was already highlighted; + it scrolls to the row on every call when the row is in the list, also when the row was already highlighted; + Show Layers Only, a search, the filter, or editing an opacity mask on another layer can leave the row out, and then + the panel still opens the rows around it but does not scroll; `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}`) + layer or sublayer holding the object instead, or a layer `id` itself, and returns `{id, objectId, ancestry}`; with a + group or object isolated, the panel's Locate Layer is off) 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, @@ -5888,9 +6061,10 @@ and `layerRows`, the rows highlighted in the panel. `layer.reverse {ids?}`, `layer.template {ids?, on?}`, `layer.hideOthers` / `layer.showAll`, `layer.outlineOthers` / `layer.previewAll` (Ctrl/Cmd+Alt-clicking an eye runs Outline Others for the row's layer, or Preview All Layers when the others are in Outline already), `layer.lockOthers` / `layer.unlockAll` (Alt-clicking an eye or a lock - runs Hide or Lock Others for the row's layer, or Show or Unlock All when the others already are), `layer.pasteRemembersLayers`, + runs Hide or Lock Others for the row's layer, or Show or Unlock All when the others already are; in isolation mode + the panel's menu and row menu turn these pairs off, and the Alt-clicks change nothing), `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 + ruler guide, 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 {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 @@ -5912,7 +6086,9 @@ and `layerRows`, the rows highlighted in the panel. {sublayer?}` open Layer Options (dialog `layerOptions`: name, color, template, locked, visible, printable, preview, dimImages, dimPercent; OK is one undo step; `ui.dialog.set` of `template` also sets `locked` and `dimImages`, as the checkbox does, except a Dim Images set before it; for several `ids` the dialog shows the first row's settings, and OK sends only the fields set with a - control or `ui.dialog.set`; Cmd/Ctrl+Alt+L runs `ui.newLayer` for a new layer), `ui.layersPanelOptions` opens Panel Options (`layersPanelOptions`: + control or `ui.dialog.set`; Cmd/Ctrl+Alt+L runs `ui.newLayer` for a new layer; in isolation mode `ui.newLayer` for a + layer that would be outside the isolated art is an error, OK in the dialog checks again and returns the same error, + and the Layers panel's New Layer and New Sublayer are off then), `ui.layersPanelOptions` opens Panel Options (`layersPanelOptions`: layersOnly, locateSelected, rowSize small|medium|large|other, otherSize, thumbLayers, thumbGroups, thumbObjects), and `ui.layersExpand {ids?, open?}` opens or closes rows as their triangles do (Alt-click: everything inside). With `locateSelected` on (Locate Selected Objects, off by default), when the last selected object changes on the canvas @@ -6255,7 +6431,7 @@ objects differ) and `recentUrls`. `attributes.set {overprintFill?, overprintStro note?, ids?}` sets them in one undo step; `path.setFillRule {rule: "nonZero"|"evenOdd"}` sets the fill rule of the paths and compound paths, and `path.reverse {reversed?}` makes subpaths run counter-clockwise (true) or clockwise (false). When every subpath of a path or compound path turns alike, its strokes' width profiles (left and right swapped) and pen -pressure, tilt, bearing and rotation turn with it, so the strokes draw as before. SVG export wraps an object with a URL in `<a xlink:href>`, and SVG import reads `<a href>` links back. +pressure, tilt, bearing, rotation and wheel turn with it, so the strokes draw as before. SVG export wraps an object with a URL in `<a xlink:href>`, and SVG import reads `<a href>` links back. `recentUrls` keeps the 30 newest distinct URLs given in the session, newest first. The panel's URL menu lists the first 10 of them by default; the panel menu's Panel Options… opens the `attributesPanelOptions` dialog (field `count`), @@ -6502,16 +6678,16 @@ focal points stay highlighted where it left them; Escape during a drag puts the switching to another tool clears them. `path.freehand`, `brush.freehand`, `path.knife`, `path.eraseRegion`, `path.eraseSegments`, `path.smoothRegion`, -`path.joinScrub` and `path.blob` refuse a pen `pressure` outside 0 to 1, a `tiltX` or `tiltY` outside -90 to 90 and a -`rotation` outside 0 to 360 with an error such as `` `tiltX` must be from -90 to 90 ``, naming the key, and a point -given as an array of more than six numbers with `` `points[3]` must be an array of at most 6 entries ``, naming the -point. `path.blob` and `path.eraseRegion` refuse a `size` outside 0.1 to 1000 pt with +`path.joinScrub` and `path.blob` refuse a pen `pressure` outside 0 to 1, a `tiltX` or `tiltY` outside -90 to 90, a +`rotation` outside 0 to 360 and a stylus `wheel` outside 0 to 1 with an error such as +`` `tiltX` must be from -90 to 90 ``, naming the key, and a point given as an array of more than seven numbers with +`` `points[3]` must be an array of at most 7 entries ``, naming the point. `path.blob` and `path.eraseRegion` refuse a `size` outside 0.1 to 1000 pt with `` `size` must be from 0.1 to 1000 `` and a `sizeVariation` over 1000 pt with `` `sizeVariation` must be from 0 to 1000 ``, in every `sizeMode` and when it is left out. `path.blob` refuses a negative `sizeVariation` with the same message, and `path.eraseRegion` with "sizeVariation must be 0 or more". The document and the selection do not change and no undo step is recorded. A null is read as a key left out, and a point given as `[x, y]` has no pen values. The pressure and tilt ranges are those of -[Pointer Events](https://www.w3.org/TR/pointerevents3/); the rotation, size and size variation ranges are +[Pointer Events](https://www.w3.org/TR/pointerevents3/); the rotation, wheel, size and size variation ranges are VectorCraft's own values. `path.eraseRegion` (the Eraser) takes a variation mode for each of its tip's values, as the variation menus of @@ -6519,13 +6695,14 @@ Eraser Tool Options set them ([Erase paths using the Eraser tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/erase-paths-using-eraser-tool.html)): `angleMode` with `angleVariation` (degrees, 0 to 180), `roundnessMode` with `roundnessVariation` (percent, 0 to 100) and `sizeMode` with `sizeVariation` (points, 0 to 1000), each `"fixed"` (the default), `"random"`, `"pressure"`, -`"tilt"`, `"bearing"` or `"rotation"`. A value that varies takes up to its variation either way. Random draws one -value for the drag. Pressure goes from the value less the variation where the pen presses lightest to the value plus -it where the pen presses hardest. Tilt goes from less with the pen lying flat to more with it upright. Bearing and -Rotation go from less at −180° to more at 180° of the way the pen leans or its barrel turns. The tip at each point of -the drag takes what the pen read there (the points' pressure, tilt and rotation, as `path.freehand` takes them); a -drag without that reading, such as a mouse drag, erases at the value itself. One Random value per drag, which way -Tilt, Bearing and Rotation run, and the value itself without a reading are VectorCraft's own rules. +`"tilt"`, `"bearing"`, `"rotation"` or `"stylusWheel"`. A value that varies takes up to its variation either way. +Random draws one value for the drag. Pressure goes from the value less the variation where the pen presses lightest to +the value plus it where the pen presses hardest. Tilt goes from less with the pen lying flat to more with it upright. +Bearing and Rotation go from less at −180° to more at 180° of the way the pen leans or its barrel turns. Stylus Wheel +goes from less at 0 to more at 1 of an airbrush pen's finger wheel. The tip at each point of the drag takes what the +pen read there (the points' pressure, tilt, rotation and wheel, as `path.freehand` takes them); a drag without that +reading, such as a mouse drag, erases at the value itself. One Random value per drag, which way Tilt, Bearing, +Rotation and Stylus Wheel run, and the value itself without a reading are VectorCraft's own rules. The command refuses another mode, and a variation below 0 or past its range, and erases nothing. In the desktop app 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 @@ -6553,9 +6730,9 @@ and `dx`, `dy`, `tol` and `radius` in `path.reshape`. A null is read as a key le an `x` without a `y`, or a `y` without an `x`, with "x and y must be given together". `path.freehand`, `path.curvature`, `path.knife`, `path.eraseRegion`, `path.eraseSegments`, `path.smoothRegion`, `path.joinScrub` and `path.blob` refuse a point in `points` whose x or y is not a number, such as `["10", 10]` or a point written as a -string, with "x and y must both be numbers". All of them except `path.curvature` refuse a pen pressure, tilt or -rotation that is neither a number nor null with `` `pressure` must be a number, not "0.5" ``, naming the key -(`pressure`, `tiltX`, `tiltY` or `rotation`). `path.close` refuses an `at`, `in` or `out` that is not `[x, y]` +string, with "x and y must both be numbers". All of them except `path.curvature` refuse a pen pressure, tilt, +rotation or wheel that is neither a number nor null with `` `pressure` must be a number, not "0.5" ``, naming the key +(`pressure`, `tiltX`, `tiltY`, `rotation` or `wheel`). `path.close` refuses an `at`, `in` or `out` that is not `[x, y]` with `` `in` must be [x, y] ``, naming the key. `path.eraseRegion` refuses an `angle` outside -180° to 180° with `` `angle` must be from -180 to 180 degrees `` and a @@ -6706,6 +6883,7 @@ the release, the tool shows the circle as a dashed outline (solid once it is mor 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. +A press let go within 2 screen points of where it was pressed is a click, also after a drag that came back to it. 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. @@ -6721,6 +6899,38 @@ perspective grid shows with an active plane, a Shift-click opens the size dialog {"name":"run_command","arguments":{"command":"shape.circleThroughPoints","params":{"points":[[0,0],[80,0],[0,60]]}}} ``` +## Curvature circle + +`shape.curvatureCircle {id, subpath?, segment, t, convex?}` draws the circle that touches path `id` at `t` (0 to 1) on +segment `segment` of subpath `subpath` (0 when left out) and bends as the path bends there (its circle of curvature), +as a live ellipse with the current paint, and selects it. The circle goes on the side the path bends toward; with +`convex: true` it goes on the other side. A segment that is the usual cubic of a circular arc of 90° or less (its two +ends the same distance from the center, and each handle 4/3 · tan(θ/4) of the radius long for an arc of θ) gives a +circle with the arc's own radius, and on a circle drawn with the Ellipse tool the result is the circle itself. The +result is `{id, cx, cy, radius, nominal}`, where `nominal` is true for such an arc, and one undo removes the circle. +The circle is not pixel-aligned, even while [Align New Objects to Pixel Grid](#align-new-objects-to-pixel-grid) is on. +The command returns an error and draws nothing on a straight segment or the turning point of an S curve, at a cusp, +at an anchor whose handle is drawn back onto it, at a corner anchor (`t` 0 or 1 where two segments meet at an angle +of more than half a degree and the anchor is not marked smooth with both handles pulled out, or where they turn by +90° or more; segments of no length between them are passed over, and an anchor reached past one is treated as not +marked smooth), when the circle would reach past the canvas (4,000,000 pt from the +origin), when `t` is not from 0 to 1, when `id` is a guide, and when the path, subpath or segment does not exist. + +The Curvature Circle tool, after the Circle tool in the Ellipse tool's toolbar group, draws with this command. The +pointer snaps to the nearest path that is not a guide within 5 screen points, or within Smart Guides › Snapping +Tolerance when that is larger, and the tool shows the circle that matches the path there as a dashed outline (solid +once it is more than 50,000 screen points around), a small cross at its center, a line from the center to the point +it touches and, with Measurement Labels on, its radius by the pointer, followed by an asterisk for an arc's own +radius. A click draws the circle, and a press dragged 2 screen points or more, or canceled with Escape, draws nothing; +Shift held at the press puts the circle on the other side of the path. On a straight segment, at a cusp, at a corner +anchor, or where the circle would reach past the canvas, the pointer shows "Straight segment", "Cusp", "Corner" or +"Circle too large", and a click draws nothing. The pointer passes over the circles the tool drew until another tool +is chosen or an edit, Undo or Redo is made outside the tool. + +```json +{"name":"run_command","arguments":{"command":"shape.curvatureCircle","params":{"id":12,"segment":0,"t":0.5}}} +``` + ## Editing a path with the Curvature tool The Curvature tool edits any selected path, whatever drew it, keeping its shape except where edited (#798). Each edit @@ -6883,6 +7093,11 @@ records the `basis` used, so a recorded action replays in the same frame; a save journal entry recorded before it) plays along the page's axes, as it did when it was recorded. `object.transformAgain` repeats the transform's page matrix, also after Reset Bounding Box. The Scale and Reflect dialogs, the Transform and Properties panels' flips, the Scale tool and the Reflect tool's default axis and Shift steps follow the box the same way; a Reflect axis drawn with the tool is the line drawn on the page. +With the Reflect tool, a plain click (a `pointer_gesture` `down` and `up` without Alt) sets the first point of an axis, and a second +click reflects the selection across the line through both points as one `object.transform` and one undo step. An +Alt-click opens the Reflect dialog and sets no axis, so the plain click after it sets a first point. With +Alt held when the second click is released, the transform has `copy: true` and reflects a copy. A second click whose snapped +point is within 3 screen pixels of the first point's snapped point does nothing. ```json {"name":"run_command","arguments":{"command":"object.scale","params":{"sx":200,"sy":100}}} @@ -7032,6 +7247,13 @@ outlining in red those that reach their limit; the Selection tool shows the widg the Direct Selection tool those of any path. Several objects each with their own corners are one call: `items: [{id, corners?}]` in place of `ids` and `corners`. Alt-clicking one cycles their kind and double-clicking one opens Corners (`ui.corners {id?, corners?}`, dialog `corners`: `kind`, `radius`; OK runs `object.setLiveShape`). +`view.shapeWidgets {on?}` (desktop app, the Hide Shape Widgets and Show Shape Widgets button in the Control bar of the +Rectangle, Rounded Rectangle, Ellipse, Polygon and Star tools) hides or shows the corner widgets of selected live +rectangles and polygons, the pie widgets of live ellipses and the side widget of a live polygon, for the Selection tool +and those shape tools: hidden widgets are not drawn, and those tools do not answer a press, a double-click or the cursor +on them. `on`, when given and not `null`, must be `true` or `false` and sets the state; without it, or with `null`, the +command toggles. The reply is the new state (`true` when shown, the default). The bounding box, the center point and +Direct Selection's corner widgets, which follow `view.cornerWidget` alone, stay as they are, and no undo step is added. ```json {"name":"run_command","arguments":{"command":"object.setLiveShape","params":{"id":12,"corners":[1],"radius":16}}} @@ -7563,6 +7785,9 @@ wheel zooms about the pointer, Shift-wheel scrolls up and down, Cmd/Ctrl-wheel s `ui.wheel` turns the wheel), `trackpadRotateView` (on by default: a two-finger rotation on a Mac trackpad, in the macOS app or in Safari, turns the view about the pointer once it reaches 5°; with it off, the gesture does not turn the view), `zoomToSelection` (on: Zoom In and Zoom Out centre the selection), `showToolTips`, +`showToolCards` (off by default: with `showToolTips` on, resting the pointer on a tool button shows a card with what +the tool does and the keys its hint-bar text lists, for the tools that have a description; a press, drag, key, +modifier key, scroll or pinch puts the card away), `anchorSize` (1–7), `gridColor`, `gridStyle`, `gridsInBack`, `guideColor`, `guideStyle`, `showPixelGrid` (on by default: in View › Pixel Preview at 600% zoom and above, a line at every document pixel over the art), `recentFontsCount`, `antiAliasedArtwork` (on by default; off, the canvas draws the art with hard edges — a pixel is @@ -7906,6 +8131,15 @@ continuous point. Indices that are not the two halves of one discontinuous point 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. +`ui.widthPointEdit {id, indices: [i…]}` (or double-clicking one of several Shift-selected width points) opens Width +Point Edit on several points: Side 1, Side 2 and Total Width are blank (null) where the points differ, a side width +typed in sets that side of every point (both sides while the link is on, which it is when every point has equal sides; +turn it off to keep each point's other side), and Total Width scales each point's own two sides. OK sets them all with +one `stroke.widthProfile.set` (one undo step, none when nothing changed), and Delete removes them all; with a +discontinuous point among them, Incoming and Outgoing edit its two halves and both edit the continuous points. +Malformed or out-of-range `indices`, or more than one of `index`, `indices` and `t`, are errors that open no dialog. OK +and Delete on existing points are refused when those points changed since the dialog opened or another document is +active. `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. @@ -9178,6 +9412,8 @@ the panel, in the order `links.list` gives them; the panel menu passes the selec them. An embedded image gives the name its row shows. An id that is not an image or a placed document, a malformed `ids`, or nothing to copy is an error, and the clipboard is left as it was. +Draft #5804 adds a local, native-picker-only raster editor override when Use System Defaults is off. Its saved choice and Preferences draft are outside engine preferences and `Dialog::fields`: `prefs.set` (including bulk values), `ui.dialog.set` and `ui.set` cannot assign it. The chooser refuses control requests and synthetic input. If the chosen application is missing, Edit Original tries PhotoCraft and then the system default; validation or launch errors are reported. The existing refusal of automated external Edit Original remains. No executable arguments or shell command are accepted. + ```json {"name":"run_command","arguments":{"command":"links.list","params":{"show":"missing"}}} {"name":"run_command","arguments":{"command":"links.placementOptions","params":{"ids":[12],"preserve":"fit","align":"top"}}} @@ -9204,9 +9440,14 @@ result carries the same files as a zip (`{name: "<name>.zip", dataBase64}`, entr `document.info {selectionOnly?, category?, format?: "text"}` adds `sections` (`[{id, title, rows: [[label, value]]}]`: document, objects, graphicStyles, brushes, spotColors, patterns, gradients, symbols, fonts, fontDetails, linkedImages, embeddedImages, repeats), `fonts` (the fonts the document's type uses, the type in opacity masks and in the art of -its symbols and pattern swatches included, which the fonts and fontDetails categories list; with `selectionOnly`, the -fonts of the selected type), `fontDetails` (`[{font, match, family, style, file, embedding}]`: each font of `fonts`, -in order, as the fontDetails category's rows give it: `match` is `exact`, `style` (a style the family lacks, shown in +its symbols and pattern swatches included, type in a composite font giving the fonts of the parts its characters fall +in, which the fonts and fontDetails categories list; with `selectionOnly`, the fonts of the selected type), +`fontUses` (`[{font, type, uses}]`: each font of `fonts`, in order, as the fonts +category's rows give it, such as `TrueType; 2 uses`: `type` is `truetype` or `opentype` by the outlines of the face +the type is drawn in (`glyf`, or `CFF` or `CFF2`), `unknown` for a font not installed in the family and style it +names; `uses` is the number of text objects set in the font, each counted once however many of its runs use it, the +type in a mask or in a symbol's or pattern's art once however many objects show it), `fontDetails` +(`[{font, match, family, style, file, embedding}]`: each font of `fonts`, in order, as the fontDetails category's rows give it: `match` is `exact`, `style` (a style the family lacks, shown in `family` `style`), `missingWithFallback` (not installed, shown in `family` `style`) or `missing`; `file` is the face's file name, null for a built-in face; `embedding` is `allowed`, `editing`, `previewPrint` or `forbidden`, null when no face is found), `imageObjects` (`[{name, width, height, linked, file}]`: the image objects in the order the @@ -9602,9 +9843,10 @@ starts a new point type object at the position the advance gives, and an underli of the last character's advance. Type on more than one line is placed a line at a time: each line is aligned by its own advances and split as a single line is. An EMF that draws with EMF+ records is read from them. Hatched and pattern brushes fill with their average color. Records VectorCraft doesn't read are skipped with one warning. -Each of these adds one warning, with a count: a file, or a metafile image inside it, cut short by one of the reader's -limits; images and pattern brushes whose bitmap can't be read, which are left out; clips that can't be applied as the -file sets them; and raster operations other than a plain copy, drawn as a plain copy or left out. +A file, or a metafile image inside it, cut short by one of the reader's limits adds one warning without a count. +Each of these adds one warning, with a count: images and pattern brushes whose bitmap can't be read, which are left +out; clips that can't be applied as the file sets them; and raster operations other than a plain copy, drawn as a +plain copy or left out. `clipboard.importEmf {dataBase64, center?}` loads an EMF or WMF picture into the clipboard for `edit.paste`; the app pastes `image/emf` from the system clipboard ahead of text and bitmaps when the platform's clipboard service offers it (the Windows desktop service doesn't read metafiles yet). @@ -9736,6 +9978,15 @@ a warning. {"name":"run_command","arguments":{"command":"document.export","params":{"format":"hpgl","path":"/tmp/stencil.plt","sortPaths":true,"insideFirst":true}}} ``` +In the app, Export As… with the HP-GL format opens HP-GL Options (`ui.hpglOptionsDialog` opens it too): Version, +Curve Tolerance, Origin (Bottom Left or Center), Pens (One Pen per Color, or Pen Table with a row per pen to type +its color, remove it or add one), Draw the Nearest Path Next (`sortPaths`) and Draw Inner Paths First +(`insideFirst`). Pen Table starts from the pens One Pen per Color gives the art this export plots (the chosen +artboards, the bounds of the art, or the selection with Export Selection or Export Selected Art Only), or one black +pen when that art draws nothing. When the export refuses the options or the artboard choice, One Pen per Color stays +chosen and the dialog shows why. OK checks the options and the artboard choice, and remembers the options for the +next export; a canceled save panel writes nothing and keeps the options remembered before. + ## TIFF, BMP and Targa export `document.export` (and `export`) writes them like the other raster formats: one artboard (or `useArtboards`, one @@ -9905,7 +10156,8 @@ asset's `format3D` (null for a picture asset). `.usda`, `.usdz`, `.gltf` (glTF 2.0, its buffer embedded) or `.obj` with its `.mtl` (whitespace and `#` in an OBJ's name become `_`). Every solid of the object (the fill's, each stroke's, a group's members') is its own mesh, with a two-sided material in the color it is painted -(a gradient's stops averaged, a pattern gray). The mesh holds the solid's faces before they are projected onto the +(a gradient's stops averaged, a pattern gray); a solid with mapped graphics is split into a textured mesh for each face +that carries them and a plain mesh for the rest, as described below. The mesh holds the solid's faces before they are projected onto the page, those turned away from the viewer included, at the object's 3D rotation, y up, about the point the object turns about: in points (USD's layer gives `metersPerUnit`), in meters in glTF. Files that would share a name get `-2`, `-3` and so on. Graphics mapped onto a plane or onto Extrude & Bevel's front or back cap (`threeD.mapGraphic`) are exported as a PNG @@ -9920,8 +10172,11 @@ and an MTL `map_Kd`; OBJ and USDA write the PNG beside them as `<name>-texture-1 whose face is not opaque also gets `<name>-texture-1-opacity.png`, the alpha as gray levels, for the MTL's `map_d`. Faces with the same color, graphics and bounds share one texture. `textureSize` (128 to 4096, default 1024, VectorCraft's own values) is the number of pixels along the longer side of each texture; one export -draws at most 67,108,864 texture pixels in all, and past that it is refused. Graphics on Revolve's side are not -exported yet. The layouts follow glTF 2.0, UsdPreviewSurface (<https://openusd.org/release/spec_usdpreviewsurface.html>) +draws at most 67,108,864 texture pixels in all, and past that it is refused. Graphics on Revolve's side are a texture +of the side unrolled as the canvas lays it out (around the axis, the angle times the distance from the axis; along the +profile, its length), on a mesh of the side's triangles; its end caps and cut sides stay plain, and a full turn's +texture is cut at the back, where the canvas cuts the graphics. In a group, the graphics go on the side of the member +with the longest profile. The layouts follow glTF 2.0, UsdPreviewSurface (<https://openusd.org/release/spec_usdpreviewsurface.html>) and OBJ/MTL (<https://www.loc.gov/preservation/digital/formats/fdd/fdd000508.shtml>). With `zip`, the files go into one ZIP named after the document with `-3D` added (`Untitled-1-3D.zip`), or `3D Assets.zip` when the document's title gives no file name. @@ -10899,12 +11154,50 @@ which Japanese characters may not start or end a line. **Hard** (the default; ne setting) keeps closing brackets, commas, full stops, middle dots, iteration marks, the prolonged sound mark ー and small kana off the line start, and opening brackets off the line end. **Soft** lets 々, ー and small kana start a line, as JLREQ's level 3 line-breaking rules do (https://www.w3.org/TR/jlreq/#addendum_a3); the rest of the set stays. -**None** applies no kinsoku. `hard` isn't saved. One undo step. +**None** applies no kinsoku. `hard` isn't saved. The name of a custom set of the document (`type.kinsokuSets.list`, any +case) gives each paragraph a copy of that set, saved with the paragraph (`kinsoku_set` in `para`) beside Hard, so an +older build reads the paragraph as Hard; a name the document has no set of fails the call and changes nothing. +Paragraph styles carry the set; `paraStyle.new` and `paraStyle.setAttrs` given `kinsoku_set` with `kinsoku` None or Soft, +or with a blank or built-in set name, fail and change nothing. One undo step. ```json {"name":"run_command","arguments":{"command":"text.setFormat","params":{"kinsoku":"soft"}}} ``` +## Kinsoku Shori Settings + +`type.kinsokuSets.set {sets: [{name, from?, cannotStart?, cannotEnd?, hanging?, inseparable?}]}` (Type › Kinsoku Shori +Settings…'s OK, shown with the East Asian options) replaces the active document's custom Kinsoku Shori sets as one undo +step, and records none when nothing changes. `cannotStart` lists the characters that never start a line, `cannotEnd` +those that never end one, and `hanging` the punctuation that Burasagari hangs outside a line's end, each as text, one +character after another. `inseparable` lists sequences of 2 to 16 characters that a line never breaks inside while +Bunri-Kinshi is on. `cannotStart`, `cannotEnd` and `hanging` keep each character once, sorted; `inseparable` keeps each +sequence once, sorted, so a sequence may repeat a character (`……`). Each category holds at most 4096 characters (a +sequence counts each of its characters); a control or space character in a category fails the call. Names are trimmed, 1 to 128 characters, unique in any +case and never None, Hard or Soft; a document holds at most 256 sets. These limits are VectorCraft's own. A set with +the name of a set the document has (any case) and no `from` edits that set; `from` names the set it renames. Every +paragraph and paragraph style using an edited set takes its new characters and name, and those using a set left out +take Hard. An unknown key, a null value, a name used twice, a `from` the document has no set of and a sequence of one +character fail the call and change nothing. The built-in None, Hard and Soft are not stored and can't be changed. → `{sets}`. + +`type.kinsokuSets.list` returns the sets with how many paragraphs (`paragraphs`), paragraph styles (`styles`) and graphs +(`graphs`, in the paragraph attributes a graph keeps for its labels) use each. `type.kinsokuSets.base {base: "hard"|"soft"|"none"|name, name?}` returns the categories a new set based on a +built-in or custom set starts with: Hard and Soft list the characters they keep off a line's start and end, the East +Asian comma and full stop as hanging punctuation and the Bunri-Kinshi pairs; None lists nothing. + +Type › Kinsoku Shori Settings… opens a dialog on the document's sets: Kinsoku Set picks one, New adds a set based on +the choice in Based on (Hard, Soft, None or a set of the dialog), Delete takes the one picked out, the four fields edit +its categories (inseparable sequences separated by spaces), and Unicode with Add puts the character of a code point +(`U+3001` or `3001`) into Cannot Start Line, Cannot End Line or Hanging Punctuation. Nothing changes until OK, which +runs `type.kinsokuSets.set`; a refused set keeps the dialog open. The Paragraph panel's Kinsoku Set lists the custom +sets after None, Hard and Soft, and its last entry opens the dialog. Importing and exporting sets is not available. +The help page: +https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/use-kinsoku-for-japanese-line-breaking.html + +```json +{"name":"run_command","arguments":{"command":"type.kinsokuSets.set","params":{"sets":[{"name":"Tight","cannotStart":"、。」ー","cannotEnd":"「(","hanging":"、。","inseparable":["——","……"]}]}}} +``` + ## Kinsoku Shori Type `text.setFormat {kinsokuType: "pushInFirst"|"pushOutFirst"|"pushOutOnly"}` (Paragraph panel menu › Kinsoku Shori Type, @@ -10917,8 +11210,8 @@ of the character before it and by at most a tenth of that em; a line that cannot tab, pushes out instead. **Push Out First** pushes in the same way only when pushing out would leave the line more than an em, of the character before the break, short of its measure. **Push Out Only** (the default: new type and documents from before the setting) moves the -character before a prohibited line start to the next line with it. With Burasagari on, an overflowing comma or full -stop may hang outside the margin first, leaving the preceding character on the line. With Kinsoku Set None the setting +character before a prohibited line start to the next line with it. With Burasagari on, overflowing hanging punctuation +of the Kinsoku Set may hang outside the margin first, leaving the preceding character on the line. With Kinsoku Set None the setting does nothing. When Push In First or Push Out First is selected and a paragraph contains a prohibited line-start or line-end character, the whole paragraph is broken line by line, as the Single-line Composer breaks it, even if no line ends up pushing a character in. The setting is saved @@ -10936,10 +11229,13 @@ on or off for the paragraphs of the selected type (or `ids`, or the paragraphs a line never breaks inside an inseparable pair: two em dashes (U+2014), two horizontal ellipses (U+2026), two two-dot leaders (U+2025), or the upper half of a vertical kana repeat mark (U+3033 or U+3034) followed by its lower half (U+3035), the pairs W3C JLREQ lists for its class cl-08 (https://www.w3.org/TR/jlreq/#cl-08), which are VectorCraft's -set. A chain of em dashes stays together as well. A pair is two neighboring characters, whatever their fonts and -styles; a forced line break between them ends the line as before. Both composers, vertical type, Kinsoku Shori Type, -hyphenation and No Break follow it, and a pair wider than the line stays whole on it. Justification adds no space inside -a pair. The setting works only with a Kinsoku Set: with Kinsoku Set None the paragraph keeps the value without effect, +set for Hard and Soft. A chain of em dashes stays together as well. With a custom Kinsoku Set, the set's inseparable +sequences (Kinsoku Shori Settings) replace these pairs: a line never breaks between two characters of an occurrence of +one of them, such as `AB` or `あいう`, and occurrences may overlap. A custom set keeps a built-in pair together only +when it lists that pair, as a set based on Hard or Soft does. A pair or sequence is neighboring characters, whatever +their fonts and styles; a forced line break between them ends the line as before. Both composers, vertical type, +Kinsoku Shori Type, hyphenation and No Break follow it, and a pair or sequence wider than the line stays whole on it. +Justification adds no space inside a pair or sequence. The setting works only with a Kinsoku Set: with Kinsoku Set None the paragraph keeps the value without effect, and the menu item is unavailable. Off by default, for new type and for paragraphs saved before the option. It is saved with the paragraph (`bunri_kinshi` in `para`) only when on, paragraph styles carry it (Paragraph Style Options › East Asian Composition Settings), and Reset Panel turns it off. A value that is not true or false is refused. One undo @@ -10998,9 +11294,11 @@ help page: https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-an ## Hanging punctuation (burasagari) `text.setFormat {burasagari: "none"|"standard"|"forced"}` sets the Paragraph panel menu's Burasagari (None / Regular / -Force) of the selected type (or `ids`): an East Asian comma or full stop ending an area type line (、。,., half-width -、。) hangs outside the frame, Regular only when it doesn't fit, Force always (the rest of the line then fills the -measure). Closing brackets and Latin punctuation don't hang; point type, right-to-left and hyphenated lines are left as +Force) of the selected type (or `ids`): hanging punctuation ending an area type line hangs outside the frame, Regular +only when it doesn't fit, Force always (the rest of the line then fills the measure). With the Kinsoku Sets None, Hard +and Soft, the hanging punctuation is the East Asian comma and full stop (、。,., half-width 、。), and closing brackets and +Latin punctuation don't hang. A custom Kinsoku Set hangs the characters in its `hanging` category instead (Kinsoku Shori +Settings), closing brackets and Latin punctuation included. Point type, right-to-left and hyphenated lines are left as they are. The hanging mark is as wide as its punctuation spacing makes it (`mojikumi`). New type (the Type tools, `text.create`) takes `standard`; documents from before it and imported text keep `none`, except legacy `.ai` type with binding punctuation (`Tg`) on, which opens as `forced`. `none` isn't saved. One undo step. @@ -12117,11 +12415,17 @@ Transform Object Only while it is off. Use Registration Point for Symbol is the `useRegistrationPointForSymbol` preference: with it on and one symbol instance selected, those panels show and set X and Y at the symbol's registration point (`symbol.options` `registration`) where the instance's transform puts it (after a flip the art's top-left corner is the box's top-right one), give `reference` as the box's point nearest it -and turn, shear and flip about it (`origin`). +and turn, shear and flip about it (`origin`). Show on Shape Creation is the `showOnShapeCreation` preference (off +until set): with it on, the app shows the Transform panel, as `window.panel {"panel": "transform"}` does, after a +`shape.rectangle`, `shape.ellipse`, `shape.polygon`, `shape.star` or `shape.line` succeeds, alone, as a +`command.batch` step or on the active perspective plane as the `command` of `perspective.draw`, whether a shape tool's drag, its dialog, the Shaper tool or an agent ran it. A panel that is showing already +stays as it is. Failed commands, saved steps an action plays, a script's commands and Presentation Mode leave the +panels as they are. ```json {"name":"run_command","arguments":{"command":"prefs.set","params":{"key":"transformPanelPatterns","value":"pattern"}}} {"name":"run_command","arguments":{"command":"object.setBounds","params":{"x":170,"reference":4,"objects":false,"patterns":true}}} +{"name":"run_command","arguments":{"command":"prefs.set","params":{"key":"showOnShapeCreation","value":true}}} ``` ## Plug-ins @@ -12441,7 +12745,13 @@ tool keeps last across tool switches (and documents) and are saved with the pref `prefs.get`'s full object), as the reference app keeps them: the Liquify tools' brush and tool options, Mirror & Cut's axis and side, Puppet Warp's mesh, the Symbolism brush, the line, grid, pencil, brush and eraser tools' options, polygon sides and star points, the Flare Tool Options and the Shape Builder Tool Options. The Liquify tools share one set of Global Brush Dimensions (width, height, angle, -intensity), and the Symbolism tools one brush. Interaction state (pins, a reference point) starts afresh. In the +intensity), and the Symbolism tools one brush: `diameter` (80), `intensity` (5), `density` (5), `usePressure` (false), +`method` (`userDefined`), `showBrush` (true), `sprayScrunch`, `spraySize`, `spraySpin`, `sprayScreen`, `sprayStain` +and `sprayStyle` (each `average`), `proportional` (true) and `affectsDensity` (false); these starting values are +VectorCraft's own. With `showBrush` the brush's outline follows the pointer, with a dashed ring inside it at +`intensity`/10 of its radius (no ring at 10, with `usePressure` or for the Symbol Sprayer, which uses neither). For a +Symbolism tool, a `method` or Symbol Sprayer value not in those lists, or a `usePressure`, `showBrush`, `proportional` +or `affectsDensity` that is not true or false, is an error that sets none of the values. Interaction state (pins, a reference point) starts afresh. In the 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). @@ -12495,7 +12805,12 @@ options' counts and growth, without a `ringSeed`. The Artboard tool's are the ac are the artboard's top-left corner in document points, while the dialog shows X and Y at the reference point the Transform panel uses, counted from the ruler origin), a graph tool's the selected graph's Graph Type (dialog `graphType`, described below; an error without one), a Symbolism tool's the Symbolism Tools Options (dialog -`symbolismOptions`: `diameter` in points, `intensity` and `density` 1–10, one brush for the eight tools) and the +`symbolismOptions`: `tool` (the tool whose options show, which the Tool row changes), `diameter` in points, +`intensity` and `density` 1–10, `usePressure`, `method` (`userDefined`, `average` or `random`), `showBrush`, the +Symbol Sprayer's `sprayScrunch`, `spraySize`, `spraySpin`, `sprayScreen`, `sprayStain` and `sprayStyle` (each +`average` or `userDefined`) and the Symbol Sizer's `proportional` and `affectsDensity`: one brush for the eight +tools. OK runs `tool.setOption {tool, values}`, and with symbol sets selected and a new `density` it first runs +`symbol.setDensity` from the density the dialog opened with) and the Magic Wand tool's its panel. `ui.newArtboard` (Alt-click on the Artboards panel's New Artboard) opens Artboard Options for a new artboard, with `new: true` and the name, position and size that `artboard.new {}` would give it. OK runs `artboard.new` with the fields and makes the new artboard the active one, and Cancel adds no artboard. @@ -12981,8 +13296,8 @@ step, and `press_key` Escape or a switch to another tool during it puts the valu How blends interpolate: closed shapes start where they twist least unless `starts` picks the anchors; strokes interpolate weight, dashes (a solid stroke counts as the dashed one with its gaps closed), miter limit, arrowhead scale, -width profiles and the pen pressure, tilt, bearing and rotation recorded with the Paintbrush (a stroke without a -recording counts as half pressure, half tilt and 0°, as brushes read it; angles turn the shorter way round; a key's +width profiles and the pen pressure, tilt, bearing, rotation and wheel recorded with the Paintbrush (a stroke without +a recording counts as half pressure, half tilt, 0° and the wheel half way, as brushes read it; angles turn the shorter way round; a key's profiles, recordings, arrowheads, dashes and gradient along or across the stroke turn with its path when the blend starts it at another anchor), while caps, joins, alignment, arrowheads and brushes switch halfway; gradients of one kind with different stop counts resample to a common set of stops, keeping each step (two stops at one offset). Groups pair their members in stacking order (members only @@ -13435,12 +13750,12 @@ type and evening out horizontal scales are not there yet. Path Precision Tools is a built-in add-on for exact anchor and path work: its commands are `addon.pathtools.*`, and in the desktop app it lives in Object › Plug-ins › Path Precision Tools, in its Anchor Inspector panel (`window.panel {panel: "anchorInspector"}`), in its Parametric Shape panel (`window.panel {panel: "parametricShape"}`) -and in eight tools: `anchorEraserBrush`, `extendPath`, `measureInspect`, `parametricShape`, `cornerTool`, `slideAnchor`, -`sharedEdge` and `trimAtCrossings`. The toolbars don't show the first seven until they are added from the All Tools -drawer (or chosen with `tool.select`); `trimAtCrossings` is in the Scissors tool's group in both shipped toolbars, -after the Knife, and `ui.tool.list` lists it there. A toolbar edited before it joined keeps its saved layout until -Reset Toolbar. None has a shortcut; one can be set in Edit › Keyboard Shortcuts › Tools. Each edit is one undo step, -and an edit that changes nothing makes no step. +and in nine tools: `anchorEraserBrush`, `extendPath`, `measureInspect`, `parametricShape`, `cornerTool`, `slideAnchor`, +`sharedEdge`, `tangentCircle` and `trimAtCrossings`. The toolbars don't show the first eight until they are added from +the All Tools drawer (or chosen with `tool.select`); `trimAtCrossings` is in the Scissors tool's group in both shipped +toolbars, after the Knife, and `ui.tool.list` lists it there. A toolbar edited before it joined keeps its saved layout +until Reset Toolbar. None has a shortcut; one can be set in Edit › Keyboard Shortcuts › Tools. Each edit is one undo +step, and an edit that changes nothing makes no step. Tools: @@ -13489,6 +13804,28 @@ Tools: different in length, or at over 120° at an end, are left alone. Options (`tool.setOption`, or the panel, kept with the preferences): `diameter` (0.25 to 200 pt, 20), `tolerance` (how near two anchors count as coincident, 0 to 3 pt, 0.002) and `together` (Keep Shared Points Together). +- **Tangent Circle Tool** (`tangentCircle`): draws a circle on two path segments of any unlocked paths, selected or + not. A click picks the first segment; over a second segment the circle that would be drawn shows (red) with its + center, its radii to the two touch points and its radius, or a note that there is none. A click there draws the + circle that is tangent to the first segment at the point clicked and touches the second (its center on the first + segment's normal there). With Shift the circle instead has the tool's `radius` and may touch the first segment + anywhere along it. A drag from the second segment sets the radius to the drag's length, and the circle may again + touch the first segment anywhere along it; Shift steps the radius by 1, 2 or 5 times a power of 10 pt, at least 4 + screen pixels long (2 pt at 200%), and Cmd/Ctrl pressed during the drag moves it by a tenth of the pointer's + movement (held at the press, Cmd/Ctrl lends the selection tool, as for every tool). + The segments on either side of the second one, on its subpath, count with it (the first segment excepted; the two + may be on the same path, and the first segment picked again gives no circle), and of the circles found the one + touching them nearest the pointer is drawn (in a drag, nearest the press). A circle touches them when they lie + outside it with a point on it (within a millionth of its radius); it never crosses the first segment, and it + touches the two segments at different points. The circle is a new ellipse with the current paint, drawn through + three of its points with `shape.circleThroughPoints` so that Align New Objects to Pixel Grid leaves it in place, one + undo step. A circle too small or too large for its three points to give it back in floating point counts as no + circle. Shift pressed or let go during a click counts at the release. With no circle the note shows, a click draws + nothing and the first segment stays picked; it also stays when drawing the circle fails or the press on the second + segment is canceled (a canceled touch). Escape, an edit, Undo or Redo outside the tool, or another document forgets + the first segment. + Option (`tool.setOption`, or a double-click on the tool): `radius` (pt, 0.01 to 1000000, 36). `tool.setOption` + gives an error for a value outside that range or one that is not a number, and for any other option. - **Trim at Crossings Tool** (`trimAtCrossings`): removes stretches of paths between the places where they are crossed, on any path that can be edited, selected or not. A click runs `addon.pathtools.trim` with `at`, for the path within 4 screen pixels of the pointer. A drag draws a rectangle and runs it with `rect` on release; once the pointer has @@ -13689,12 +14026,12 @@ Commands: only. A path inside the other has none. Paths that touch, from outside or from inside, share one tangent there instead: a line centered on the point where they touch and as long as the narrower path is wide along it. Paths that meet at a corner or along a shared stretch of outline get one such line, at the middle of the directions that - touch both. Paths count as touching when the gap between them is less than the tolerance, a billionth of the larger + touch both. Paths count as touching when the gap between them is at most the tolerance, a billionth of the larger of their sizes and the distance between their centers. One of the two may be a point instead, a path of one anchor: the lines then run from the point to where they touch the path, two when the point lies outside it (one that lies along a straight side covers the whole side), one when the point lies on its outline (centered on the point and as long as the path is wide along it, or the whole straight side the point lies on), and none when it - lies inside. The point counts as on the outline when it is less than the touching tolerance from it, with the + lies inside. The point counts as on the outline when it is at most the touching tolerance from it, with the point's distance from the path's center in place of the distance between centers. Every `tangents` value gives the same lines, counted in `internal` when `tangents` is `internal` and in `external` otherwise; the centerline runs from the point to the path's center. Two points are refused with "select two closed paths". The lines are @@ -13703,6 +14040,40 @@ Commands: nothing changes, and the result's `warning` says why. Common Tangents… opens a dialog (Tangents, Centerline) with Preview; with a point selected, every Tangents choice gives the same lines. → `{ids, external, internal, centerline, warning?}` (`centerline`: the centerline's id, or null). +- `addon.pathtools.boundingRectangle {each?, offset?}` draws a live rectangle on the geometric bounding box of the + selected objects, strokes and effects left out (Object › Plug-ins › Path Precision Tools › Add Bounding Rectangle…, + #6966). `addon.pathtools.boundingCircle {each?, offset?}` draws the smallest live circle that holds the outlines of + the selected objects (Add Bounding Circle…). The circle reads paths and compound paths by their curves, clip groups + and sublayers that clip their contents by their clipping paths, other sublayers by their shown objects, images by + their corners, and type and other objects by the corners of their bounding box. It splits each curve into pieces + until every piece's control points lie within 0.01 pt of its chord, fits the circle to the ends of the pieces, and + makes the radius 0.01 pt larger, so the circle holds the curves themselves. A curve is split into 1,024 pieces at + most. One command makes at most 1,048,576 splits at any depth, and with `each` every shape gets an equal share. A + shape that has used up its share splits each further curve into at most 8 pieces, with at most 7,340,032 more + splits shared the same way (8,388,608 in all), and then counts each further curve whole. A piece that still bends more counts by the hull of its control points cut down to its bounding box, which + can make the circle larger than the smallest one. Before the 0.01 pt is added, the circle around a circle of four + curves is less than 0.3% larger when each curve is split into 8 pieces, and about 14% larger when each counts + whole. A path of a compound path selected on its own + counts as an object, as `object.transform` moves it. `offset` (0 or more, default 0) adds space: a rectangle grows + by `offset` on each side and a circle's radius grows by `offset`. `each: true` draws one shape around each selected + object instead of one around the whole selection. The menu items Add Bounding Rectangle… and Add Bounding Circle… + open a dialog with Offset (0 to 4,000,000 pt, default 0), One per Object (`each`, default off) and Preview; OK draws + the shapes as one undo step, and Cancel removes the preview without a step of history. + + Each shape gets the current paint and goes on top of the current layer, or of the isolated group, as other new art + does; inside an isolated compound path it goes beside the compound path and does not join it. The new shapes are + selected, and one undo removes them all. An object with no outline (an empty group) gets no shape, and neither does + a shape with no size: the rectangle around a straight horizontal or vertical line, or the circle around a single + point, unless `offset` is more than 0. With `each`, the result's `skipped` counts those objects. It is an error, with + the document unchanged, when no shape is left to draw ("the shape would have no size" when a shape with no size was + left out, else "nothing to enclose"), when an edge of a shape (of a circle's bounding box) would lie more than + 4,000,000 pt from the origin along either axis ("the shape would reach past the edge of the canvas", for example + with a very large `offset`), and when `offset` is below 0. + → `{id: the first shape, ids, skipped?}` + + ```json + {"name":"run_command","arguments":{"command":"addon.pathtools.boundingCircle","params":{"offset":2}}} + ``` A parametric shape is an ordinary path. It keeps its numbers, with a fingerprint of the outline they drew, in one entry of its object data (`vc-pathtools-shape`, as `document.node` lists `attrs.data`), which SVG export leaves out; diff --git a/docs/roadmap.md b/docs/roadmap.md index 4e23db3070..8889ff1cbd 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -8,12 +8,16 @@ > > Vector Halftone preview update (2026-11-10): temporary dot selection marks are hidden, and the bounding box stays available (#6369). > +> **Text thread overlay update (2026-11-11):** repeated selection lookups share an index when needed (#6543); four focused output controls passed; scores and estimates unchanged. +> > **Eraser fill update (2026-11-11):** filled open paths without a visible painted stroke retain fill outside the sweep or Alt-drag marquee (#6582); stroked paths retain main behavior; scores and estimates unchanged. > > **Flyout update:** 2026-11-06 — resizable icon-strip flyouts and bottom-aligned panel footers (#5713); scores and estimates unchanged. > > Numeric spinner update (2026-11-10): held mouse arrows repeat past the click timeout; scores and estimates unchanged (#6307). +> Scissors snapping update (2026-11-11): with Alt released, hover and cuts use the Pen's path, alignment, intersection and anchor snaps (#6470). Scores and estimates unchanged. + > **PDF import status (2026-11-14, #6957):** Outlined Indic glyphs retain their full stroke properties; translucent glyphs stay separate, and a soft mask attaches to each glyph separately. Scores and estimates unchanged. > Blend redraw update (#5179): renderer bounds include spine-placed keys and steps; both focused CPU regressions pass. Scores and estimates unchanged. @@ -22,6 +26,10 @@ ## Feature submission evidence +Draft enhancement #5804: Preferences › File Handling can select a raster editor through the native picker, with a private draft outside engine preferences and generic dialog fields. OK saves it, Cancel discards it, and Reset restores PhotoCraft. With Use System Defaults off, a missing chosen editor falls back to PhotoCraft, then the system default; validation and launch failures are reported. Control/MCP and synthetic input cannot choose an application or run external Edit Original. Web behavior, parity scores and estimates are unchanged; macOS/Linux smoke tests remain pending. + +**2026-11-19 revision:** merged main while preserving the private raster-editor choice; no parity rescore. + M4: Explicitly requested editing data keeps a single artboard larger than its 14,400 pt capped PDF page (#6865). Scores and estimates unchanged. Numeric fields step on wheel hover without taking keyboard focus (#5949). Arrow keys still require focus; modifiers, units, limits, mixed values and existing rounding stay in the shared stepping path. Headless regressions in `tests/numfields.rs` cover hovered unfocused fields, focused fields, trackpad accumulation and panel scroll exclusion. Scores and estimates unchanged. @@ -147,7 +155,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule Selection, smart guides and snapping first. 60–90 h, parallel by tool. 2. **`.ai` files from real users** (G9): layer structure (#951). 10–20 h. 3. **Launch and stability** (G10): the Windows and Linux start-up reports. 20–35 h. -4. **Core-tool bugs** (G11): SVG units reverting to points (#864) and a Transform effect in a fill's or stroke's own effects (#885). Shape Builder regions (#937), Asset Export ghost borders (#983 / #1037) and the stalling bezier drag preview (#834) are fixed. 8–15 h. +4. **Core-tool bugs** (G11): SVG units reverting to points (#864; SVG export physical units fixed) and a Transform effect in a fill's or stroke's own effects (#885). Shape Builder regions (#937), Asset Export ghost borders (#983 / #1037) and the stalling bezier drag preview (#834) are fixed. 6–13 h. 5. **Then:** advanced type (G4) and the Illustrator 2026 additions (G13), then 3D (G3). The Effect Gallery's filter thumbnails and in-dialog preview are in (G2). ## Next @@ -166,17 +174,17 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule |---|---|---|---| | M0 | Skeleton + vertical slice | ✅ done | — | | M1 | Selection, transform, layers, MCP (common command tools, strict keys, session resources and version-aware result hints) | ✅ mostly done (path and compound-path interior selection follows enabled fill rows (#6625); a marquee leaves locked or hidden guide paths out inside groups, as clicks do (#8538); hidden-fill and no-fill stroke cap/join CPU regressions passed; document-tab artwork drag with lossless resource transfer and one target Undo; malformed MCP app replies discard the connection without replay, #1761; bounded control socket waits and connection-slot recovery, #1726; bounded synthetic control input, #1709; no-op anchor Align keeps Undo, Redo and saved state (#1180 follow-up); transform reference point snaps to anchors/centres; rotated objects keep a rotated bounding box and their angle; Free Transform, Scale and Reflect along a rotated box pending; the Transform fields take one Tab each, the W/H link after them) | 4–6 | -| M2 | Drawing tools + smart guides | ✅ mostly done (Eraser preserves fill outside fixed and varied tip sweeps and Alt-drag marquees on fill-only open paths and keeps their compound holes; clipping masks retain surviving contours or empty geometry in the same node; ordinary Group/Layer paints and evaluated gradient placements are preserved when the stored paint reproduces their appearance; hidden Rasterize and Along/Across stroke rows do not block visible gradients; replacement-art effects, plug-ins/Rasterize, along/across-stroke gradients and placements that cannot be reproduced keep their existing fitting; stroked open paths retain main behavior (#6582); #3380 deletion creates independent selected path pieces and keeps bounds-fitted gradients in place; endpoint highlighting remains open; Polygon/Star exact-size count persistence, with repeated-drag, tool-switch and Cancel regression coverage; Curvature point markers without direction handles (#1236, in part); Direct Selection segment click/Delete preserves neighboring edges, #1278; Flare, Reshape, Live Corners widget dragging and per-corner radii and kinds landed, on any path's corners; Shaper rough-shape recognition and orientation steps, the remaining Pen modifier nuances; Shaper Groups with editable sources and separate fill/stroke edits landed; custom ruler origin with drag preview, active-artboard reset, relative X/Y fields and native round-trip (#1212); construction widget/refinements pending); a shape just drawn moves by its centre point and turns from the zone outside a corner with its tool still active (#5477); Tangent and straight-segment perpendicular snapping use saved Smart Guides Geometric Guides preferences and Control bar quick access (#2537), including the existing Snap to Glyph and Alignment Guides toggles (#6164); no View submenu; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123) | 12–18 | +| M2 | Drawing tools + smart guides | ✅ mostly done (Eraser preserves fill outside fixed and varied tip sweeps and Alt-drag marquees on fill-only open paths and keeps their compound holes; clipping masks retain surviving contours or empty geometry in the same node; ordinary Group/Layer paints and evaluated gradient placements are preserved when the stored paint reproduces their appearance; hidden Rasterize and Along/Across stroke rows do not block visible gradients; replacement-art effects, plug-ins/Rasterize, along/across-stroke gradients and placements that cannot be reproduced keep their existing fitting; stroked open paths retain main behavior (#6582); #3380 deletion creates independent selected path pieces and keeps bounds-fitted gradients in place; endpoint highlighting remains open; Polygon/Star exact-size count persistence, with repeated-drag, tool-switch and Cancel regression coverage; Curvature point markers without direction handles (#1236, in part); Direct Selection segment click/Delete preserves neighboring edges, #1278; Flare, Reshape, Live Corners widget dragging and per-corner radii and kinds landed, on any path's corners; Shaper rough-shape recognition and orientation steps, the remaining Pen modifier nuances; Shaper Groups with editable sources and separate fill/stroke edits landed; custom ruler origin with drag preview, active-artboard reset, relative X/Y fields and native round-trip (#1212); construction widget/refinements pending); a shape just drawn moves by its centre point and turns from the zone outside a corner with its tool still active (#5477); Tangent and straight-segment perpendicular snapping use saved Smart Guides Geometric Guides preferences and Control bar quick access (#2537), including the existing Snap to Glyph and Alignment Guides toggles (#6164); no View submenu; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123); Scissors hover and cuts use the Pen's path/align/intersect/anchor snaps, with Alt Add Anchor and cut endpoint selection retained (#6470) | 12–18 | | M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Eyedropper copies transformed character dimensions (#6404) and styles highlighted text only (atomic transparency rejection); Eyedropper reads visible locked and outside-isolation sources (#1251); Color Picker, Color panel (its spectrum grows with a resized panel, #8005), Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416; native Lab entry and swatch libraries in the picker, Assign-row menus, #8031/#4028); gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; visible strokes when paint is added to inherited None/zero-width art (#1253); stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool (Shift-double-click enables adjoining adjustment in Width Point Edit; finite-arithmetic follow-up regressions and full CI passed ([Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area))), Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries; CSS library export preserves fractional linear and radial gradient stop positions. Left: freeform gradients in SVG/PDF, mixed spot/process gradients in SVG and PDF gradients mixing a spot color with RGB or Lab stops export as stops or process colors; PDF export writes dithered gradient fills with spot stops, and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, as images in process colors; confirm the Scale Strokes & Effects default; Recolor model selection is available through the engine and MCP only (#2520); the dialog retains its existing controls; Library panels' lists (swatch, Color Book, brush, symbol and graphic style libraries) fill a taller panel above its footer (#2992; scores and estimates unchanged); Graphic Styles list fills a taller panel above its footer (#2992; scores and estimates unchanged); Swatches list fills a taller panel above its footer (#1638; `the_list_fills_a_tall_panel_above_its_footer`; scores and estimates unchanged); | 4–8 | | M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths (#8128; estimates unchanged); Production Preflight checks fonts, overflow, links and image resolution with clickable findings and automatic rechecking (VectorCraft addition; estimates unchanged); PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300; estimates unchanged); PDF import: type filled and stroked by one text-showing operator comes in as one filled and stroked type object (#8015; not for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one, as the file composites them; estimates unchanged); PDF import: type filled and stroked by a `TJ` whose kerning starts a new line part way through comes in filled and stroked, a type object for each part, also where it draws a glyph again where it drew one, in an `ActualText` span too, where it stays one replacement type object on the first glyph's line and in its style; a `TJ` over more than 65 lines (the 64 its fill pass finished, kept back, and the open one) stays a filled object and a stroked one for each part (#8543; estimates unchanged); PDF import: stroked type keeps the file's line cap, line join and miter limit (#7741; estimates unchanged); Rename artboards in Export for Screens (#7275); Explicit editing-data import keeps oversized capped-page artboards (#6865; estimates unchanged); Save refusal continuation (#6146): ordinary Save offers Save As; unchanged format keeps options, changed format opens its Save options; cancellation/automation isolation; focused UI regressions passed, native acceptance pending; PDF authored ActualText preserved once in editable import (#6165; first-glyph line/style, bounded input; estimates unchanged); PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import preserves authored ActualText separately (#6165), with cross-line/style layout limits; separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. `.ai`/EPS type from the text document keeps its paragraphs' tab stops (#6147); `.ai`/EPS type from the text document keeps auto leading per line, its hyphenation options, and may show more of the last lines the file sets in an area frame of its own, when growing the frame by its lines' deepest descent plus 0.05 pt shows them (#6137); ✅ done (M4.14–M4.98 on 2026-10-05): Save As/Save a Copy/Revert/templates, Data Recovery and background save, SVG import and export fidelity (units, text, symbols, filters, SVGZ, Preserve Editing, SVG Options), shared guarded PDF writer and windowed reader ([pdf-backend.md](pdf-backend.md)), PDF import (colours, layers, masks, editable text, security) and export (presets, marks, bleed, ICC and output intent, raster effects, subset fonts, PDF/X-1a, X-3 and X-4, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3), Place and Links, Package, EPS and DXF in and out (EPS legacy mesh corners, vector opacity masks and raster page comparison verified; closed SPLINE flags round-trip and circular paths export as native CIRCLE/ARC, #1299), EMF/WMF, TIFF/BMP/Targa/PSD/GIF/PNG-8 export, Print and print presets, slices, Save for Web, TIFF in Export for Screens and Asset Export, clipboard flavours, File Info; AF.1–AF.4 add Affinity import (native layers, artboards, vectors, text and images from Affinity 1–3 files; the embedded preview only as a warned fallback; AF.4 expands current `.af` fixtures and every-board round-trip validation); EPS Save and Save As keep an opened EPS as EPS with its page frame and complete editable VectorCraft document (2026-10-26; G9 import fidelity unchanged). Left: DWG (use DXF), PSD placement as layers, overprint read back from PDF, Affinity export, polish; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke, adding no text (#6971; scores and estimates unchanged); | 3–6 (existing scope; Affinity export unestimated) | -| M5 | Performance | 🟡 background render + caches + MT done; `vectorcraft-cli bench` and `vectorcraft-cli perf` (budget suite); opaque solid-fill knockout paths draw once in hard-edge/supersampled raster export, with analytical-AA compositing unchanged; file format v2 opens 3× faster (50k paths: 722 → 244 ms); raster effects (glows, shadows, blur, feather) no longer force the whole frame single-threaded (filtered offscreen per effect, verified equal to the single-threaded reference); Craquelure/Mosaic Tiles/Stained Glass distance searches optimized with pixel-invariance checks and the `texture_drag_perf` probe (#1257); effect-heavy demos need a clean-machine benchmark; dirty-region rendering, GPU backend spike pending | 15–25 | +| M5 | Performance | 🟡 background render + caches + MT done; text thread overlays index repeated selection lookups, keeping the first lookup and singleton selections direct (#6543); `vectorcraft-cli bench` and `vectorcraft-cli perf` (budget suite); opaque solid-fill knockout paths draw once in hard-edge/supersampled raster export, with analytical-AA compositing unchanged; file format v2 opens 3× faster (50k paths: 722 → 244 ms); raster effects (glows, shadows, blur, feather) no longer force the whole frame single-threaded (filtered offscreen per effect, verified equal to the single-threaded reference); Craquelure/Mosaic Tiles/Stained Glass distance searches optimized with pixel-invariance checks and the `texture_drag_perf` probe (#1257); effect-heavy demos need a clean-machine benchmark; dirty-region rendering, GPU backend spike pending | 15–25 | | M6 | Path operations (Pathfinder, Shape Builder, offset…) | ✅ mostly done (live compound shapes: Make, Alt-click a Shape Mode, member modes, Release, Expand (#4522); single-result Pathfinder names and SVG IDs retained (#1293); Divide open-cutting-path geometry, appearance and history verified (#1307; existing segment cap remains); Simplify preview/counts and rewritten-path component selection verified (#1272; the slider opens at the Auto-Simplify level; a Direct Selection part of a path simplifies on its own); Compound appearance and member fill-rule edits verified (#1197); Boolean precision on almost-horizontal edges fixed and the property tests made deterministic; Shape Builder gap detection, large-offset bug open); Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog | 3–6 | | M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | Spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, the custom dictionary and Ignore All commands, Auto Spell Check with its right-click suggestions, Ignore All and Add to Dictionary, Spelling › Auto Spell Check in the context menu of type, the Edit Custom Dictionary dialog, and the modal Check Spelling dialog (Edit › Spelling › Check Spelling…, `Cmd+I`, `ui.checkSpelling`, #4936); 🟡 Retype phase 1: `type.retype` turns outlined text that exactly matches an available font back into point text (#4934); Right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops (#6147); A line a soft return ends is justified as a wrapped line is (#6137); Indian-language pattern hyphenation preserves syllables in both composers (#4947); 🟡 Hanging punctuation keeps its published amounts under Glyph Scaling, and Standard burasagari counts a hung line start as room; Fullwidth `!` / `?` keep an upright fallback in vertical type; Hyphenation… and Justification… per paragraph (#2310, #2755), Auto Leading also driving the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs (feature-valued alternates and unencoded glyphs applied in one Undo step while keeping Arabic joining, #5514), OpenType panel (including font-defined Stylistic Sets), Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas tatweels on the base letter's paint (`tests::harakat`); tab leaders, vertical type pending | 45–60 | | M8 | Transform & distort (Puppet Warp, Liquify tools, Envelopes, Blends, Perspective Grid) | ✅ done (M8.1–M8.20 on 2026-10-06, fidelity pass): Liquify Tool Options with one shared brush, pen pressure, hold-to-apply, a safe scope and incremental strokes; tool options that last; Puppet Warp rotation, multi-select, Control bar and a rest-shape session that follows Undo; Width tool on compound paths; Envelope dialogs with preview, Reset with Warp/Mesh, full Envelope Options, type/images/symbols/appearance/gradients/patterns distorted on canvas and in every export, warps that keep their frame, Edit Contents, mesh handles and Control bar; Blend Options, anchor-targeted Blend tool, editable spine, keys picked on the canvas, faithful interpolation and knockout; Anchor Point spine conversion/handle editing and selection priority (#2544), with #2425 Shift reshape preserved; Perspective Grid with Define Grid, presets, lock/snap/rulers, widgets, the 1–4 plane switch, movable planes, Perspective Selection scale/copy/perpendicular/Transform Again, and type and symbols truly projected with Edit Text. Left: Anti-Alias and Preserve Shape output, warp-envelope point editing, brush interpolation in blends, Free Transform/Scale/Reflect along a rotated box | 2–4 | | M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | Spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, the custom dictionary and Ignore All commands, Auto Spell Check with its right-click suggestions, Ignore All and Add to Dictionary, Spelling › Auto Spell Check in the context menu of type, the Edit Custom Dictionary dialog, and the modal Check Spelling dialog (Edit › Spelling › Check Spelling…, `Cmd+I`, `ui.checkSpelling`, #4936); Right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops (#6147); A line a soft return ends is justified as a wrapped line is (#6137); Indian-language pattern hyphenation preserves syllables in both composers (#4947); 🟡 Hanging punctuation keeps its published amounts under Glyph Scaling, and Standard burasagari counts a hung line start as room; Fullwidth `!` / `?` keep an upright fallback in vertical type; Hyphenation… and Justification… per paragraph (#2310, #2755), Auto Leading also driving the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs (feature-valued alternates and unencoded glyphs applied in one Undo step while keeping Arabic joining, #5514), OpenType panel (including font-defined Stylistic Sets), Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas tatweels on the base letter's paint (`tests::harakat`); tab leaders, vertical type pending | 45–60 | | M8 | Transform & distort (Puppet Warp, Liquify tools, Envelopes, Blends, Perspective Grid) | ✅ done (M8.1–M8.20 on 2026-10-06, fidelity pass): Liquify Tool Options with one shared brush, pen pressure, hold-to-apply, a safe scope and incremental strokes; tool options that last; Puppet Warp rotation, multi-select, Control bar and a rest-shape session that follows Undo; Width tool on compound paths; Envelope dialogs with preview, Reset with Warp/Mesh, full Envelope Options, type/images/symbols/appearance/gradients/patterns distorted on canvas and in every export, warps that keep their frame, Edit Contents, mesh handles and Control bar; Blend Options, anchor-targeted Blend tool, editable spine, keys picked on the canvas, faithful interpolation and knockout; Anchor Point spine conversion/handle editing and selection priority (#2544), with #2425 Shift reshape preserved; Perspective Grid with Define Grid, presets, lock/snap/rulers, widgets, the 1–4 plane switch, movable planes, Perspective Selection scale/copy/perpendicular/Transform Again, and type and symbols truly projected with Edit Text. Left: Anti-Alias and Preserve Shape output, warp-envelope point editing, brush interpolation in blends, Free Transform/Scale/Reflect along a rotated box; #5179 curved-spine redraw bounds include rotated keys and steps (two focused CPU regressions) | 2–4 | | M9 | Live effects (+ 3D & Materials) | 🟡 2D effects done incl. Effect → Pathfinder, Color Adjustments and Document Raster Effects Settings; PDF export warns when the pixel cap lowers raster-effect resolution; Artistic › Colored Pencil, Cutout, Dry Brush, Film Grain, Fresco, Neon Glow, Paint Daubs, Palette Knife, Poster Edges, Rough Pastels, Smudge Stick, Sponge, Underpainting and Watercolor and Sketch › Halftone Pattern, Bas Relief, Charcoal, Conté Crayon, Photocopy, Stamp, Torn Edges and Water Paper done (57/57 Photoshop filters); Revolve with automatic smooth vector shading, default-on circular caps and continuous rims, Extrude & Bevel, Inflate and Rotate with one to ten colored directional lights and four original lighting presets; SVG Filters, remaining raster effects and 3D materials and shadows pending | 81–130 | -| M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG `<pattern>`/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, six generated libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, Weather Icons), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, twelve generated libraries including Tech Circuit, Arrows, Pressure Sensitive, Ink and Wash, Bristle Brushes and Dry Media, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | +| M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG `<pattern>`/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, six generated libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, Weather Icons), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, thirteen generated libraries including Tech Circuit, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes and Dry Media, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | | M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View, middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | | M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color, 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 | @@ -254,8 +262,10 @@ not take the artwork yet. Overflow-menu drag remains separate. Scores and hours | 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 | M5/G15: text thread overlay membership indexing, focused output controls and matched component timings (#6543); scores and estimates unchanged. | | 2026-11-11 | minor | Eraser: fixed and varied tips and the Alt-drag marquee cut fill-only open contours and compound holes as areas; stroked open paths retain main behavior (#6582). Scores and 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-11 | minor | M2: Scissors hover and cuts share Pen-style path/align/intersect/anchor snapping (#6470); existing Alt and cut endpoint selection retained. 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 5393c089cf..638ec8fe8f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: #8128: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, so the compound clipping path clips its clipping group; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Twist: a strongly twisted path joins its pieces without kinks, #7069; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; Layers panel: Alt over the list shows the copy cursor while rows or the selection square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Properties panel: the Character section shows the font of the Type tool's selection, not the first run's (#8189); scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter, so a top object saved with its sides' curves in pieces draws as its `.ai` drawn art, #7097; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: #8128: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, so the compound clipping path clips its clipping group; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Twist: a strongly twisted path joins its pieces without kinks, #7069; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; Layers panel: Alt over the list shows the copy cursor while rows or the selection square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Properties panel: the Character section shows the font of the Type tool's selection, not the first run's (#8189); scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter, so a top object saved with its sides' curves in pieces draws as its `.ai` drawn art, #7097; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). > @@ -14,10 +14,14 @@ > > Vector Halftone preview update (2026-11-10): temporary dot selection marks are hidden, and the bounding box stays available (#6369). > +> **Text thread overlay update (2026-11-11):** repeated selection lookups share an index when needed (#6543); four focused output controls passed; scores and estimates unchanged. +> > **Eraser fill update (2026-11-11):** filled open paths without a visible painted stroke retain fill outside the sweep or Alt-drag marquee (#6582); stroked paths retain main behavior; scores and estimates unchanged. > > **Flyout update:** 2026-11-06 — resizable icon-strip flyouts and bottom-aligned panel footers (#5713); scores and estimates unchanged. +> Scissors snapping update (2026-11-11): with Alt released, hover and cuts use the Pen's path, alignment, intersection and anchor snaps (#6470). Scores and estimates unchanged. + > **PDF import status (2026-11-14, #6957):** Outlined Indic glyphs retain their full stroke properties; translucent glyphs stay separate, and a soft mask attaches to each glyph separately. Scores and estimates unchanged. > Blend redraw update (#5179): renderer bounds include spine-placed keys and steps; both focused CPU regressions pass. Scores and estimates unchanged. @@ -26,6 +30,8 @@ ## Feature submission evidence +SVG export preserves document units on the root `<svg width="..." height="...">` for documents with physical units (`mm`, `cm`, `in`, `pc`) per SVG 1.1 coordinates §7.10, preventing exported drawings from scaling to 75% in external tools like Inkscape and LightBurn (#864). Internal user coordinates in `viewBox` and path geometry remain in 1:1 points, and unitless documents (pixels, points) omit unit suffixes. Evidence: `crates/svg/tests/it/import_units.rs::export_physical_units_writes_unit_suffixes` (asserts physical unit suffixes `mm`, `in`, `cm`, `pc`, unitless points/pixels, responsive export omission, and small decimal precision) and `crates/engine/src/cmd/fileio/tests_svg.rs::svg_round_trip_preserves_document_units` (verifies full round trip through engine commands `file.new` -> `document.setUnits` -> `document.serialize` -> `document.open`). G11 estimate 8–15 → 6–13 h; parity scores unchanged. + `window.panel.float` updates an existing native panel window's supplied position and size (#8391). Positions use the main window's content origin. Omitted coordinates and dimensions keep their current native values, including after an OS window move or resize. Evidence: `panel_docking::native_tests::an_explicit_float_command_updates_an_existing_native_windows_geometry` covers panel, group and column commands. Scores and estimates are unchanged. EPS embedded fonts, 2026-11-09 (#6023–#6067): the fonts an EPS carries draw their glyphs instead of being set as type in an installed font: composite (Type 0) fonts with the 8/8 mapping, plain Type 42 fonts (characters from their glyph names or character map, widths from the font), CID-keyed fonts over CMaps (Type 0 and Type 2 CIDFonts, CIDFonts in a FontSet's Compact Font Format data, base-font CMaps, named CIDFonts over predefined Unicode CMaps set as type) and embedded Type 1 fonts; the show operators' spacing along the baseline is kept as tracking, `kshow` included. Each step is charged to the interpreter's budgets. Hand-written test files only (no corpus file uses these fonts); scores and estimates unchanged. Evidence: `crates/eps/src/import/tests_composite.rs`, `tests_type42.rs`, `tests_cid.rs`, `tests_type1.rs`; details in [file-format-parity.md](file-format-parity.md). @@ -69,6 +75,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-18 | minor | G11: SVG export writes physical unit suffixes on the root <svg width="..." height="..."> for documents with physical units (mm, cm, in, pc), preventing drawings from scaling to 75% in external tools and preserving units across round-trips (#864; general unit preference on restart remains open under #864). Tests: export_physical_units_writes_unit_suffixes (crates/svg/tests/it/import_units.rs) and svg_round_trip_preserves_document_units (crates/engine/src/cmd/fileio/tests_svg.rs). G11 estimate 8–15 → 6–13 h. | | 2026-11-18 | minor | PDF import (#8543): type filled and stroked (text rendering modes 2 and 6) by a `TJ` whose kerning starts a new line part way through came in as four type objects, each part filled only and each part stroked only over it: the reader fills every glyph of the operator before it strokes them, and the line the first part was gathered on was finished before the stroke pass came back to it. Lines an operator's fill pass finishes while a stroke may still be drawn over them are now kept (up to 64 besides the open line, so a `TJ` over up to 65 lines: one over more stays a filled object and a stroked one for each part, as before) until the stroke pass goes past them, and the pass's strokes are held (up to 4096: a longer pass is matched a part at a time, each part to glyphs filled one right after another, never to one an operator before it filled) until it ends, then matched to the glyphs filled last, in the order they were filled, so each stroke finds the glyph it was filled as, also where the `TJ` draws a glyph again where it drew one (`[(A) -3500 (B) 4834 (A)] TJ`). Each part comes in as one type object filled and stroked, in the order drawn; also a `TJ` that jumps back and one whose kerning starts two new lines. In an `ActualText` span (whose stroke was lost) the replacement text stays one type object on the first glyph's line and in its style, now filled and stroked, also where the `TJ` draws a glyph again: the span's strokes are matched the same way. A stroke over no filled glyph (stroked type of its own) and the start and end of an `ActualText` span end a stroke pass: no stroke after them goes over a glyph filled before them, so none is drawn under type drawn after it, and a later span keeps its own replacement text. Stroke rendering stays stroke only, and translucent type stays a filled object and a stroked one. Tests: `a_tj_whose_kerning_starts_a_new_line_is_filled_and_stroked`, `a_tj_that_draws_a_glyph_again_where_it_drew_one_strokes_each_copy`, `a_stroked_tj_whose_kerning_starts_a_new_line_stays_stroke_only`, `a_translucent_tj_whose_kerning_starts_a_new_line_stays_fill_and_stroke_apart`, `a_long_stroke_pass_strokes_its_own_glyphs_not_one_filled_before`, `a_stroke_after_stroked_type_of_its_own_does_not_join_a_glyph_filled_before`, `a_stroke_in_an_actual_text_span_does_not_take_an_earlier_spans_glyph`, `a_tj_that_draws_a_glyph_again_in_an_actual_text_span_strokes_the_replacement`, `a_tj_over_more_lines_than_are_kept_comes_in_as_fill_and_stroke_apart`, `a_tj_over_more_lines_than_are_kept_that_ends_where_it_began_stays_fill_and_stroke_apart`, `type_after_a_tj_over_more_lines_than_are_kept_is_filled_and_stroked`; scores and estimates unchanged. | | 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. | @@ -264,12 +271,12 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Area | Weight | Done | Main gaps | One agent (h) | Kind | |---|---:|---:|---|---:|---| | Selection, transform & align tools | 6 | 85% | Direct Selection segment click/Delete corrected (#1278); deletion splits an ordinary contour into selected sibling objects with bounds-fitted gradients kept in place (#3380, deletion only; `crates/engine/tests/it/delete_path_pieces.rs`); open-path anchor Delete keeps gaps; Select › Start Global Edit finds the paths, compound paths and symbol instances of the selected object's shape (Appearance, Size and artboard options) and gives an edit of one to all of them in proportion, as one undo step (#3521), and on a group the groups like it, an edit inside one reaching the same object in the others (#4939), and a Shift-click on a highlighted match leaves it out; the Align panel menu's Align to Glyph Bounds › Point Text and Area Text measure type by its glyphs' ink for Align and Distribute (#4231); remaining: Free Transform/Scale/Reflect along a rotated box, Global Edit of rotated copies, transform nuances (no-op anchor Align history regression-tested, #1180 follow-up) | 4–6 | estimated; fill-stack selection regression-tested (`crates/engine/tests/path_fill_hits.rs`, #6625); cap/join follow-up CPU regressions passed; Global Edit regression-tested (`crates/engine/src/tests/globaledit.rs`; Quick Action, menu label and Escape in `panels::properties::tests::start_global_edit_quick_action_and_escape`) | -| Drawing tools (Pen, Curvature, Pencil, shapes, Shaper) | 7 | 85% | Shaper construction widget, Pencil/Pen nuances, Blob Brush options, Touch Type, Dimension tool; see [ui-parity.md](ui-parity.md) | 8–13 | estimated; Curvature point display regression-tested (#1236, in part); Polygon/Star exact-size count persistence regression-covered; Live Corners' Relative rounding done (#3091), score unchanged; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123), score and hours unchanged; the Pen, Smart Pen and Curvature tool show the measurement readout with the rubber band off (#7043), score, gaps and hours unchanged; Eraser preserves fill-only open-path area outside fixed and varied tip sweeps and Alt-drag marquees, including compound holes; clipping masks keep their remaining contours and empty-mask role; ordinary Group/Layer paints and evaluated gradient placements are preserved when the stored paint reproduces their appearance; replacement-art effects, plug-ins/Rasterize, along/across-stroke gradients and placements that cannot be reproduced keep their existing fitting; stroked open paths retain main behavior and result structure (#6582; `crates/engine/tests/eraser_open_fill.rs`), score and hours unchanged | +| Drawing tools (Pen, Curvature, Pencil, shapes, Shaper) | 7 | 85% | Shaper construction widget, Pencil/Pen nuances, Blob Brush options, Touch Type, Dimension tool; see [ui-parity.md](ui-parity.md) | 8–13 | estimated; Curvature point display regression-tested (#1236, in part); Polygon/Star exact-size count persistence regression-covered; Live Corners' Relative rounding done (#3091), score unchanged; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123), score and hours unchanged; the Pen, Smart Pen and Curvature tool show the measurement readout with the rubber band off (#7043), score, gaps and hours unchanged; Scissors shares the Pen's path/align/intersect/anchor snaps (#6470), source and headless regressions below; Eraser preserves fill-only open-path area outside fixed and varied tip sweeps and Alt-drag marquees, including compound holes; clipping masks keep their remaining contours and empty-mask role; ordinary Group/Layer paints and evaluated gradient placements are preserved when the stored paint reproduces their appearance; replacement-art effects, plug-ins/Rasterize, along/across-stroke gradients and placements that cannot be reproduced keep their existing fitting; stroked open paths retain main behavior and result structure (#6582; `crates/engine/tests/eraser_open_fill.rs`), score and hours unchanged | | Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 80% | Shape Builder on the reporter's file (#937: art past 4,096 segments is cut by lines again; unconfirmed on the file itself); gap detection shares Live Paint’s finder, with a 72 pt custom cap and the existing options; Live Paint Gap Options | 4–8 | estimated; Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog (lowered from 86%: open issues); compound attributes regression-tested (#1197); single-result source names survive SVG export/import (#1293), with [SVG ID semantics](https://www.w3.org/TR/SVG2/struct.html#IDAttribute) and original-shape tests; Simplify component selection and preview regression-tested (#1272); Simplify of a Direct Selection part of a path regression-tested (`tests/simplify_part.rs`); Divide open-cutting-path geometry and appearance regression-tested (#1307); the Shape Builder's edge-source grid is bounded in memory and files a segment once per cell (`planar.rs` test `rect_index_holds_a_bounded_number_of_references`); live compound shapes (Make, Alt-click, member Shape Modes, Release, Expand, saved and exported) regression-tested (#4522); Live Paint Bucket face drags, including narrow faces and one Undo, regression-tested (#6373) | | Colour, swatches, gradients, patterns, mesh, recolor | 7 | 92% | Picker Lab entry, picker libraries and Assign-row menus complete the deferred #4028 UI paths (#8031); scores and estimates unchanged; Eyedropper copies effective character dimensions across text transforms (#6404); 30.0's gradient additions are done (dither, perceptual blending, presets); freeform gradients in SVG/PDF, mixed spot/process gradients in SVG, PDF gradients mixing a spot color with RGB or Lab stops, and dithered spot gradient fills and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, which PDF export writes as images in process colors| 4–7 | estimated; Recolor model selection is available through the engine and MCP (#2520), and the dialog's color sliders (HSB, RGB, CMYK, Lab, Tint for a spot color) edit the selected row's new color in its mode, and the Edit tab's Global Adjust sliders (Saturation, Brightness, Temperature, Luminosity, -100% to 100%) change every recolored color at once (lowered from 96%: target moved); unpainted zero-width stroke restoration fixed (#1253), score and hours unchanged; Eyedropper source reads regression-tested (#1251); screen-bounded Recolor Edit chip list (#3416), score and hours unchanged; a point on a gradient mesh's outline locates on its edge on every side (#7006: `mesh_locate_takes_a_point_on_any_side_of_the_outline`, `mesh_add_line_exactly_on_the_edge_needs_no_tolerance`), score and hours unchanged; Color panel spectrum grows with the resized panel (#8005) | -| Strokes, brushes, width profiles | 5 | 88% | Shift-double-click adjoining adjustment is implemented; brush libraries are done (twelve generated libraries including Tech Circuit, Arrows, Pressure Sensitive, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media, User Defined, Other Library…, Save Brushes); Art brush Overlap and Pattern brush auto corners are done; remaining: pen pressure on macOS, Stylus Wheel, more built-in brush libraries, tilt, bearing and rotation for Art, Pattern and Bristle brushes and on native Wayland and the web | 8–15 | estimated; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed; evidence below; finite-arithmetic follow-up regressions and full CI passed (evidence below) | +| Strokes, brushes, width profiles | 5 | 88% | Shift-double-click adjoining adjustment is implemented; brush libraries are done (thirteen generated libraries including Tech Circuit, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media, User Defined, Other Library…, Save Brushes); Art brush Overlap and Pattern brush auto corners are done; remaining: pen pressure on macOS, Stylus Wheel, more built-in brush libraries, tilt, bearing and rotation for Art, Pattern and Bristle brushes and on native Wayland and the web | 8–15 | estimated; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed; evidence below; finite-arithmetic follow-up regressions and full CI passed (evidence below) | | Appearance, transparency, graphic styles, masks | 5 | 97% | raster effect reach in preview bounds | 1–2 | estimated; Transform typing, sliders, preview, and undo are covered in `crates/ui-egui/src/panels/tests_appearance.rs` | -| 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, painter visibility); materials, light presets, shadows, ray tracing, the rest of 3D Classic (Map Art), Turntable views, textures, map art and shading in 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12); every 3D seam has round joins (2026-11-12, [three-d.md](three-d.md#seams)), score, gaps and hours unchanged | +| 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, painter visibility); materials, light presets, shadows, ray tracing, Turntable views, textures, map art and shading in 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12); Map Art on Extrude & Bevel (Classic) and Revolve (Classic) is covered by `crates/effects/src/solids/tests_map_art.rs` and `crates/engine/src/cmd/effectcmd/map_art_tests.rs` (score and hours unchanged); every 3D seam has round joins (2026-11-12, [three-d.md](three-d.md#seams)), score, gaps and hours unchanged | | Type core | 9 | 80% | Auto-leading style resets are implemented; Hyphenation… and Justification… options are done (#2310, #2755), and a paragraph's Auto Leading also sets the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; remaining: Optical Margin Alignment, Middle Eastern features beyond bidi layout (the Middle Eastern & South Asian and Standard composers are done per paragraph, #4935; `.ai`/EPS/PDF files carry no composer), optional group font-size preservation; transformed character controls fixed (#1034), see [type-parity.md](type-parity.md) | 14–19 | estimated; eleven-language pattern hyphenation in both composers, with grapheme and shaping-cluster protection (#4947, `hyphen::tests` and `layout::wrapping_tests`); Sanskrit patterns pending an allowlisted source; recent-font groups in font pickers (#3515); full-name font matches regression-tested (#1258); mixed paragraph alignment indication implemented; headless regressions, full integration CI and visual review pass; localized legacy family-name fallback with loaded/catalog regressions (#2208); Fractional Widths per type object regression-tested; color emoji fonts with bitmap glyphs (`sbix`, `CBDT`) draw and export; threading ports: every selected area type and type on a path shows its in and out ports (empty, arrow, red "+"), and the Selection tool threads from either, the in port into a frame before it, and a double-click on a threaded port breaks the thread there (`threads::tests::break_splits_the_thread_and_the_story_flows_into_the_first_part`, `select::tests::a_double_click_on_a_threaded_port_breaks_the_thread`, `canvas::tests::a_double_click_on_a_threaded_out_port_breaks_the_thread`) (#2572; `select::tests::a_click_on_the_in_port_threads_into_a_frame_before_it`, `text::tests::selected_type_shows_its_ports_in_each_state`, `threads::tests::add_before_threads_the_story_from_the_new_frame_into_the_clicked_one`, live screenshot); the Glyphs panel highlights and scrolls to the character selected with the Type tool (#4908, `panels::glyphs` tests); the OpenType panel lists only `ss01`–`ss20` sets present in the selected font and uses its custom names when supplied; Type-range desktop Copy publishes styled art and keeps font family, size and color on canvas Paste after editing (#5636); paint-only Arabic harakat keep joining with conditional GDEF-mark ownership and Insert Kashidas base-letter paint (`tests::harakat`) | | Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (ruby, mojikumi), variable font axes, tab leaders, Touch Type, Retype beyond exact matches of available fonts | 20–28 | estimated; Retype phase 1 (`type.retype`, exact glyph matches, #4934); upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | | Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons and Weather Icons are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) are done | 4–7 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested | @@ -280,13 +287,13 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons and Weather Icons are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) are done | 4–7 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested | | Image Trace, graphs, image tools | 3 | 75% | graph Column designs, Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; simpler contour walk, 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, so Paths is monotone on the code-drawn sweep) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them; Live trace result bounds and selection highlights exclude the retained bitmap except in source-image views (scores/hours unchanged); Create Object Mosaic's dialog with New Size, Constrain Ratio, Resize Using Percentages and Use Ratio is covered by `dialogs::object_mosaic::tests` (score, gaps and hours unchanged); High Fidelity Photo traces in Full Tone with abutting shapes, summed mean pixel difference over 19 test images 80.5 to 65.6 levels ([quality notes](image-trace-quality.md#high-fidelity-photo-in-full-tone)), score, gaps and hours unchanged | | Live vector effects | 5 | 85% | Outline Object, SVG Filters | 4–8 | measured count 49/50 (Pathfinder 13/13 with Trap), depth estimated; Warp Options controls verified by focused checks and original-image review | -| 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, original lighting presets, painter visibility), Revolve (Classic) with Angle, Cap, Offset and the Plastic, Diffuse, No Shading and Wireframe surfaces, the Quick Actions › Expand as Wireframes command (#6354), the Render Settings › Wireframe mode on Extrude & Bevel, Revolve, Inflate and Rotate; materials, shadows, ray tracing, the rest of 3D Classic (Map Art), Turntable views, textures, map art and shading in 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12); Revolve (Classic) is covered by the `revolve::classic` tests and `dialogs::revolve::tests::classic_revolve_shows_its_options_and_applies_as_one_step`; Expand as Wireframes is covered by `crates/effects/src/solids/wireframe/tests.rs` and `crates/engine/src/cmd/wireframe/tests.rs`, and Render Settings › Wireframe by `crates/effects/src/solids/wireframe/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` (score, gaps and hours unchanged); every 3D seam has round joins (2026-11-12, [three-d.md](three-d.md#seams)), score, gaps and hours unchanged | +| 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, original lighting presets, painter visibility), Revolve (Classic) with Angle, Cap, Offset and the Plastic, Diffuse, No Shading and Wireframe surfaces, the Quick Actions › Expand as Wireframes command (#6354), the Render Settings › Wireframe mode on Extrude & Bevel, Revolve, Inflate and Rotate; materials, shadows, ray tracing, Turntable views, textures, map art and shading in 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12); Map Art on Extrude & Bevel (Classic) and Revolve (Classic) is covered by `crates/effects/src/solids/tests_map_art.rs` and `crates/engine/src/cmd/effectcmd/map_art_tests.rs` (score and hours unchanged); Revolve (Classic) is covered by the `revolve::classic` tests and `dialogs::revolve::tests::classic_revolve_shows_its_options_and_applies_as_one_step`; Expand as Wireframes is covered by `crates/effects/src/solids/wireframe/tests.rs` and `crates/engine/src/cmd/wireframe/tests.rs`, and Render Settings › Wireframe by `crates/effects/src/solids/wireframe/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` (score, gaps and hours unchanged); every 3D seam has round joins (2026-11-12, [three-d.md](three-d.md#seams)), score, gaps and hours unchanged | | Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (mojikumi), variable font axes, tab leaders, Touch Type, Retype beyond exact matches of available fonts | 20–28 | estimated; Retype phase 1 (`type.retype`, exact glyph matches, #4934); No Break keeps marked characters on one line; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | | Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (mojikumi), tab leaders, Touch Type, Retype beyond exact matches of available fonts | 20–28 | estimated; Retype phase 1 (`type.retype`, exact glyph matches, #4934); No Break keeps marked characters on one line; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | | Raster effects (Effect Gallery) | 4 | 55% | — | — | estimated (raised from 52%: the Effect Gallery's filter thumbnails and in-dialog preview, an original landscape drawing passed through each filter, [Filter Gallery overview](https://helpx.adobe.com/photoshop/desktop/effects-filters/get-started-with-filters/filter-gallery.html), `dialogs::effect_gallery::tests::gallery_shows_thumbnails_and_an_in_dialog_preview`; the gallery itself shipped in #2883, six categories, per-filter settings, ordered stack, live canvas preview, one undo step, `stack_ok_is_one_undo_step`, `stack_preview_is_one_interaction`); measured count 57/57 (Artistic complete with Colored Pencil, Fresco, Paint Daubs, Palette Knife, Rough Pastels and Underpainting; Sketch complete with Torn Edges and Conté Crayon, `pixel::tests_sketch::conte_crayon_*`); texture redraw distances optimized (#1257), pixels verified; the score stays under 100% because the filters are original approximations; depth estimated | | Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons and Weather Icons are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) and on-canvas 9-slice guides (#5280) are done | 4–7 | estimated | | Image Trace, graphs, image tools | 3 | 75% | graph Column designs, Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; large images trace with a warning; Auto Color keeps rare distinct colours) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them | -| Layers, artboards, document setup | 5 | 78% | Selected-artboard deletion is consistent across panel actions (all-selected retains artboard 1); history prunes removed indices while preserving valid multiselection; remaining: 30.0's artboard locking and colours and managing artboards from the canvas, Layers row menu commands beyond Collect for Export and menus on guide and blend spine rows (click-to-fit objects is done, #1227) | 5–8 | estimated (lowered from 82%: target moved); Artboard deletion keys keep artwork and the first of an all-selected set; Artboard Options' Show Center Mark and Show Cross Hairs draw on the canvas only (exports and print leave them out), regression-tested; Artboard Options' Show Video Safe Areas and Video Ruler Pixel Aspect Ratio (per artboard, native format) are done ([video display options](#evidence-what-ships-today-by-area)), score unchanged | +| Layers, artboards, document setup | 5 | 78% | Selected-artboard deletion is consistent across panel actions (all-selected retains artboard 1); history prunes removed indices while preserving valid multiselection; remaining: 30.0's artboard locking and colours and managing artboards from the canvas, Layers row menu commands beyond Collect for Export and menus on blend spine rows (guide row menus are done; click-to-fit objects is done, #1227) | 5–8 | estimated (lowered from 82%: target moved); Artboard deletion keys keep artwork and the first of an all-selected set; Artboard Options' Show Center Mark and Show Cross Hairs draw on the canvas only (exports and print leave them out), regression-tested; Artboard Options' Show Video Safe Areas and Video Ruler Pixel Aspect Ratio (per artboard, native format) are done ([video display options](#evidence-what-ships-today-by-area)), score unchanged | | View & navigation | 3 | 70% | multiple windows and the rest of Arrange (Cascade, Float in Window, Float All in Windows) | 9–14 | estimated; Window › Arrange › Tile and Consolidate All Windows done (score/hours unchanged); document-tab artwork hover/copy and lossless transfer tested (2026-10-22; score/hours unchanged); cached canvas reprojection preserves scale during resize, rotation and DPI changes (regression and contributor original-file evidence below; scores/hours unchanged); cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission (regression evidence below) | | File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), a saved `.ai`'s editing copy without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects other than grouped column, stacked column, line and area graphs the `.ai` reader reads back whole as their art (#868), FreeHand/CorelDRAW/DWG/HEIC import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.; PDF type filled and stroked at less than full opacity comes in as a filled object and a stroked one (#8015) | 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); DXF export's Include Placed Images and Include Fill Hatches options, off in CNC / CAM (`images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_both`; score, gaps and hours unchanged); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`; the distance from the path under Align to Path is measured from the top of each character's em box, half the height of the top of its H or the bottom of its font's bounding box (`tests_native::aligned_type_lies_as_far_from_its_path_as_the_file_lays_it_out`), and the fit under Gravity does not reproduce the file's layout), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. PDF import: stroked type (text rendering modes 1, 2, 5 and 6) keeps the file's line cap, line join and miter limit, as paths do (#7741, `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`); score, gaps and hours unchanged. `.ai` and EPS import: clipping paths grouped in a compound path are the compound path's subpaths, so the compound clipping path clips its clipping group instead of coming in as nested clipping groups (#8128, `clipping_paths_grouped_in_a_compound_path_are_its_subpaths` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. PDF import: type filled and stroked by one text-showing operator (rendering modes 2 and 6) comes in as one type object, filled and stroked, not a stroked copy over a filled one (#8015, `a_word_filled_then_stroked_imports_as_one_filled_and_stroked_type` in `crates/pdf/src/tests/textstroke.rs`); not for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one (`translucent_fill_and_stroke_text_stays_two_objects`); score and hours unchanged. PDF import: type filled and stroked by a `TJ` whose kerning starts a new line part way through comes in filled and stroked, a type object for each part, also where it draws a glyph again where it drew one, in an `ActualText` span too, where it stays one replacement type object on the first glyph's line and in its style; a `TJ` over more than 65 lines (the 64 its fill pass finished, kept back, and the open one) stays a filled object and a stroked one for each part (#8543, `a_tj_whose_kerning_starts_a_new_line_is_filled_and_stroked`); score and hours unchanged. PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300, `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked` in `crates/pdf/src/tests/textstroke.rs`); score and hours unchanged. | | File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), a saved `.ai`'s editing copy without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects other than grouped column, stacked column, line and area graphs the `.ai` reader reads back whole as their art (#868), FreeHand/CorelDRAW/DWG/HEIC import, textures, map art and shading in 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.; PDF type filled and stroked at less than full opacity comes in as a filled object and a stroked one (#8015) | 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. Graphs saved to `.ai` in either form open again as live graphs (`ai_editing::tests::graphs_are_written_with_their_records_and_open_live`, `legacy_ai::tests::graphs_are_written_with_their_records_and_open_live`, `cmd::graph::tests::a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns`); other graphs are still written as their art (`graphs_the_records_cant_keep_are_written_as_their_art`); score and hours unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. PDF import: stroked type (text rendering modes 1, 2, 5 and 6) keeps the file's line cap, line join and miter limit, as paths do (#7741, `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`); score, gaps and hours unchanged. `.ai` and EPS import: clipping paths grouped in a compound path are the compound path's subpaths, so the compound clipping path clips its clipping group instead of coming in as nested clipping groups (#8128, `clipping_paths_grouped_in_a_compound_path_are_its_subpaths` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. PDF import: type filled and stroked by one text-showing operator (rendering modes 2 and 6) comes in as one type object, filled and stroked, not a stroked copy over a filled one (#8015, `a_word_filled_then_stroked_imports_as_one_filled_and_stroked_type` in `crates/pdf/src/tests/textstroke.rs`); not for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one (`translucent_fill_and_stroke_text_stays_two_objects`); score and hours unchanged. PDF import: type filled and stroked by a `TJ` whose kerning starts a new line part way through comes in filled and stroked, a type object for each part, also where it draws a glyph again where it drew one, in an `ActualText` span too, where it stays one replacement type object on the first glyph's line and in its style; a `TJ` over more than 65 lines (the 64 its fill pass finished, kept back, and the open one) stays a filled object and a stroked one for each part (#8543, `a_tj_whose_kerning_starts_a_new_line_is_filled_and_stroked`); score and hours unchanged. PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300, `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked` in `crates/pdf/src/tests/textstroke.rs`); score and hours unchanged. | @@ -297,8 +304,8 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Export for Screens, Asset Export, slices, Save for Web | 3 | 85% | anti-aliasing ghost borders (#983); TIFF choices and settings are implemented | 2–4 | estimated | | Print, colour management, separations, flattener | 3 | 80% | Production Preflight available; print preview fidelity remains | 2–4 | estimated | | Automation (Actions, Variables, scripting, batch) | 3 | 60% | a scripting surface (Illustrator: JavaScript/ExtendScript), Batch, image and graph variables, dataset import/export | 8–14 | estimated; MCP `add_text` exposes existing vertical type; score and hours unchanged | -| UI chrome (panels, Properties, workspaces, preferences) | 6 | 80% | Properties per context, 2 Preferences options stored but unused (#394, audited 2026-10-30: Scratch Disks, legacy vector clipboard), context menus in the panels that have none, accessibility | 13–20 | estimated; floating panels in OS windows of their own on the desktop (#4135), score and hours unchanged; macOS save Format menu implemented (#866), score and hours unchanged; Eyedropper cursor and precise setting checked (#1269), OS visual QA unverified; the line under the Preferences fields describes each General, Selection & Anchor Display, Guides & Grid, Smart Guides, Slices and Hyphenation setting on hover and keyboard focus (#8199, #8223, #8248, #8264, #8360), score and hours unchanged; numeric-field focus and normal text drags regression-tested (#1326); a focus click released more than 1 pt from its press keeps the caret and a tap within 1 pt selects all (#6659); artboard navigation synchronizes the tool selection before destructive actions; status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates (sample widths cached by language/unit/DPI; regression and contributor original-file evidence below; scores/hours unchanged); effect dialogs' colour fields show a swatch that opens the Color Picker (#5365), score and hours unchanged; icon-strip flyouts retain user sizes (#5713); floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), scores and hours unchanged ; interim macOS cursor delivery (#2292), headless coverage only; native validation pending, score and hours unchanged; Swatches item context menus have focused regressions and rendered-layout evidence below; scores and estimates unchanged | -| Libraries, Links, Package | 2 | 82% | shared libraries, linked graphics, gradients and patterns as library items (no cloud by design) | 2–3 | estimated | +| UI chrome (panels, Properties, workspaces, preferences) | 6 | 80% | Properties per context, 2 Preferences options stored but unused (#394, audited 2026-10-30: Scratch Disks, legacy vector clipboard), context menus in the panels that have none, accessibility | 13–20 | estimated; floating panels in OS windows of their own on the desktop (#4135), score and hours unchanged; macOS save Format menu implemented (#866), score and hours unchanged; Eyedropper cursor and precise setting checked (#1269), OS visual QA unverified; the line under the Preferences fields describes each General, Selection & Anchor Display, Guides & Grid, Smart Guides and Slices setting on hover and keyboard focus (#8199, #8223, #8248, #8264, #8360), score and hours unchanged; numeric-field focus and normal text drags regression-tested (#1326); a focus click released more than 1 pt from its press keeps the caret and a tap within 1 pt selects all (#6659); artboard navigation synchronizes the tool selection before destructive actions; status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates (sample widths cached by language/unit/DPI; regression and contributor original-file evidence below; scores/hours unchanged); effect dialogs' colour fields show a swatch that opens the Color Picker (#5365), score and hours unchanged; icon-strip flyouts retain user sizes (#5713); floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), scores and hours unchanged ; interim macOS cursor delivery (#2292), headless coverage only; native validation pending, score and hours unchanged; Swatches item context menus have focused regressions and rendered-layout evidence below; scores and estimates unchanged | +| Libraries, Links, Package | 2 | 82% | shared libraries, linked graphics, gradients and patterns as library items (no cloud by design) | 2–3 | estimated; #5804: private native-picked raster editor (scores unchanged) | | Generative AI (Text to Vector, Generative Recolor, Shape Fill, Concept to Vector, Prompt to Edit, Rewrite Text) | 2 | 0% | a pluggable provider and the panels; needs an owner decision on models | 30–60 | measured (absent) | | **Feature depth** | **105** | **~75%** | | **~250–420** | | | Interaction-fidelity pass (every tool's modifiers, cursors, Properties per context) | | | [ui-parity.md](ui-parity.md) | 60–90 | estimated | @@ -453,7 +460,7 @@ what keeps it from beta, not from alpha. | File formats | 75% | 15–30 | estimated | [file-format-parity.md](file-format-parity.md) | | Hardware (GPU, pen, touch, displays) | 35% | 25–45 | estimated | [hardware-parity.md](hardware-parity.md) | | Localization (the 12 key languages, equally weighted) | 74% | 50–85 | measured from catalogs | [localization-parity.md](localization-parity.md) | -| Performance | ~60% | 15–25 | estimated (unverified budgets; measured long-path hits and large-selection nudges) | [gaps.md](gaps.md) | +| Performance | ~60% | 15–25 | estimated (unverified budgets; measured long-path hits, large-selection nudges and text thread filtering) | [gaps.md](gaps.md) | | Stability | ~60% | 30–50 | estimated | [gaps.md](gaps.md) | | Platforms (macOS, Windows x64/arm64, Linux, FreeBSD, web) | 80% | 15–25 | estimated | [gaps.md](gaps.md) | | Ecosystem and plug-ins (scripting, third-party plug-ins) | 15% | 30–60 | estimated | [gaps.md](gaps.md) | @@ -539,7 +546,7 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale) | Drawing tools | 7 | 86% | Eraser preserves fill when cutting fill-only open paths with fixed or varied tips or Alt-drag marquees; painted-stroke paths retain main behavior and clipping masks keep their remaining contours or empty geometry, with reproducible evaluated gradient placement preserved on ordinary paths, compounds, groups and layers (#6582); replacement-art effects, plug-ins/Rasterize, along/across strokes and placements that cannot be reproduced retain fitting; rough-square Shaper recognition and orientation steps corrected; editable Shaper Groups landed; Pencil: Alt key toggles to Smooth Tool (#2001); remaining: Shaper construction widget/gesture refinements, pencil and the remaining pen modifier nuances, Blob Brush Merge Only with Selection, Touch Type, Live Corners' Relative rounding | 7–12 | | Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 86% | Live Paint gap options, Shape Builder gap detection, options (Tool Options dialog, clicking a stroke in merge mode) and Shift-drag marquee | 3–6 | | Colour, swatches, gradients, patterns, mesh, recolor | 7 | 96% | Picker Lab entry, picker libraries and Assign-row menus complete the deferred #4028 UI paths (#8031); scores and estimates unchanged; Library panels' lists (swatch, Color Book, brush, symbol and graphic style libraries) fill a taller panel above its footer (#2992; scores and estimates unchanged); Swatches list fills a taller panel above its footer (#1638; `the_list_fills_a_tall_panel_above_its_footer`; scores and estimates unchanged); freeform gradients in SVG/PDF and mixed spot/process gradients in SVG (exported as stops; PDF export keeps the spot inks in a DeviceN shading, except next to RGB or Lab stops; dithered fills and Perceptual gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve are written as images in process colors), pattern fills in Expand | 2–4; Eyedropper source reads regression-tested (#1251) | -| Strokes, brushes, width profiles | 5 | 90% | more built-in brush libraries (twelve generated in code including Tech Circuit, Arrows, Pressure Sensitive, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media are done; Art brush Overlap and Pattern brush auto corners are done), pen pressure on macOS (the windowing layer reports none there), Stylus Wheel, tilt, bearing and rotation for Art, Pattern and Bristle brushes and on native Wayland and the web | 8–15 | +| Strokes, brushes, width profiles | 5 | 90% | more built-in brush libraries (thirteen generated in code including Tech Circuit, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media are done; Art brush Overlap and Pattern brush auto corners are done), pen pressure on macOS (the windowing layer reports none there), Stylus Wheel, tilt, bearing and rotation for Art, Pattern and Bristle brushes and on native Wayland and the web | 8–15 | | Appearance, transparency, graphic styles, masks | 5 | 98% | Graphic Styles list fills a taller panel above its footer (#2992; scores and estimates unchanged); raster effect reach in preview bounds (flattener presets apply in PDF, EPS and print) | 1–2 | | Live vector effects | 5 | 85% | Outline Object, Pathfinder Hard/Soft Mix and Trap (since done: #3061, #3063, #3785), SVG Filters, Transform Patterns and Scale Strokes & Effects on a fill's or stroke's own Transform effect | 6–10 | | 3D and Materials | 4 | ~25% | Initial Revolve, Extrude & Bevel, Inflate and Rotate, with simple lighting; materials, light presets, shadows, ray tracing, Rotate (Classic), Map Art and more complete visibility remain | 25–45 | @@ -550,7 +557,7 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale) | Type core | 9 | 80% | Middle Eastern features beyond bidi layout, Paragraph Direction, digit types and Kashidas (editable bidirectional SVG text, a split caret where directions meet; the Middle Eastern & South Asian composers are done, #4935, but `.ai`/EPS/PDF files carry no composer); paint-only harakat keep joining with conditional GDEF-mark colour ownership, but fonts without GDEF mark classes and some AAT/`morx` ligatures can still leave marks painted as their letters; Every-line Composer fidelity for justified and ragged text (available per object; mixed type sizes in a paragraph still break single-line in non-rectangular area type and with text wrap), Optical Margin Alignment, paragraph spacing limit for vertically justified area type, paragraph attributes in the Type tool's copy and paste (the characters keep their styles, the paragraphs take the destination's), mixed-value display in the Paragraph panel for a selection across differing paragraphs, partial selection of type-area anchors by marquee, optional font-size preservation during group scaling (scaled character controls fixed in #1034). Hyphenation and Justification options, Fractional Widths, System Layout, styled Type-range canvas Paste (#5636), and pattern hyphenation for eleven Indian languages with grapheme/cluster protection (#4947) are done; Sanskrit automatic patterns remain pending an allowlisted source | 14–19 | | Symbols, blends, envelopes, Repeat, perspective | 5 | 90% | further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons and Weather Icons are done), dynamic symbols' `.ai` round trip, envelope Anti-Alias/Preserve Shape output and warp point editing, brush interpolation in blends (M8 fidelity pass done); Symbol Options › Registration and Export Type and on-canvas dynamic part paint (gradient/pattern, opacity, blend) are done; symbol editing shows draggable 9-slice guides (#5280), while guides outside the artwork remain unsupported | 4–7 | | Image Trace, graphs, image tools | 3 | 72% | graph Column designs (Graph Design, Marker designs and series colours set with Group Selection are done), Create Object Mosaic, per-feature stroke/fill choice and varying widths in Image Trace's Create Strokes (Vector Halftone and the Image Trace View modes, Palette and Create Strokes are done) | 6–10 | -| Layers, artboards, document setup | 5 | 82% | Layers panel: a confirmation before deleting layers that hold art, row menu commands beyond Collect for Export (now on every layer, sublayer, group and object row), menus on guide and blend spine rows, the Layer Options dialog for several rows with mixed values, Paste Remembers Layers for sublayers; artboard preset polish (artboard escape routing and document setup modal handoff done; Move Artwork for artboard X/Y edits, Rearrange All Artboards, Document Setup, New Document and the rest of the Layers panel are done) | 4–7 | +| Layers, artboards, document setup | 5 | 82% | Layers panel: a confirmation before deleting layers that hold art, row menu commands beyond Collect for Export (now on every layer, sublayer, group, object and guide row), menus on blend spine rows, the Layer Options dialog for several rows with mixed values, Paste Remembers Layers for sublayers; artboard preset polish (artboard escape routing and document setup modal handoff done; Move Artwork for artboard X/Y edits, Rearrange All Artboards, Document Setup, New Document and the rest of the Layers panel are done) | 4–7 | | View & navigation | 3 | 70% | New View/Edit Views, multiple windows/arrange, Snap to Pixel/Glyph (print tiling is done) | 9–14 | | Guides, grids, smart guides, snapping, rulers | 3 | 85% | global/video rulers, Spacing Guides' distance readouts and spacing for resized or drawn art, Alt swapping a ruler guide's orientation, ruler guides selected together with art (marquee, Shift-click), ruler guides as Layers rows with their own lock and hide (#451: Lock Guides locks them all; Make Guides paths are Layers rows already; a marquee leaves locked or hidden guide paths out inside groups too, #8538) (dragging existing guides is done, #414; new guides snapping to side midpoints and artboards, and artboard guides, #451; the drawing tools snapping, with Construction Guides, #506; Spacing Guides for moves, #394; moves snapping to the grid, #740; ruler guides pulling drawn points with Smart Guides on, and "center" and "anchor" labels while hovering with the Selection tool, #812; distance and angle labels while drawing, #2983) | 2–4; status-bar X/Y uses the active ruler origin and General units | | File formats | 6 | 85% | `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, so the compound clipping path clips its clipping group (#8128; scores and estimates unchanged); PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300; scores and 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; scores and estimates unchanged); PDF import: stroked type keeps the file's line cap, line join and miter limit (#7741; scores and estimates unchanged); 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); Explicit editing-data oversized single-artboard import fixed (#6865); scores and estimates unchanged. Legacy `.ai` files that name but omit their prolog open with their layers, or with their art on one layer when the format has no layers; graph data and settings in these files still come in only as drawn art. Affinity export, and the rest of Affinity import (adjustments, blur and bevel effects, brushes, live symbol instances, text threading), DWG (no open spec: DXF instead), PSD placement as layers (Photoshop Import Options; the merged image is done), EPS checked against more real files users send (Inkscape files open as vectors; other generators' constructs are tested with programs written from the PostScript Language Reference only; CID-keyed CJK type and `CCITTFaxDecode` images not read), the rest of Illustrator's editing data (appearances and live effects, symbols, pattern fills, brushes, placed files: #637), the remaining fidelity polish; EPS, DXF, EMF/WMF, TIFF, BMP, Targa, PSD export, SVGZ, PDF security, PDF/X, PDF layers, presets and Affinity import are done | 6–10 (existing scope; Affinity export unestimated) | @@ -591,7 +598,7 @@ since 2026-10-01. | **Interaction fidelity:** modifiers, cursors, small behaviours | ~30–40% | The dedicated pass hasn't started, and there has been no side-by-side session with Illustrator yet. A power user notices this first | | **Look & feel** | ~75–80% | Measured against Illustrator 2026 screenshots (2026-10-02); the panels added since haven't been re-measured | | **File interop** | ~85% | SVG/SVGZ, PDF and PDF-compatible `.ai` (and legacy version 7 `.ai` out, keeping layers, groups and type as text), EPS, DXF, EMF/WMF, raster formats, PSD export and PSD/PSB placement (merged image), Place and Links, Package, Print, clipboard flavours. Affinity documents (Affinity 1–3) open natively as editable art, checked against 51 pinned public files (33 current `.af`), with selected saved-thumbnail comparisons and every-board native/SVG/PDF/PSD checks for current files; Affinity export is missing and effects, adjustments and brushes don't import. Affinity isn't an Illustrator feature, so this doesn't raise the parity score. The editing copy inside an Illustrator EPS or `.ai` is read for its structure: layers, groups, names, hidden objects and type, colours, gradients, transparency, images and every artboard (see Out of scope for what it doesn't read yet); DWG has no open spec | -| **Bundled content:** brush, symbol, style and swatch libraries | ~46% | Ours are original and generated in code, and far fewer than Illustrator ships; symbol libraries have six (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons, Weather Icons), graphic style libraries eleven (including Game HUD, Status Effects and Neon & Glow) and brush libraries twelve (Art Ribbons, Ink and Wash, Calligraphic Nibs, Pressure Sensitive, Bristle Brushes, Pattern Borders, Scatter Shapes, Game Trails, Energy Beams, Dry Media, Tech Circuit, Arrows) beside User Defined and Other Library… | +| **Bundled content:** brush, symbol, style and swatch libraries | ~46% | Ours are original and generated in code, and far fewer than Illustrator ships; symbol libraries have six (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons, Weather Icons), graphic style libraries eleven (including Game HUD, Status Effects and Neon & Glow) and brush libraries thirteen (Art Ribbons, Ink and Wash, Calligraphic Nibs, Pressure Sensitive, Bristle Brushes, Pattern Borders, Scatter Shapes, Stipple, Game Trails, Energy Beams, Dry Media, Tech Circuit, Arrows) beside User Defined and Other Library… | | **Performance** | unverified | Multithreaded, off-thread rendering and caches are in place. The last budget run (2026-10-01, loaded machine) measured 290 ms for a 50k-path fit against a 16 ms budget. Re-run `vectorcraft-cli perf` on an idle machine | | **Robustness** | good, new | ~2,840 tests, property tests, no panics in shipped code (lints, the `guard` safety net, import fuzzing), Data Recovery. Missing: a corpus of real-world files, Windows/Linux/browser QA | | **Platforms and 1.0 polish** | ~60% | The macOS app and the web build work, and Finder opens every readable format with the macOS app (#295, #354); on macOS the menus are in the system menu bar, laid out as a Mac app's, with the in-window menus as a fallback (`--in-window-menus`; verified on Windows and by cross-compilation, not yet by hand on a Mac); hybrid-graphics laptops render on the power-saving GPU by default on Windows and macOS (#306), and Windows starts on Direct3D 12, falling back to OpenGL, and loads no Vulkan driver unless `WGPU_BACKEND` asks for it (#545: Vulkan flickered black on an Intel GPU, DX12 and OpenGL didn't; #806: a faulty Vulkan driver crashed the app before its window appeared; verified by unit tests and the reporter's runs with `WGPU_BACKEND`), and Linux on the GPU the desktop runs on, since a Wayland compositor may refuse frames from the other one; a window that fails on its GPU while starting up starts again on the next one instead of crashing (#502; the dual-GPU Wayland case is verified by unit tests and cross-compilation, not on such hardware); web drops land in the document they were dropped on (#359); desktop drops carry no pointer position (winit 0.30), so a dropped document opens as a tab of its own and a picture or text is placed in the middle of the view, while the web places anything dropped on the canvas and opens what is dropped off it, as Illustrator does (#472); a web page that loses its WebGPU device or WebGL context restarts its graphics with the same documents (#369); on Linux/Wayland the clipboard reads the compositor's own (data-control) and copied image files paste, but files can't be dropped on the window under native Wayland until eframe moves to winit 0.31 (#398; the Wayland side is verified by compilation only), so Preferences › Performance › Linux Display Server › X11 (XWayland) opens the window through XWayland, where drops work (#1151; verified by unit tests and cross-compilation, not on a Wayland desktop); on Linux the Paste menu checks the system clipboard on a background thread, so a clipboard owner that never answers no longer freezes the window, while Windows and macOS keep their quick in-line check (#510; the X11 hang verified by the contributor, here by headless tests); on KDE Plasma 6.3+ under Wayland, pens and pen displays reach the app only under XWayland (`WAYLAND_DISPLAY=`) or with KWin's `KWIN_WAYLAND_EMULATE_TABLET=1`, since winit 0.30 has no Wayland tablet input (#491, not verified on hardware); Windows/Linux packaging and accessibility are pending | @@ -758,6 +765,7 @@ since 2026-10-01. - **EPS Save with Use Artboards:** Save As › EPS Options show Use Artboards with All or Range, for a separate file per artboard ([saving in EPS](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/save-artwork-in-eps-format.html)), unchecked by default (the scripting reference's EPS save options list `saveMultipleArtboards` with a default of false, [scripting reference](https://web.archive.org/web/20160803105056/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20JavaScript%20Scripting%20Reference.pdf)). Unchecked, Save writes one file whose bounding box fits all the visible art, as Export does, without the artboards' background colors; when no art shows, the page is the first artboard in its color. An opened EPS saved back this way loses its page margins. Checked with two or more chosen artboards, the file at the path is the central file of the visible art and each artboard is also written to `<name>_<artboard>.eps` beside it. Checked with one chosen artboard, VectorCraft writes that artboard as the page of the file at the path alone (the behavior Save had since #4293). Evidence: `cmd::fileio::tests_artboard_fill::eps_save_draws_the_color_on_an_artboard_page`, `tests::save::eps_save_without_use_artboards_fits_the_box_to_art_past_the_artboard`, `tests::save::opened_eps_saves_to_its_own_file_around_its_art_or_on_its_page`, `tests::save::eps_save_with_use_artboards_writes_the_central_file_and_one_per_artboard`, `dialogs::save_options::tests::eps_save_as_shows_use_artboards_off_and_writes_the_art_or_the_artboard`. - **EPS Options custom flattener settings:** the help page describes flattening an EPS's transparency with a preset or with custom options, adjusted through Custom ([saving in EPS](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/save-artwork-in-eps-format.html)). EPS Options now has Custom… beside the flattener Preset. It opens Custom Transparency Flattener Options on the settings the export would use: the raster/vector balance, both resolutions, the text and stroke outline switches, Clip Complex Regions and Anti-alias Rasters. OK goes back to EPS Options with the preset shown as [Custom], the export flattens with those settings, and the next EPS Options start from them; choosing a preset drops them, and Cancel goes back to EPS Options unchanged. Preserve Alpha Transparency stays off, and overprints are kept only with Overprints set to Preserve. The [Custom] label, the remembering, the Cancel behavior, Anti-alias Rasters and the ranges (balance 0 to 100, resolutions 1 to 2400 ppi) are VectorCraft's own. Evidence: `dialogs::tests_eps::custom_flattener_options_start_from_the_preset_and_cancel_goes_back_unchanged`, `custom_flattener_options_are_exported_and_remembered_until_a_preset_is_chosen`, `bad_custom_flattener_options_keep_the_dialog_open`. +- **Save PDF custom flattener settings:** the help page describes the Advanced section's flattener preset for PDF 1.3 saves of transparent art, with a Custom button for adjusting the flattener settings, and says neither is available at PDF 1.4 and later ([PDF options](https://helpx.adobe.com/illustrator/using/pdf-options.html)). Save PDF › Advanced now has Custom… beside Flattener preset, enabled for PDF 1.3, PDF/X-1a and PDF/X-3. It opens Custom Transparency Flattener Options on the settings the save would use: the raster/vector balance, both resolutions, the text and stroke outline switches and Anti-alias Rasters; Clip Complex Regions shows on, as the PDF 1.3 writer always clips, overprints are kept only with Overprint set to Preserve, and Preserve Alpha Transparency shows off, as PDF 1.3 rasters keep no alpha. OK goes back to Save PDF with the preset shown as [Custom] and the save flattens with those settings; settings equal to the preset's leave its name, choosing a preset drops them, and Cancel goes back unchanged. PDF presets keep the flattener preset but not these settings, and Save Preset… says so while they are set. `ui.savePdfDialog` keeps a `flattener` it is given. The [Custom] label, the Cancel behavior, Anti-alias Rasters, the editor's absence from the PDF preset editor and the ranges (balance 0 to 100, resolutions 1 to 2400 ppi) are VectorCraft's own. Evidence: `dialogs::save_pdf::tests::custom_is_enabled_where_the_save_flattens`, `custom_starts_from_the_preset_and_cancel_goes_back_unchanged`, `custom_options_are_written_until_a_preset_is_chosen`, `custom_options_equal_to_the_preset_leave_its_name`, `custom_shows_alpha_as_the_pdf_1_3_writer_drops_it`, `save_preset_says_it_leaves_the_custom_flattener_options_out`, `save_pdf_opens_with_the_flattener_options_given_and_refuses_bad_ones`. - **Raster export backgrounds (#6125):** a raster export draws its background under the finished art, and blend modes read only the art below them, as on the canvas. An Outer Glow in Screen mode on the bare page shows in a PNG on white and in a JPEG. Flatten Transparency puts its white under the finished art the same way. Evidence: `tests::file::a_screen_outer_glow_is_in_raster_exports`, `tests::objectfx::a_screen_outer_glow_on_the_bare_page_shows_on_a_background`, `tests::knockout::page_knockout_and_isolated_blending`, `tests::knockout::no_blend_mode_reads_the_background`, `tests::cmykflatten::every_blend_mode_flattens_to_the_canvas_pixels_in_cmyk`. @@ -806,6 +814,7 @@ since 2026-10-01. - **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. +- **Width Point Edit on several selected width points:** double-clicking one of several Shift-selected width points keeps the selection and opens the dialog for all of them (`ui.widthPointEdit {id, indices}`); a double-click on an unselected point edits that point alone. Side 1 and Side 2 typed in apply to every selected point, and OK changes them all in one undo step (none when nothing changed); Delete removes them all. Fields show a value only where every point has it and are blank otherwise; a side width replaces that side of each point and keeps its other side, Total Width scales each point's own sides, Adjust Adjoining Width Points changes the nearest unselected points, and with a discontinuous point Incoming and Outgoing edit its halves; these rules are VectorCraft's own. Tests `distort::width::tests::double_click_on_one_of_several_selected_points_edits_them_all` and `dialogs::width_point::tests::several_points_*`, `a_side_width_sets_that_side_of_every_selected_point`, `ok_on_several_points_is_one_undo_step`, `adjoining_points_follow_every_changed_point_once`, `delete_removes_every_selected_point` and `double_clicking_one_of_several_selected_points_and_typing_edits_them_all`. Public references: [Apply stroke on an object](https://helpx.adobe.com/illustrator/using/stroke-object.html), which describes Shift-clicking to select several width points and setting Side 1 and Side 2 for all of them in Width Point Edit, and an [archived user guide, p. 161](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=167), which describes the same dialog for several points. 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. @@ -858,7 +867,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **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`. +- **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 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`. +- **Profile Mismatches and Missing Profiles:** Edit › Color Settings… (the Separations panel's Color Settings section and `edit.colorSettings`) has Profile Mismatches: Ask When Opening and Ask When Pasting, and Missing Profiles: Ask When Opening, off by default and kept in `Color Settings.json`. With a box on, File › Open asks before a document opens whose color mode's profile is not the working space (use the embedded profile, convert the colors to the working space, or discard the profile) or that has none (leave it, assign the working space, or assign a profile), and Paste, and a drag of artwork from another document, ask whether colors from a document with another profile keep their numbers or convert; each starts on what the policy does, and a paste question about both models has a choice for each. `document.open {profileChoice}` and `profileMismatch` on the paste commands and `edit.dropSelection` give the answer without a prompt, and `clipboard.profileMismatch` lists what a paste or a drop would ask about. Asking about the profile of the document's color mode only, the choice a missing profile starts on under Convert to Working Space and a paste choice for each model are VectorCraft's own rules. Public reference: [About missing and mismatched color profiles and 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 `dialogs/profile_mismatch/tests.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`. @@ -1043,6 +1053,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - With anchor points selected with Direct Selection, the contextual task bar offers Remove Anchor Points, Connect (`path.join`), Cut Path, and Convert Selected Anchor Points to Corner and to Smooth (`path.convertAnchors` with `to` set to `corner` or `smooth`), the commands of the Control bar's anchor buttons; the two convert buttons show their icons alone, named by their tool tips as on the Control bar (VectorCraft's own choice). The overview lists items that delete the selected anchors, join selected end points, split the path at the selected anchors, and make the selected anchors corner or smooth points ([Contextual Task Bar overview](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/contextual-task-bar-overview.html)). With a path selected whole with Direct Selection, the bar also offers Simplify and Smooth, which open the Simplify and Smooth sliders as Object › Path › Simplify… and Smooth… do; the same overview names Smooth as adjusting the path's curvature (#6784). VectorCraft's own rule: while anchors are picked out, the bar offers the anchor items without Simplify and Smooth. Evidence: `direct_selection_smooth_opens_the_smooth_slider` in `crates/ui-egui/src/tests/taskbar.rs`. - Tool flyouts tear off: dragging or clicking the tear-off bar on a flyout's right side (or releasing the long press over it) floats its group as a strip of tool buttons, moved by the same bar and put back in the toolbar by the × at its top (`window.floatTools`). While a group floats, the presses that would open its flyout raise the strip instead. Floating strips are kept with the preferences and in user workspaces. Not done: turning a strip vertical, docking it. - Screen readers get a name for the Tools panel's tool buttons, flyout rows, floating strips and tear-off bars, and for the icon buttons, text buttons, toggles, checkboxes, radio buttons, tabs, chips, sliders, angle dials and combo boxes that panels and dialogs draw with `crates/ui-egui/src/widgets.rs`: the text, label or tool tip each one shows, or a name of its own where it shows none (the angle dial, the spinner, the preset arrow, the color wheel and the Reference Point's squares). The tool buttons, toggles, checkboxes, radio buttons, tabs and the Reference Point's nine squares also report whether they are on, an icon button that is lit, such as the chosen Align To button, reports that it is pressed, and the angle dial reports its angle. The status bar's First, Previous, Next and Last Artboard buttons have tool tips. + - General › Show Tool Cards (`showToolCards`, off by default, VectorCraft's own feature): with Show Tool Tips on, resting the pointer on a tool button in the Tools panel, a floating flyout or a toolbar made with New Toolbar shows a card in place of its one-line tool tip, and resting it on a flyout's row shows one too. The card has the tool's icon, name and shortcut, one sentence on what the tool does, and one line for each action of its hint-bar text, with the modifier keys named for the platform. A tool without a description keeps its one-line tool tip. The card does not take clicks, keys or the pointer, sits beside its button inside the window (beside a flyout on the side the flyout opened toward, past its bar; below a floating flyout, or above it when there is no room below; where the window has no room for it, the button keeps its one-line tool tip), and goes away on a press, drag, key, modifier key, scroll or pinch until the pointer leaves the button. While a group's flyout is open, only its rows show cards. The checkbox is dimmed while Show Tool Tips is off. Evidence: `a_tool_card_never_gets_in_the_way`, `a_floating_flyouts_cards_give_way_to_an_open_flyout`, `a_floating_flyouts_card_goes_above_or_gives_way_in_a_short_window` and `a_flyout_opened_to_the_left_shows_its_cards_on_the_left` in `crates/ui-egui/src/toolbar/tests.rs`. - Tab does not stop on the regions that only the pointer uses: the custom title bar's background and the window's resize zones, the band at the top of a dialog that moves it, the Tools panel's grip, a flyout's and a floating strip's tear-off bar, the isolation bar's background, and the rulers and the box where they meet. - These dialog sliders, each beside a number field, respond to the keyboard: those of the effect, tool option, brush and transform dialogs, the Perspective Grid, the 3D dialogs, and the flattener options, which the Flattener Preview panel also shows. A click, or Tab, gives a slider the keyboard focus, and an outline shows it. Then → and ↑ step the field's number up to the next whole number and ← and ↓ step it down to the next whole number, Shift with an arrow and Page Up and Page Down step it by ten, and Home and End set the slider's first and last value; no step goes past either end. Screen readers' increment and decrement actions step the slider as → and ← do. The Color panel's, Swatch Options', the Navigator's and the Character panel's sliders, and the Color Picker's channel slider, respond only to the pointer. The keys follow the WAI-ARIA slider pattern (<https://www.w3.org/WAI/ARIA/apg/patterns/slider/>); the reference app's help does not describe keys on a dialog's slider, so the step sizes are VectorCraft's own. - Screen readers get the value of the color and channel sliders that panels and dialogs draw (the Color panel, the Color Picker, Swatch Options, the Navigator's Zoom, the Character panel's variable font axes, the Perspective Grid and flattener options, and the sliders of the effect, tool option and transform dialogs): the number and text of the field beside each one, such as 128 for G or 50% for an opacity, with the slider's range, which extends to include a number past the slider's end. The harmony wheel's Brightness slider, which has no field, reports its brightness in percent. @@ -1063,6 +1074,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Window › Toolbars › Manage Toolbars… and Manage Toolbars… in the All Tools drawer's menu open a dialog that lists the toolbars made with New Toolbar: a new name typed for the selected toolbar renames it, + copies it with its tools (with none selected, + makes a blank toolbar), and the trash can deletes it. Each change shows under Window › Toolbars and stays in the workspace (<https://helpx.adobe.com/illustrator/using/tools.html>; `window.toolbar.manage`, `window.toolbar.rename`, `window.toolbar.duplicate`, `window.toolbar.delete`; `manage_toolbars_renames_duplicates_and_deletes`). - A toolbar made with New Toolbar docks in a lane along the window's left or right edge when its title bar is dropped on that edge, or with Dock to Left and Dock to Right in the title bar's context menu. Toolbars docked at one edge stack from the top, each with its share of the lane's height, and the lane is as wide as its widest toolbar; a lane too short for its stack wraps it into more columns, up to half the window's width, and past that the toolbars show only their title bars, which the mouse wheel scrolls through when even they do not fit. Dragging the title bar out of the lane, or Float Toolbar, floats it again, and Escape during the drag puts it back. Hiding and renaming keep its place, and the workspace keeps it. New toolbars still start floating. The lanes and the stacking are VectorCraft's own rules (#1759; `window.toolbar.dock`, `window.toolbar.float`; `toolbars_dock_and_float_by_their_commands`, `docked_toolbars_stack_in_lanes_along_the_window_edges`, `a_title_bar_dropped_on_an_edge_docks_the_toolbar`). - The status bar shows the errors of the toolbars made with New Toolbar (a missing, empty, too long or taken name, the 64-toolbar limit, a `side` or `order` that `window.toolbar.dock` does not take, and New Toolbar's dialog and Manage Toolbars) in every language that translates every message, with the toolbar's name, the parameter key and the value given kept as they are; the error the command returns stays English (`custom_toolbar_command_errors_are_translated`). + - Swedish messages (2026-11-13): the Swedish (`sv`) catalog has an `@msg` row for 464 of the 628 status and error messages the untranslated report listed for it; 162 messages that no complete-message catalog translates, 36 composite font errors among them, are not translated yet, and two unknown-parameter errors that start with the `{within}` placeholder stay in English, as does `{name} must be {lo}–{hi}{unit} (got {v})`, whose existing row can't match because two of its placeholders sit side by side; the rows keep their placeholders, backticked names, quoted values and command ids; native review remains; scores and estimates unchanged. - Window › Toolbars › Keep Tools Beside the Canvas, a VectorCraft layout option that is off by default, docks the Tools panel between left-side panels and the canvas instead of at the window's left edge, and workspaces keep the setting. A floating Tools panel dropped on the canvas's left edge, right of panels docked on the left, docks there and turns the setting on, and one dropped on the window's left edge docks there and turns it off; with no panels docked on the left, a drop leaves the setting as it is (#7837). Scores are unchanged (`window.toolsBesideCanvas`; `docked_tools_keep_the_window_edge_unless_kept_beside_the_canvas`, `tools_dropped_on_a_left_edge_dock_there_and_the_setting_follows`, `tools_dropped_where_the_left_edges_overlap_keep_the_setting`, `tools_dropped_beside_a_collapsed_left_dock_follow_the_strip_dropped_on`). - Hindi (2026-11-06): Hindi (`hi`): 7,877-row machine-assisted catalog, zero/one singular plurals, desktop font fallback and optional Devanagari craft-fonts fallback; all 55 translation tests pass; native review and a web font remain; scores and estimates unchanged. [Terminology and limitations](localization-hi.md). - Gujarati (2026-11-14, #6613): `gu` has 4,673 catalog rows, zero/one singular plurals, installed desktop font fallback and support for optional `Gujr` craft-font faces. The original 4,286 rows remain unchanged; all 387 additions are contributor-reviewed and approved, with 11 wording corrections. Status/error messages remain partial; the pinned fonts and web startup list have no Gujarati face, so web selection remains unavailable until one is bundled. Current-head validation is recorded in the PR; scores and estimates unchanged. @@ -1115,6 +1127,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - 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, 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 menu's Show on Shape Creation (`showOnShapeCreation`) shows the Transform panel after a shape is drawn: with the Rectangle, Rounded Rectangle, Ellipse, Polygon, Star or Line Segment tool (a drag, or OK in the tool's dialog), as a rectangle, ellipse, polygon or line that the Shaper tool recognizes, or by a `shape.rectangle`, `shape.ellipse`, `shape.polygon`, `shape.star` or `shape.line` command, alone, as a batch step or on the active perspective plane ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/transform-panel-overview.html)). VectorCraft's own rules: the option is off until chosen and is kept with the preferences; the panel shows where Window › Transform shows it, and a panel that is showing already stays as it is; a canceled drag or dialog, saved steps an action plays, a script's commands and Presentation Mode leave the panels as they are (`panels::transform::tests::show_on_shape_creation_shows_the_transform_panel_after_a_shape`, `a_frame_after_a_shape_shows_the_transform_panel`, `tests::journal::take_shape_drawn_follows_the_shapes_that_were_drawn`, `take_shape_drawn_counts_shapes_drawn_in_perspective`). - 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`). @@ -1123,6 +1136,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Object › Transform › Rotate Bounding Box… turns the selection's bounding box by the angle typed in its dialog without moving the art (`object.rotateBoundingBox`, `absolute: true` to set the angle). Objects with different angles get one shared angle, and the objects inside a group and the art of a linked opacity mask turn with it. A path of a compound path selected on its own turns only its own box, and Reset Bounding Box squares only that path's box too (VectorCraft's own behavior; `bboxrotate::rotate_bounding_box_turns_the_box_and_leaves_the_art`, `rotate_bounding_box_back_to_zero_stores_zero`, `rotate_bounding_box_gives_a_mixed_selection_one_angle`, `rotate_bounding_box_turns_the_objects_inside_a_group_with_it`, `rotate_bounding_box_turns_a_linked_masks_art_only`, `reset_bounding_box_squares_every_box_rotate_bounding_box_turned`, `rotate_bounding_box_refuses_bad_params`, `tests::rotate_bounding_box_of_a_compound_paths_member_turns_only_that_path`, ui-egui `panels::transform::tests::rotate_bounding_box_menu_item_turns_the_box_by_the_dialog_angle`). - After a rotation the Free Transform tool shows and drags the same turned bounding box as the Selection tool: its handles, their cursors and its rotate zone sit on the selection's own sides, a handle scales along those sides from the opposite handle ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/scale-objects.html)), Cmd/Ctrl on a side handle shears along that side, and Perspective Distort and Free Distort start from the turned box's corners (`object.distort` takes `angle` with `from`) (`bboxrotate::free_transform_handles_turn_with_the_object_and_scale_along_its_axes`, `free_transform_shears_along_the_turned_side`, `free_transform_distort_starts_from_the_turned_box`, `xform::distort_reads_from_in_a_turned_frame_and_rejects_a_bad_angle`, tools `xform::free::tests::the_box_and_its_handles_turn_with_the_selection`). - After a rotation the Scale and Reflect tools, the Scale and Reflect dialogs, `object.scale`, `object.reflect` with a named axis and the Transform and Properties panels' flips act along the selection's turned bounding box until Reset Bounding Box: the horizontal and vertical scale stretch along its own width and height, and the vertical and horizontal reflection axes are its own. The Reflect tool's default axis and its Shift steps start from the box's axes, and an axis drawn with the tool is the line drawn on the page. `basis: "page"` keeps the page's axes (VectorCraft's own rules; `bboxrotate::scale_and_reflect_follow_the_turned_box`, tools `xform::transform::tests::scale_and_reflect_drags_follow_a_turned_bounding_box`). + - The Reflect tool sets an axis with two clicks: a click sets the first point (and the reference point), and a second click reflects the selection across the line through both points as one undo step; Alt/Option on the second click reflects a copy, and a drag after the first click draws the axis from it ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/reflect-or-flip-objects.html)). A dashed line runs from the first point to the pointer until the second click. VectorCraft's own rules: an Alt-click opens the dialog and sets no axis; a second click whose snapped point is within 3 screen pixels of the first point's snapped point does nothing and the axis keeps waiting; Shift does not constrain a plain second click; Escape, Enter, a changed selection, an edit made outside the tool or another tool drops the waiting axis. A double-click arrives as two clicks: its first click is the second point, so a double-click away from the first point reflects the selection, and the double-click then opens the dialog with no axis waiting (tools `xform::transform::tests::a_second_reflect_click_reflects_across_the_line_through_both_points` and the four tests after it; engine `xform::two_reflect_clicks_reflect_across_their_line_as_one_undo_step`). - Perspective Distort and Free Distort (`object.distort`) turn each warped object's bounding box as the warp turns the object at its own center, the objects inside groups, compound paths and clip groups and the art of linked opacity masks included, so the next Selection or Free Transform drag uses the tilted box; Object › Transform › Reset Bounding Box squares it again, and corners left where they are add no undo step (VectorCraft's own rule; `bboxrotate::distort_turns_an_upright_box_with_the_warp_at_its_center`, `distort_turns_each_member_and_linked_mask_by_its_own_warp`, `mirrored_and_collapsing_distorts_keep_valid_angles`, `distort_angles_undo_redo_and_reopen_together`, `xform::unchanged_distort_records_no_history`). - 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`). @@ -1181,10 +1195,12 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **The Symbols panel reads its current symbol from the document:** the Symbols panel and its panel menu read the current symbol on each frame without running `symbol.list`, which counts every symbol's instances by walking the whole document. The current symbol they show and act on is the one `symbol.list` reports, and an idle frame of the panel or its menu runs no command, so on macOS the native menu is not brought up to date on every frame while the panel is open. In a document with 200 symbols and 50,000 objects, the read takes 0.035 µs instead of 48.5 ms in a release build (thread CPU time on Linux, median of 7 runs); in a small document the difference is too small to notice. Tests: `tests::brushsym::current_symbol_is_the_current_symbol_list_answers`, `panels::symbols::tests::current_is_the_current_symbol_list_answers`, `panels::symbols::tests::idle_frames_of_the_panel_and_its_menu_run_no_command`; the timing probe is `panels::symbols::tests::current_symbol_read_timing`. - **Expand of symbol instances:** Object › Expand turns selected symbol instances (without effects, not in perspective, in groups or placed documents too) into their art as Break Link to Symbol places it, one level deep, as one undo step; the Expand dialog's Fill and Stroke reach that art (`object.expand`, `crates/engine/src/tests/expand_symbols.rs`; estimated, score unchanged). - **Reset Transformation** ([Transform symbols](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/transform-symbols.html), [Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html)): the Symbols panel menu's Reset Transformation and the Control bar's Reset, shown while symbol instances are selected, give the selected instances their symbol's own scale again, without rotation or shear, as one undo step (`symbol.instance.resetTransform`); an instance in perspective is left as it is. VectorCraft's own rules: each instance keeps the center of its bounding box in place, reflection is removed too, and the menu item and the button are enabled only while a selected instance would change. Tests: `tests::brushsym::reset_transformation_restores_the_symbols_scale_and_keeps_the_center`, `reset_transformation_keeps_the_center_of_art_away_from_the_origin`, `reset_transformation_ignores_a_stored_size_that_is_not_positive`, `reset_transformation_leaves_unchanged_instances_and_refuses_bad_ids`, `panels::symbols::tests::reset_transformation_is_enabled_for_a_transformed_instance_and_resets_it`. + - **Symbolism Tools Options** ([Symbolism tool options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbolism-tool-options.html), [the archived manual](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=118)): the dialog a double-click on a symbolism tool opens has, besides Diameter, Intensity and Symbol Set Density, Use Pressure Pen (a pen's pressure is the intensity), Method (User Defined, Average or Random) for the Scruncher, Sizer, Spinner, Stainer, Screener and Styler, Show Brush Size and Intensity, the Symbol Sprayer's Scrunch, Size, Spin, Screen, Stain and Style (each Average or User Defined), and the Symbol Sizer's Proportional Resizing and Resizing Affects Density; a new Symbol Set Density spaces the instances of the selected symbol sets (`symbol.setDensity`). VectorCraft's own rules: a Tool row lists the eight tools by name and shows the chosen one's options; Random gives each instance its own share of the change for the whole stroke; Average moves each value toward the mean of the instances under the brush; the starting values are Method User Defined, the Sprayer's six options Average, Proportional Resizing on and Resizing Affects Density off, so only a Sprayer stroke over instances of the selected set changes from before (its new instances take their mean values); the brush shows the intensity as a dashed ring. The Symbol Sprayer does not use Intensity or pen pressure. Tests: `crates/engine/src/tests/symbolism_options.rs`, `symbolism::tests` in `crates/tools`, `dialogs::symbolism_options::tests`. - **The Symbols and Properties panels find selected symbol instances once per revision:** whether the selection or its groups hold a symbol instance (Break Link to Symbol), one with appearance changes of its own (Reset Symbol Instance and the Properties panel's Reset), or one Reset Transformation would change is worked out in one walk of the selected objects for each document revision, and later frames reuse it. The buttons and menu items are enabled as before. With one selected group of 300,000 paths, the two panels' reads took a median 5.1 to 5.7 ms of thread CPU time per frame; the first read after a change now takes about 3 ms and later frames about 5 ns (Linux, opt-level 3, median of 7 runs). In a small document the difference is too small to notice. Tests: `panels::symbols::tests::instance_flags_are_found_once_per_revision_and_match_a_walk_of_the_selection`, `properties_and_symbols_panels_walk_the_selection_once_per_revision`. - **Expand of dimensions:** Object › Expand, Expand Appearance, Create Outlines and Outline Stroke turn a dimension whose art they change into a plain group of that art, which stays as it is through later moves, scales and edits of what it measured; undo gives the live dimension back (`crates/engine/tests/it/dimensions.rs`; VectorCraft's own rule; estimated, score unchanged). - - **Brush libraries** ([public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html)): Window › Brush Libraries, the Brushes panel's Brush Libraries Menu and its menu's Open Brush Library open each library in a library panel of its own, as swatch, graphic style and symbol libraries do. The built-in libraries (Art Ribbons, Ink and Wash, Calligraphic Nibs, Pressure Sensitive, Bristle Brushes, Pattern Borders, Scatter Shapes, Game Trails, Energy Beams, Dry Media, Tech Circuit, Arrows) are original brushes generated in code (`crates/engine/src/cmd/brushlib.rs`); Striped Ribbon's art is filled with the library's own pattern and Sparkles scatters the library's own symbol; Ink and Wash adds ink and wash brushes (the [help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html) lists an Ink brush library of strokes with varied thickness and texture; the names, shapes and opacities are VectorCraft's own): Tapered Ink, an art brush broad near its start that thins to a fine tip; Brush Pen, a calligraphic brush whose size follows the pen pressure; and Soft Wash and Pooling Wash, art brushes of translucent gray layers that take the stroke color as tints; Game Trails adds motion art brushes (Speed Line, Dash Trail, Burst Ray, Zigzag); Energy Beams adds laser and plasma art brushes (Laser Bolt, Plasma Arc, Charge Wave, Spark Trail); Dry Media adds grainy art brushes (Chalk Grain, Graphite Pencil, Wax Crayon, Charcoal Dust). 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`. + - **Brush libraries** ([public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html)): Window › Brush Libraries, the Brushes panel's Brush Libraries Menu and its menu's Open Brush Library open each library in a library panel of its own, as swatch, graphic style and symbol libraries do. The built-in libraries (Art Ribbons, Ink and Wash, Calligraphic Nibs, Pressure Sensitive, Bristle Brushes, Pattern Borders, Scatter Shapes, Stipple, Game Trails, Energy Beams, Dry Media, Tech Circuit, Arrows) are original brushes generated in code (`crates/engine/src/cmd/brushlib.rs`); Striped Ribbon's art is filled with the library's own pattern and Sparkles scatters the library's own symbol; Ink and Wash adds ink and wash brushes (the [help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html) lists an Ink brush library of strokes with varied thickness and texture; the names, shapes and opacities are VectorCraft's own): Tapered Ink, an art brush broad near its start that thins to a fine tip; Brush Pen, a calligraphic brush whose size follows the pen pressure; and Soft Wash and Pooling Wash, art brushes of translucent gray layers that take the stroke color as tints; Game Trails adds motion art brushes (Speed Line, Dash Trail, Burst Ray, Zigzag); Energy Beams adds laser and plasma art brushes (Laser Bolt, Plasma Arc, Charge Wave, Spark Trail); Dry Media adds grainy art brushes (Chalk Grain, Graphite Pencil, Wax Crayon, Charcoal Dust). 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`). + - **Stipple library** ([About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Stipple holds Fine Stipple, Dense Stipple, Soft Stipple and Bold Stipple. These original scatter brushes place filled vector dots or small dot clusters along a path, with varied size, spacing and spread; Soft Stipple uses translucent dots. Their art and settings are VectorCraft's own. Evidence: `stipple_library_draws_dot_textures_and_survives_save` in `crates/engine/src/tests/brushlib.rs` covers listing, finite drawn geometry, dots that take the stroke color with only Soft Stipple's translucent, add and apply, and saved-library reopening. - **Bristle strokes follow recorded pen input** ([brush documentation](https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=201)): a Bristle brush in VectorCraft widens its strand spread and thickness with pressure along the stroke; pen tilt changes the spread, and bearing and barrel rotation turn it in the path's local frame. Missing pen channels use neutral values, and mouse strokes keep their existing appearance. This is VectorCraft's own rendering model; hardware-specific output has not been verified. `bristle_pen_pressure_changes_its_footprint`, `bristle_pen_pressure_is_sampled_along_the_stroke`, `trimmed_bristle_strands_read_pressure_where_they_begin` and `bristle_pen_orientation_changes_its_footprint` cover the geometry in `crates/brush/src/tests.rs`; `bristle_path_keeps_and_draws_its_pen_pose` covers saving and export in `crates/engine/src/tests/brushsym.rs`; area scores unchanged. - **Tech Circuit library:** Circuit Trace is a chamfered art brush with 45-degree elbows and terminal pads; Bus Lines repeats three parallel conductor lanes; Terminal Nodes repeats solder pads, circular test points and connecting leads. Original vector geometry generated in code, with Tints colorization and continuous pattern tile edges. Evidence: `the_tech_circuit_library_constructs_adds_and_applies_each_brush` in `crates/engine/src/tests/brushlib.rs` covers listing, finite geometry on straight, curved, short and closed paths, add/apply, undo/redo, deduplication and saved-library round trips. G5 remaining estimate 3–13 h (estimated); area scores unchanged. - **Pressure Sensitive library** ([About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Pressure Sensitive offers Flex Ribbon, Pulse Stroke, Round Flow and Chisel Flow. The first two are art brushes whose width follows recorded pen pressure; the other two are calligraphic nibs whose size follows it. They use the engine's existing pressure input where the device and platform deliver it, and a neutral width for a mouse path. These presets and names are VectorCraft's own. Evidence: `pressure_sensitive_brushes_widen_with_pen_pressure_and_survive_a_saved_library` in `crates/engine/src/tests/brushlib.rs` checks light and heavy pressure, short and curved paths, add/apply and saved-library reopening; `the_window_menu_and_the_brushes_panel_open_brush_libraries` covers opening and clicking from the UI. @@ -1205,6 +1221,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **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. - **Pen rubber band after a smooth anchor:** the preview segment to the pointer is the curve a click there adds, leaving the last anchor along its outgoing handle and arriving at the new corner anchor without a handle, so the segment keeps its shape when the anchor is placed, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/preview-paths-drawn.html) describes. Before, the preview was a different curve, and the segment changed shape at the click (#8296, in part; `pen::tests::rubber_band_is_the_segment_a_click_adds`); scores and estimates unchanged. + - **Pen rubber band over an anchor a click ends on:** over the path's first anchor, the preview segment ends on that anchor, as the closing segment does; over an end of another open path, it ends on that end and arrives along the end's own handle, as the joining segment does. The preview picks these anchors at the pointer before snapping, as a press does. Before, the preview ended at the pointer and arrived without a handle, so the segment moved by up to the pick tolerance at the click, and changed shape when the other end was smooth (#8296, in part; the `pen_rubber_band` tests in `engine/tests/it`); 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. @@ -1235,6 +1252,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - 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`). + - In isolation mode the Layers panel lists only the art of the isolated layer, sublayer or group, and lists the other layers and groups again when isolation mode ends ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=212)). As VectorCraft's own rules, the isolated layer, sublayer, group or object is the top row and opens on entering, the panel scrolls back to its row on leaving, search and filter look only inside it, nothing is dropped beside its row or into the empty space under the rows, Rename and Locate Object open no rows outside it, and rows highlighted outside it are no longer highlighted. With no row highlighted, Delete Selection and the trash do not delete a current layer outside it. New Layer, New Sublayer and Duplicate (in the panel menu and a row's context menu) are off, and OK in New Layer Options is an error, while the layer or copy they make would be outside it (`isolation_lists_only_the_isolated_art_and_exit_lists_every_layer_again`, `isolation_opens_the_isolated_row_and_keeps_drops_inside_it`, `isolation_drops_highlights_outside_the_isolated_art`, `isolation_keeps_rename_and_locate_to_the_rows_listed`, `isolation_keeps_delete_to_the_rows_listed`, `isolation_keeps_new_layers_to_the_rows_listed`, `new_layer_options_ok_checks_isolation_again`). - 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). @@ -1246,6 +1264,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - On Windows and Linux, F2, F3 and F4 run Cut, Copy and Paste alongside Ctrl+X, Ctrl+C and Ctrl+V, and in the web build they do so everywhere except macOS. The Edit menu keeps the Ctrl shortcuts, and Keyboard Shortcuts lists both keys of each row. On macOS only Cmd+X, Cmd+C and Cmd+V are the defaults. F2, F3 and F4 do not run these commands in a focused text field or while the Type tool edits text. A saved shortcut set that assigns one of these keys to another command keeps that assignment. Public reference: [Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html). - Cmd/Ctrl+A follows the keyboard: in a panel, dialog or search field it selects the field's text, while the Type tool edits it selects all of that text (also `select.all` over MCP), and only otherwise every object. On macOS the menu bar's Select All, Cut, Copy and Paste (keys or clicks) act on a focused field too, and elsewhere the in-window menus' do: the field that had the keyboard when the menu opened gets them, with its selection, and the keyboard back (#516). Not yet: Select All across threaded frames (one frame's text is selected). - Cmd/Ctrl+A follows the keyboard: in a panel, dialog or search field it selects the field's text, while the Type tool edits it selects all of that text (also `select.all` over MCP), and only otherwise every object. On macOS the menu bar's Select All, Cut, Copy and Paste (keys or clicks) act on a focused field too, and elsewhere the in-window menus' do: the field that had the keyboard when the menu opened gets them, with its selection, and the keyboard back (#516). In a frame of threaded text, Select All selects the whole story, highlighted in every frame: Copy and Cut take all of it, typing or Delete replaces it as one undo step, and a fill, a size step or a Character or Paragraph panel change applies to every frame's text (VectorCraft's own behavior; `textedit::select_all_in_a_threaded_frame_selects_the_whole_story`, `textedit::typing_over_the_whole_story_replaces_every_frames_text_in_one_step`). + - With text selected in a panel's label, such as a Document Info value, Cmd/Ctrl+C and Cmd/Ctrl+X copy that text and do not copy or cut the art, and so do F3 and F2 where they are Copy and Cut, any other keys assigned to Copy or Cut, and the menu bar's Copy and Cut on macOS. When the selected label is not drawn (the panels are hidden), Copy and Cut act on the art instead (#8432; VectorCraft's own behavior; `selectall::copy_and_cut_copy_the_text_selected_in_a_panel_label`, `selectall::copy_sent_on_from_another_window_copies_the_text_only_when_it_is_this_windows`, `selectall::panel_text_copied_before_the_art_formats_are_written_stays_on_the_clipboard`, `shortcuts::tests::a_window_notes_only_its_labels_copies_until_the_next_main_window_pass`, `shortcuts::tests::a_window_notes_a_copy_of_text_dragged_across_its_label`). Not yet: the in-window Edit menu's Copy and Cut (the click on the menu clears the label's selection first), and, while the selected text is in a floating panel's own window, the menu bar's Copy and Cut, and F3 and F2 (they do not copy the text). - With the whole story of threaded text selected by Select All, Remove Line Breaks, Remove Paragraph Breaks and Type › Bullets and Numbering › Convert to Text act on the text of every frame as one undo step, locked and hidden frames included, and the story stays selected after Convert to Text; a selection inside one frame changes only that frame (VectorCraft's own behavior; `textedit::remove_breaks_takes_the_whole_story_that_select_all_selected`, `textedit::convert_to_text_takes_the_whole_story_that_select_all_selected`, `textedit::convert_to_text_of_the_whole_story_converts_locked_and_hidden_frames`, `textedit::remove_breaks_of_the_whole_story_takes_locked_and_hidden_frames`). - When only some frames of a threaded story are selected, Remove Line Breaks and Remove Paragraph Breaks go through that story's frames once for all of them, not once per selected frame; each selected frame still loses its own breaks, in the order selected, as one undo step (`addons::cleanup::text::tests::remove_breaks_goes_through_a_partly_named_story_once`). - With the whole story of threaded text selected by Select All, the Character, Paragraph, OpenType, Tabs and Text Styles panels, the Justification dialog and the font menu change the frames that are in the edited frame's thread at the time of the change, locked and hidden frames included. A frame that has left the thread is not changed, and a frame added to the thread is (VectorCraft's own behavior; `panels::character::tests::story_changes_follow_the_edited_frames_thread_after_the_first_saved_frame_leaves`, `story_changes_leave_out_a_frame_that_left_and_take_in_a_frame_that_joined`, `story_changes_stay_in_the_edited_frame_once_its_thread_is_removed`, `story_changes_take_in_locked_and_hidden_frames`, `panels::tabs::tests::indent_markers_after_select_all_keep_each_story_paragraphs_indents`, `dialogs::justification::tests::justification_dialog_follows_the_story_thread_at_ok`). @@ -1361,6 +1380,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur In the Ellipse dialog, a click on the word Height copies the Width value into the Height field, so OK draws a circle of that width, as [the help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=140) describes for drawing ellipses. The Rectangle and Rounded Rectangle dialogs keep plain labels. VectorCraft's own rules: the word Height is a button that Space or Enter also presses, and that Enter does not press OK (nor does Enter on the Constrain Width and Height Proportions button); with the link on, the link stays on and keeps the circle when a side is typed next; a Width that is empty or not a distance, including one the field refuses as the click leaves it, leaves Height as it is; Cancel discards the copy. Evidence: `dialogs::shapes::tests::{clicking_height_in_the_ellipse_dialog_copies_width_into_height, the_ellipse_height_button_copies_width_from_the_keyboard_and_keeps_the_link_round, enter_on_the_link_button_turns_the_link_on_without_pressing_ok, only_the_ellipse_dialog_has_the_height_button, copying_width_takes_only_a_width_that_reads}`. - **Cutting:** Eraser, Scissors, Knife, Mirror & Cut, Line Cut and Rectangle Cut (real geometry, compound paths keep their holes). The Eraser cuts fill-only open contours as areas (#6582), retaining fill outside its sweep or Alt-drag marquee. An eligible appearance has a visible non-None fill and no visible non-None stroke of positive width. Fill-only open compound members are cut together under their compound fill rule so holes stay empty. Cut pieces keep the existing path/compound representation and whole appearance. Bounds-fitted gradients on ordinary paths, compounds, groups and layers keep their original evaluated placement when it can be reproduced in the stored paint. Effects that draw replacement artwork, effect plug-ins, Rasterize, gradients along or across a stroke, and flattened placements or placements that cannot reproduce the original appearance keep their existing fitted behavior. Hidden Rasterize rows and hidden strokes with gradients along or across their paths do not block preserving a visible gradient. Already placed gradients and live-effect settings are retained; changes to a live effect's geometry can still move its paint. Path or Compound clipping masks keep every surviving contour in the same mask node; full erasure leaves an empty mask without promoting clipped contents. The mask identity, fill rule, appearance and parent child order are retained. Path Eraser uses the same preservation of the clipping role. Filled-and-stroked open paths retain the outline-splitting behavior from main. `crates/engine/tests/eraser_open_fill.rs` covers fixed and varied tips on fill-only open/closed geometry and raster output, compound holes and self-crossing fill, plus a painted-stroke outline control and clipping-mask split, empty-mask and Path Eraser cases. The same public target includes container-own paint and evaluated-placement regression cases. This deliberately scoped fix does not claim to repair filled-and-stroked open-path fill behavior. Scores and hours are unchanged. + With Alt released, Scissors hover and cuts snap as the Pen does: onto paths and anchors, into alignment and onto intersections (#6470). The hover guides and cut use the same snapped point; the cursor follows the current hover target. The existing Smart Guides, Snap to Point, Snap to Pixel and Snap to Grid options keep their precedence. Pixel Preview turns off Smart Guides through the tool view context; Snap to Point keeps its existing rules. Alt Add Anchor and the cut's endpoint selection below are unchanged. Source: `crates/tools/src/draw2/anchor.rs`. Headless regressions: `scissors_snaps_intersections_with_the_drawing_options`, `scissors_shows_paths_alignment_and_configured_anchor_snaps`, `scissors_cursor_and_press_use_current_snaps` and `scissors_clears_its_snap_when_the_interaction_ends_or_alt_takes_over` in `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/scissors_snap.rs`. A Scissors cut (`path.split`) leaves one of the two new end points selected and the rest of the path unselected, as [Cut paths](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/split-paths.html) and the "Split a path" section of the [CS3 user guide](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf) describe: the two end points lie on top of each other, and a Direct Selection drag from them moves the selected one with its handles and no other anchor. A closed path cut once stays one open path. The paths a Scissors cut (`path.split`) or Cut Path at Selected Anchor Points (`path.cutAtAnchors`) makes keep the source path's fill and stroke settings, and every stroke's alignment becomes Center in the same undo step, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/split-paths.html) describes. Resetting hidden stroke rows too, centering the strokes of a path's other subpaths and of the compound path a cut member belongs to are VectorCraft's own rules (`scissors_cut_paths_have_their_strokes_centered`, `cut_at_anchors_paths_have_their_strokes_centered`). While Alt is held, the Scissors tool works as the Add Anchor Point tool ([Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)): a click on a segment adds an anchor point without cutting (`path.insertAnchor`), and the pointer shows the Add Anchor Point cursor. When Alt is let go, a click cuts again. @@ -1375,7 +1395,7 @@ 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. 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`). The Transform panel's Shear field takes the same range, and the status bar shows the error for an angle Shear refuses, as VectorCraft's own rule ([shear objects with the Transform panel](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/shear-objects.html); `panels::transform::tests::the_shear_field_takes_angles_from_minus_359_to_359`, `the_shear_field_shows_the_error_for_an_angle_with_no_shear`). 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`). The Transform panel's Shear field takes the same range, and the status bar shows the error for an angle Shear refuses, as VectorCraft's own rule ([shear objects with the Transform panel](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/shear-objects.html); `panels::transform::tests::the_shear_field_takes_angles_from_minus_359_to_359`, `the_shear_field_shows_the_error_for_an_angle_with_no_shear`). Align and Distribute act on the anchor points selected with Direct Selection (#1641, fixes #1636). Align moves the points to the edge or center of their own bounds, of the artboard with Align to Artboard, or to a key guide; with a key anchor, the other points move to it and the key anchor stays in place. On a pixel-aligned path, the snap to the pixel grid that follows Align can move the key anchor when it ends up on a horizontal or vertical straight segment, which the snap puts on a whole or half point. Distribute spaces the points among themselves (`align_moves_selected_anchor_points`, `selected_anchor_points_align_to_a_key_guide`, `align_moves_the_other_points_to_the_key_anchor`). 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`. @@ -1403,6 +1423,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Live Corners:** drag a live rectangle's corner widgets (Selection or Direct Selection) to round all corners, with a radius readout; with Direct Selection, select corner anchors to show and round just those corners (#381). Each corner keeps its own radius and kind (Round, Inverted Round, Chamfer): Alt-click a widget to cycle the kind, double-click it for the Corners dialog, and the Properties and Transform radius fields set the selected corners (`object.setLiveShape {corners, radius, kind}`). A link toggle behind Corner Radius (the `singleCornerRadius` preference) switches the panels to a field for each corner of a live rectangle: Top Left, Top Right, Bottom Right and Bottom Left. Corners stay circular when the rectangle is scaled unevenly or along its own sides when rotated (the radius keeps its size, or scales by the mean scale with Scale Corners on); only a shear distorts them. On a rectangle that isn't square every corner is the same circle: a radius past half the shorter side stops there for all of them, the widgets sit on the corners as drawn and turn the edited corners red at that limit, CSS export writes the drawn radii, and rectangles saved stretched by older versions get circular corners when their corners are next set (#442). Live Corners work on any path's corners too, as on a rectangle's (#511): a star's, a live polygon's (which also shows them to the Selection tool, has a Corner Radius field in the Properties and Transform panels and keeps its radius as its sides change) and a pen path's, wherever two sides meet at an angle at an anchor that isn't smooth: curved sides too, trimmed to what the cut leaves of them (#1144). Direct Selection shows the widgets of every corner, or of the corners holding selected anchors; each corner is a circle tangent to both sides, drawn no larger than takes its cut halfway along its shorter side; a path keeps its uncut outline so its corners stay editable, and the same command, dialog, angle preference and View › Hide Corner Widget apply. With Direct Selection a click on a widget (no drag) selects its corner, as a click on the corner's anchor does, so the next drag on it rounds that corner alone; Shift-click toggles it (#1239). While a corner widget is dragged with the Selection tool the bounding box hides, so the rounding shows against the path alone (#1229). A round corner next to a curved side curves smoothly instead of sticking out of the shape (#1547, fixes #1512). View › Hide Edges hides the Live Corners widgets, the bounding box and the type widget, and the selection tools then do not answer a press on them or change the cursor over them. - **Polygon side widget:** a selected live polygon shows a small diamond beside the middle of the right side of its bounding box, with the Selection tool and with the Rectangle, Rounded Rectangle, Ellipse, Polygon and Star tools, while the bounding box and the edges are shown. Dragging the widget sets the polygon's side count, from 3 to 11, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/add-or-remove-sides-from-polygons.html) describes; typed counts in the Transform panel and `object.setLiveShape` still go from 3 to 1000. A drag down adds one side and a drag up removes one for every 12 screen pixels along the box's own vertical axis, and the pointer shows the count while measurement labels are on. A polygon of more than 11 sides keeps its count until the drag goes up, which gives it 11. The drag sends `object.setLiveShape {sides}`, so the polygon keeps its center, radius and rotation; the release adds one undo step when the count changed and none when it ends where it began, and Escape puts the count back. The widget's look and place, the drag direction, the step and the rule for more than 11 sides are VectorCraft's own (`crates/tools/src/sidewidget.rs`). + - **Hide/Show Shape Widgets:** with the Rectangle, Rounded Rectangle, Ellipse, Polygon or Star tool, the Control bar shows a Hide Shape Widgets button, which reads Show Shape Widgets while the widgets are hidden (`view.shapeWidgets {on?}`). [The help page](https://helpx.adobe.com/illustrator/using/live-shapes.html) describes this Control panel button, offered with any live shape drawing tool, as switching the on-canvas widgets of selected shapes off and on. While they are hidden, a selected live rectangle's or polygon's corner widgets, a live ellipse's pie widgets and a live polygon's side widget are not drawn, and the Selection tool and those shape tools do not answer a press, a double-click or the cursor on their place (a shape tool draws from there). The bounding box and its handles, the center point and Direct Selection's corner widgets (View › Hide Corner Widget) stay as they are. The setting is on by default, kept with the interface state across sessions and tool switches, and adds no undo step. Its scope beyond the shape tools, its default and what it leaves shown are VectorCraft's own rules (tests `hidden_shape_widgets_leave_the_bounding_box`, `the_shape_tools_control_bar_hides_and_shows_the_shape_widgets`, `shape_widgets_command_toggles_and_takes_on`, `hidden_shape_widgets_do_not_answer_a_shape_tool` and `hidden_shape_widgets_leave_direct_selections_corners`). - **Blend spine Anchor Point tool (#2544):** on a selected blend, dragging a spine corner makes symmetric Smooth handles; the tool displays and picks existing spine handles when switched to, drags one independently or retracts it on click, and clicking a point with handles retracts both. The spine is edited live without moving its key objects. Windows native canvas checks and screenshots reviewed: symmetric and independent handles, corner/retraction, Shift constraints and perpendicular reshaping, tool switching, key preservation, Undo/Redo, save/reopen, hidden handles and overlapping Path/Blend priority (PR #2643). Behaviour reference: [public path-editing documentation](https://helpx.adobe.com/illustrator/using/adjust-path-segments.html). - **Anchor Point tool, Alt-drag on a handle:** with the Anchor Point tool chosen, dragging a direction handle with Alt (Option) held links it with the opposite handle and makes the anchor smooth, on a path and on a selected blend's spine, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/create-smooth-paths-with-the-smooth-tool.html) describes; a drag without Alt still moves one handle on its own (`path.setHandle` and `object.blend.spine.moveAnchor` with `link`). VectorCraft's own rules: the opposite handle keeps its length; a retracted one is pulled out to the dragged handle's length where a segment leaves the anchor on its side and stays retracted at an open end; Shift with Alt keeps the 45° steps; an Alt-click still retracts the handle; the Pen with Alt keeps moving a handle on its own. Tests: `anchor_point_alt_drag_links_*` in `crates/tools/src/draw2/anchor/tests.rs`, `a_linked_handle_makes_the_anchor_smooth` in `crates/engine/src/tests/anchor_edit_work.rs`, `a_linked_spine_handle_makes_the_point_smooth` in `crates/engine/src/tests/blendspine.rs`. - **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`). @@ -1511,7 +1532,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur When more than 8 of its ids name objects in the document (after the list is cut to 100,000), `layer.highlight` in each mode (`set`, `add` and `toggle`) looks each row up in a set of the highlighted rows instead of searching the highlighted rows once for each row; with 8 or fewer it searches them. The Layers panel's preview of a Shift-click or Shift+Ctrl/Cmd-click range, before it sends the command, always looks the rows up in a set. The work grows in step with the number of rows. The rows, their order, the returned rows and the current layer are the same as before. Tests: `tests::layers::layer_highlight_matches_a_search_of_the_rows_for_each_id`, `tests::layers::highlighting_rows_keeps_their_order_with_repeated_unknown_and_excess_ids` and `widgets::drag::row_click_tests::a_large_range_applies_as_a_search_of_the_rows_for_each_id_does`; timing: `cargo test --release -p vectorcraft-engine --lib layer_highlight_timing -- --ignored --nocapture`. 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`). With several objects selected, Locate Object (and Locate Layer) finds the one frontmost in the stacking order, not the one selected last (help page: https://helpx.adobe.com/illustrator/desktop/manage-layers/create-and-organize-layers/locate-objects-in-the-layers-panel.html). Objects on different layers and sublayers are compared by the layers' order. As VectorCraft's own rules, a member selected along with its group counts as in front of the group, and an `id` given to `layer.locate` still wins (`locate_object_finds_the_frontmost_selected_object` in `crates/engine/src/tests/layers.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). +- **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). A selection the Selection tool holds by a point of a path's edge (a press on its stroke or, in Outline view, its outline, or on its fill within 6 screen points of the edge) snaps that point the same way, except that on a straight path the selection then slides along that path, the point staying on it, until its bounds line up with other objects, are spaced evenly with them or line up with a ruler guide, at most twice the Snapping Tolerance and not past the path's ends (#8568). 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 or held by its edge, and the slide along a straight path, are VectorCraft's own rules; 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`, `a_move_grabbed_by_an_anchor_lands_it_where_a_path_crosses_a_ruler_guide`, `a_move_held_by_a_paths_edge_lands_it_on_another_path`, `a_move_held_by_an_edge_on_a_straight_path_still_lines_its_bounds_up_along_it`, `a_move_held_by_an_edge_slides_only_within_the_path`, `a_move_held_by_an_edge_slides_along_a_straight_path_with_handles`, `a_move_held_by_an_edge_slides_onto_an_artboard_guide_it_reaches`, `a_move_held_by_an_edge_lands_it_where_paths_cross` and `a_copy_held_by_an_edge_slides_along_the_originals_edge`. 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`. Pixel Preview: with View › Pixel Preview on, the tools use no Smart Guides. Nothing snaps to Smart Guides or shows their guides, and Snap to Point acts as it does with Smart Guides off. View › Smart Guides keeps its setting and applies again when Pixel Preview is turned off. [Work with Smart Guides](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/work-with-smart-guides.html) says Smart Guides cannot be used while Pixel Preview is on. Tests: `tests::smartguides::pixel_preview_turns_smart_guides_off`, `canvas::tests::pixel_preview_stops_smart_guides_snapping_a_move`. @@ -1591,7 +1612,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Extrude & Bevel (both kinds) and Rotate keep the art's curves in the faces they draw, export and expand: caps and the edges of walls and bevels where they meet a cap are cubics with smooth anchors where the art's are, fitted within 0.001 pt in perspective and within the sampling tolerance on a bevel's inset. An edge of a twisted wall that is cut into pieces, a piece of curve that does not fit after 8 halvings, and the curves past 1,048,576 for one solid stay straight (VectorCraft's own values; [three-d.md](three-d.md#what-differs-from-the-public-documentation)). Tests `solid::tests::a_cap_keeps_the_curves_of_the_art`, `a_cap_in_perspective_fits_the_projected_curves`, `a_beveled_cap_and_its_walls_share_their_curves`, `twisted_beveled_tiny_and_degenerate_caps_keep_their_curves`. - 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 `<name>-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`. + - 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 `<name>-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)). The graphics wrapped around Revolve's side export the same way, as a texture of the side unrolled as the canvas lays it out, on a mesh of the side's triangles, with its end caps and cut sides plain. 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`, `a_revolved_sides_corners_lie_where_the_canvas_places_the_unrolled_side`, `a_revolved_sides_layout_matches_its_drawn_faces_at_every_turn`, `export_3d_paints_graphics_mapped_onto_a_revolves_side_in_every_format`, `a_partial_revolve_keeps_its_cut_sides_plain_beside_its_textured_side`. - 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)). @@ -1706,7 +1727,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Optical Margin Alignment and Roman Hanging Punctuation hang right-to-left paragraphs of point and area type, and type on a path whose first paragraph runs right to left, too. Auto aligns a right-to-left line at its right, or at the end bracket of a path, so it hangs there. A right-to-left line is read from right to left: where it hangs at its left margin, `."` ending it hangs both glyphs. Type on a path with right-to-left text that does not fit shows the longest start of its text whose glyphs fit, also where tracking gives a letter a negative advance and a shorter start does not fit; the rest overflows or flows to the next threaded object (VectorCraft's own rule). Without hanging punctuation, and on a straight path or with no spacing, every start is measured without arranging it on the path again. With hanging punctuation, or spacing on a curve, when a letter has a negative advance, at most 32 of the starts that could fit are arranged one by one from the longest; when none of them fits, a binary search over the rest shows a start that fits, which is not always the longest (`overflowing_rtl_type_on_a_path_shows_the_longest_start_that_fits`, `the_longest_rtl_start_on_a_path_is_found_without_arranging_each_start`, `the_longest_rtl_start_on_a_path_is_the_one_each_start_gives` and `rtl_type_on_a_curve_whose_letters_take_the_line_back_is_arranged_a_bounded_number_of_times` in `crates/text/src/tests/bidi.rs`). Right-aligned and centered type on a curve with Spacing is placed by what its glyphs take where the line ends up, so text that fits is not cut off at the end bracket (`on_path_aligned_spaced_text_that_fits_shows_whole` in `crates/text/src/tests.rs`). The Paragraph panel menu's Kinsoku Shori Type (`text.setFormat {kinsokuType}`, with the East Asian options) picks Push In First, Push Out First or Push Out Only for each paragraph: a character the Kinsoku Set keeps off a line's start or end is set on the line, with the line's gaps next to CJK characters closed by at most a tenth of an em each to fit, or moved to the next line with the character before it. Push Out First pushes in only when pushing out would leave the line more than an em short. Push Out Only is the default, the setting is saved only when it is not, and paragraph styles carry it. - The Paragraph panel menu's Bunri-Kinshi (`text.setFormat {bunriKinshi}`, with the East Asian options, and the East Asian Composition Settings section of Paragraph Style Options) keeps inseparable pairs on one line in each paragraph that has it: two em dashes, two ellipses, two two-dot leaders and the two halves of a vertical kana repeat mark (the pairs of W3C JLREQ's class cl-08, VectorCraft's set). Both composers and vertical type follow it, and justification adds no space inside a pair. It works with a Kinsoku Set only, is off by default and is saved only when on; editing the set of pairs is not available. + The Paragraph panel menu's Bunri-Kinshi (`text.setFormat {bunriKinshi}`, with the East Asian options, and the East Asian Composition Settings section of Paragraph Style Options) keeps inseparable pairs on one line in each paragraph that has it: two em dashes, two ellipses, two two-dot leaders and the two halves of a vertical kana repeat mark (the pairs of W3C JLREQ's class cl-08, VectorCraft's set). Both composers and vertical type follow it, and justification adds no space inside a pair. It works with a Kinsoku Set only, is off by default and is saved only when on; the built-in pairs can't be edited, and a custom Kinsoku set keeps its own inseparable sequences instead. + Type › Kinsoku Shori Settings… (`type.kinsokuSets.set`, with the East Asian options) creates, edits, renames and deletes the document's custom Kinsoku Shori sets, each a list of characters that may not start a line, characters that may not end one, hanging punctuation and inseparable sequences, new ones based on Hard, Soft, None or another set, with characters added by Unicode code point. The Paragraph panel's Kinsoku Set and paragraph styles choose a custom set for each paragraph (`text.setFormat {kinsoku: name}`); editing a set changes the paragraphs that use it, and deleting one gives them Hard. Importing and exporting sets is not available ([the help page](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/use-kinsoku-for-japanese-line-breaking.html)). `.ai` import reads each paragraph's Kinsoku Set (None, Hard or Soft), Kinsoku Shori Type, Burasagari and Bunri-Kinshi from the file's editable text: the paragraph's own setting, else its paragraph style's or a style that one is based on, else the document's default. A paragraph with a custom Kinsoku set takes its paragraph style's set, and the importer warns about it. A value it cannot read takes its paragraph style's value too. An `.ai` save writes all four settings for every paragraph, the normal paragraph style and the document's defaults, and lists the Hard and Soft sets, in the form that reader reads, so they reopen as set and are not reported as left out; Burasagari and Bunri-Kinshi keep their values under Kinsoku None. The Paragraph panel menu's Korean Line Break Anywhere (`text.setFormat {koreanLineBreakAnywhere}`, with the East Asian options, and the East Asian Composition Settings section of Paragraph Style Options) sets for each paragraph whether a line may break between any two Hangul syllables. When it is off, a word that contains Hangul breaks only at its spaces and after punctuation, or where the word is wider than the line, and takes no hyphen. New type has it off; paragraphs saved before the option read as on, so their lines do not move. The Paragraph panel menu's Reset Panel (`text.setStyle`, `text.setFormat` and `text.tabs.clear`) gives the selected type's paragraphs, or the paragraphs the Type tool's selection touches, Auto alignment, no indents or paragraph spacing, Hyphenate off with the default Hyphenation and Justification options, Auto direction, Bottom-to-Bottom Leading, the Line-end Punctuation Half Width Mojikumi Set, Regular burasagari, the Hard kinsoku set, Push Out Only, the Every-line Composer, Bunri-Kinshi, Roman Hanging Punctuation and Korean Line Break Anywhere off, no kashidas and no tab stops, as one undo step. @@ -1736,7 +1758,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur When a drag on the Tabs panel's ruler or a value typed in its X field moves a tab stop past another stop, the moved stop stays selected. With the Selection tool, the Tabs panel shows the ruler and stops of the first paragraph of the first selected text object, also when the text is inside a selected group or a shape is selected before it; a selection without text shows "No text selected". A stop set on that ruler is set on every selected text object and the text in selected groups, and other objects are left as they were. This is VectorCraft's own rule. Tests `panels::tabs::tests::the_ruler_shows_text_selected_after_an_object_that_is_not_text`, `the_ruler_shows_text_inside_a_selected_group`, `a_stop_added_on_a_mixed_selection_sets_every_selected_text` and `a_selection_without_text_shows_no_ruler`. The Tabs panel menu's Clear All Tabs (`text.tabs.clear`), Delete Tab and Repeat Tab (`text.tabs.set`) can be chosen while the panel's ruler shows tab stops. Delete Tab removes the stop selected on the ruler. Repeat Tab replaces the stops after the selected stop with up to 20 copies of it. The copies are spaced by the selected stop's distance from the stop before it, or from the paragraph's left indent (18 pt further in for each list level past the first) when it is the first stop, and no copy is placed at 2,000 pt or beyond. Clear All Tabs removes every stop, so the default stops every ½ inch apply again. -- **Interface languages, vertical type:** Preferences ▸ User Interface (or VectorCraft ▸ Language on macOS) picks Automatic (the system locale) or a registered language, persisted as `interfaceLanguage`. Translations come from per-language catalogs (`i18n/*.tsv`): Traditional and Simplified Chinese, Japanese, German (every `de-*` locale), Spanish (neutral international Spanish, for every `es-*` locale), French (every `fr-*` locale), Italian (every `it-*` locale), Russian (every `ru-*` locale) and Ukrainian (every `uk-*` locale), Catalan (every `ca-*` locale) and Polish (every `pl-*` locale; AI-drafted, native review pending) cover the whole interface, Czech every menu label; Czech, German, Greek, Spanish, French, Georgian, Hindi, Hungarian, Italian, Japanese, Korean, Vietnamese, Polish, Brazilian Portuguese, Russian, Simplified Chinese, Traditional Chinese, Swedish, Ukrainian, Finnish, Turkish, Catalan, Dutch and Danish also translate status-bar and error messages as they are shown (`@msg` templates, every message literal tested; the messages themselves stay English for agents); untranslated text stays English. Japanese and Chinese glyphs come from the craft-fonts build input (release builds) or the installed fonts, Czech, German, Spanish, French, Italian, Russian and Ukrainian ones from the bundled UI fonts. The web app follows the browser's languages (or `?lang=`). The Basic toolbar's Type button holds Vertical Type in its flyout. Vertical Type, Vertical Area Type and Vertical Type on a Path create vertical text (columns right to left, upright CJK glyphs and marks with `vert` alternates, Latin and longer numbers on their side, two- and three-digit numbers set as tate-chu-yoko in one em of the column (kept whole when justified), upright glyphs centred on the column (tracked or justified too), point type's anchor on the first column's centre line; on a vertical path, upright glyphs and tate-chu-yoko blocks face the path's start, and letters on their side are a quarter turn clockwise from them (with Skew, 3D Ribbon and Stair Step only on a path that runs to the right), in one column that Align to Path Baseline or Center centers on the path and that the caret and selection span); kinsoku applies to horizontal and vertical Japanese (Paragraph panel › Kinsoku Set, `text.setFormat {kinsoku}`: Hard, the default, keeps closing marks, iteration marks, the prolonged sound mark and small kana off the line start and opening brackets off its end; Soft lets 々, ー and small kana start a line as JLREQ's level 3 rules do; None turns it off), and justified Japanese lines spread their room between characters (not inside Latin words); Paragraph panel › Mojikumi Set (shown with Preferences › Type › Show East Asian Options, `text.setFormat {mojikumi}`): None or Line-end Punctuation Half Width (new type's default, as in Illustrator; older documents and imported text keep None) shares one half-em space between consecutive punctuation, sets a closing mark ending a line half width and an opening bracket starting a line flush with its start (a paragraph's first line at its first-line indent, JIS X 4051's principle in JLREQ 3.1.5), and puts a quarter em between Japanese and Latin letters or digits; Paragraph panel menu › Top-to-Top / Bottom-to-Bottom Leading measures leading from em box top to top (area type's first line touches the frame) or from baseline to baseline (new type in a Japanese interface starts top to top, with em box centre character alignment, #432); Paragraph panel menu › Burasagari None / Regular / Force (`text.setFormat {burasagari: "none"|"standard"|"forced"}`) hangs an East Asian comma or full stop (、。,.、。) ending an area type line outside it, Regular (new type's default) when it doesn't fit and Force always (the rest of the line then fills the measure; closing brackets and Latin punctuation don't hang); Character panel menu › Character Alignment (with the East Asian options; `text.setFormat` or `text.setRangeStyle {charAlign}`) lines characters smaller than the largest on their line up on the Roman baseline, the em box top/right, centre or bottom/left, or the ICF (ideographic character face) top/right or bottom/left, from the font's BASE table or, without one, the average ink box of some ideographs and kana; Proportional Metrics (the same menu; `{proportionalMetrics}`) sets full-width glyphs on the font's proportional widths (OpenType `palt`) in horizontal type and upright glyphs on its proportional heights (`vpal`, shaped top to bottom; fonts without vertical metrics keep their cells) in vertical type, and Line-end Punctuation Half Width takes nothing more off the punctuation they re-spaced; Type ▸ Type Orientation switches existing text; caret, selection, hit testing and arrow keys follow the writing direction. Vertical text exports to PDF as real text and to SVG as outlines. The interface is available in Polish (`pl`): menus, panels, dialogs and messages, with one/few/many plurals; AI-drafted, native review pending (#1498). +- **Interface languages, vertical type:** Preferences ▸ User Interface (or VectorCraft ▸ Language on macOS) picks Automatic (the system locale) or a registered language, persisted as `interfaceLanguage`. Translations come from per-language catalogs (`i18n/*.tsv`): Traditional and Simplified Chinese, Japanese, German (every `de-*` locale), Spanish (neutral international Spanish, for every `es-*` locale), French (every `fr-*` locale), Italian (every `it-*` locale), Russian (every `ru-*` locale) and Ukrainian (every `uk-*` locale), Catalan (every `ca-*` locale) and Polish (every `pl-*` locale; AI-drafted, native review pending) cover the whole interface, Czech every menu label; Czech, German, Greek, Spanish, French, Georgian, Hindi, Hungarian, Italian, Japanese, Korean, Vietnamese, Polish, Brazilian Portuguese, Russian, Simplified Chinese, Traditional Chinese, Swedish, Ukrainian, Finnish, Turkish, Catalan, Dutch, Danish and Indonesian also translate status-bar and error messages as they are shown (`@msg` templates, every message literal tested; the messages themselves stay English for agents); untranslated text stays English. Japanese and Chinese glyphs come from the craft-fonts build input (release builds) or the installed fonts, Czech, German, Spanish, French, Italian, Russian and Ukrainian ones from the bundled UI fonts. The web app follows the browser's languages (or `?lang=`). The Basic toolbar's Type button holds Vertical Type in its flyout. Vertical Type, Vertical Area Type and Vertical Type on a Path create vertical text (columns right to left, upright CJK glyphs and marks with `vert` alternates, Latin and longer numbers on their side, two- and three-digit numbers set as tate-chu-yoko in one em of the column (kept whole when justified), upright glyphs centred on the column (tracked or justified too), point type's anchor on the first column's centre line; on a vertical path, upright glyphs and tate-chu-yoko blocks face the path's start, and letters on their side are a quarter turn clockwise from them (with Skew, 3D Ribbon and Stair Step only on a path that runs to the right), in one column that Align to Path Baseline or Center centers on the path and that the caret and selection span); kinsoku applies to horizontal and vertical Japanese (Paragraph panel › Kinsoku Set, `text.setFormat {kinsoku}`: Hard, the default, keeps closing marks, iteration marks, the prolonged sound mark and small kana off the line start and opening brackets off its end; Soft lets 々, ー and small kana start a line as JLREQ's level 3 rules do; None turns it off), and justified Japanese lines spread their room between characters (not inside Latin words); Paragraph panel › Mojikumi Set (shown with Preferences › Type › Show East Asian Options, `text.setFormat {mojikumi}`): None or Line-end Punctuation Half Width (new type's default, as in Illustrator; older documents and imported text keep None) shares one half-em space between consecutive punctuation, sets a closing mark ending a line half width and an opening bracket starting a line flush with its start (a paragraph's first line at its first-line indent, JIS X 4051's principle in JLREQ 3.1.5), and puts a quarter em between Japanese and Latin letters or digits; Paragraph panel menu › Top-to-Top / Bottom-to-Bottom Leading measures leading from em box top to top (area type's first line touches the frame) or from baseline to baseline (new type in a Japanese interface starts top to top, with em box centre character alignment, #432); Paragraph panel menu › Burasagari None / Regular / Force (`text.setFormat {burasagari: "none"|"standard"|"forced"}`) hangs an East Asian comma or full stop (、。,.、。) ending an area type line outside it, Regular (new type's default) when it doesn't fit and Force always (the rest of the line then fills the measure; closing brackets and Latin punctuation don't hang); Character panel menu › Character Alignment (with the East Asian options; `text.setFormat` or `text.setRangeStyle {charAlign}`) lines characters smaller than the largest on their line up on the Roman baseline, the em box top/right, centre or bottom/left, or the ICF (ideographic character face) top/right or bottom/left, from the font's BASE table or, without one, the average ink box of some ideographs and kana; Proportional Metrics (the same menu; `{proportionalMetrics}`) sets full-width glyphs on the font's proportional widths (OpenType `palt`) in horizontal type and upright glyphs on its proportional heights (`vpal`, shaped top to bottom; fonts without vertical metrics keep their cells) in vertical type, and Line-end Punctuation Half Width takes nothing more off the punctuation they re-spaced; Type ▸ Type Orientation switches existing text; caret, selection, hit testing and arrow keys follow the writing direction. Vertical text exports to PDF as real text and to SVG as outlines. The interface is available in Polish (`pl`): menus, panels, dialogs and messages, with one/few/many plurals; AI-drafted, native review pending (#1498). The Russian catalog (`crates/ui-egui/src/i18n/ru.tsv`) has 1,811 more `@msg` rows, for status and error messages of commands, scripts and file import and export, 3,444 `@msg` rows in all counted on 2026-11-13 (`russian_translates_command_script_and_file_messages` in `crates/ui-egui/src/i18n/tests.rs`). Scores and estimates are unchanged. With Line-end Punctuation Half Width, both composers measure a line with its last character set as narrow as Mojikumi sets it ([the help page](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/use-mojikumi-for-japanese-text-composition.html)): a closing bracket, comma or full stop that fits at half width ends the line, and the character before it no longer goes to the next line with it. A mark that already lost its half to the punctuation after it and a line that ends in a hyphen take nothing more off, and the quarter em between Japanese and Latin text counts only where the line ends there. Kinsoku Shori Type and Burasagari Regular measure lines the same way; right-to-left lines and Mojikumi None break as before. In a frame that is not a rectangle, or with text wrap, a line's first word is measured as it is set (an opening bracket at its start flush, its last character narrowed) when layout looks for a line wide enough for it, and it ends only where the line may break, so kinsoku keeps an opening bracket with the character after it and a No Break run counts whole (`crates/text/src/layout/wrapping_tests.rs`, `crates/text/src/tests/vertical.rs`). Scores and estimates are unchanged. Burasagari ([the help page](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)) leaves a right-to-left paragraph's comma or full stop inside its line, which then ends at a break where it fits with the mark, and in a left-to-right line with right-to-left text and a tab it hangs a mark only when the mark is drawn at the line's right end and the rest of the line fits as drawn; otherwise the line ends at the latest break that fits as drawn. Both are VectorCraft's own rules (`crates/text/src/layout/wrapping_tests.rs`, `crates/text/src/tests/hang.rs`). Scores and estimates are unchanged. @@ -1811,6 +1833,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Image Trace, Flat Logo with a color between two others:** an anti-aliased edge pixel between black and white is read as a blend of black and white, not of black and a gray that lies between them, when the flat areas around it and the pixels beside it show that edge, so a black disc beside a gray square on white, with sharp edges or edges blurred by up to about half a pixel, traces with one gray path, the square, instead of the square plus 8 to 24 gray slivers around the disc with the colors found or named exactly; on edges blurred by 1 to 3 pixels, the pixel also counts as on that edge when paths of up to 5 steps through pixels that keep getting darker and lighter reach past the gray both ways, and black and white then lie as near as the steps to them, so the same disc and square trace with one gray path at blurs of 1 and 2 pixels and with at most 4 slivers of up to 3 pixels in a light gray at 1.5 pixels, where up to 33 gray paths were traced before (at a blur of 3 pixels with the colors named, a gray of 200 leaves 4 slivers with no area and a light gray of 230 leaves 8 small slivers, where 11 and 14 gray paths were traced before; pixel noise of a level or more can still leave gray slivers); when the first step toward black or white already comes to that color, the path the other way stops at a pixel of the gray, so with edges blurred by 0.6 pixels a gray band 3 to 8 pixels wide along black traces gray at no fewer than 4 of every 5 of its pixel centers; with sharp edges, gray strokes two and three pixels wide beside black stay gray (a soft-edged gray stroke about two pixels wide lying along black traces as black and white, and a short one about three pixels wide can lose most or all of its gray); on edges blurred by a pixel or more, a soft-edged gray band up to 4 pixels wide along black traces as black and white, with gray at no more than 1 of every 16 of its pixel centers, at blurs of 1.5 and 2 pixels, a light gray stroke 2 pixels wide and 2 pixels from black, blurred by 1.5 pixels, traces gray at about 10 of the 34 pixel centers along its middle and one 4 pixels away at about 25, and a soft-edged gray stroke running out of black, blurred by 1 or 1.5 pixels, loses 3 or 4 of the 16 pixel centers along its middle nearest black; a one-pixel gray line of at least 13 touching pixels between black and white stays gray (a shorter one, or one that falls between pixels or is blurred, traces as black and white); code-drawn tests in `crates/trace`. - **Image Trace, Flat Logo with a color beyond both colors of an edge:** an edge pixel between a gray panel and a charcoal disc on a paler gray ground is read as a blend of the panel and the disc, not of the ground and the disc, when the pixels beside it lie on each side of it, none lies past the panel toward the ground, and lighter pixels lead from it to the panel's color or to a flat area of the panel, so the disc traces with three paths, one per color, with the colors found or named, instead of with 28 slivers of the ground around it when its edges are sharp and one sliver when they are blurred by 0.7 pixel (an edge blurred by a pixel or more can still leave slivers of the ground); the pixels of a pale line on the disc, one pixel wide, blurred over three pixels or falling between two pixels, and the edge of a gap of the ground's color between the disc and the panel keep the ground in their blends; code-drawn tests in `crates/trace`. - **Image Trace, Keep Colors:** `"keepColors": ["#rrggbb", …]` traces only the palette colors near a listed color (Abutting: each with the paths the trace of every color gives it; Overlapping: not reaching under the colors left out), in Black and White, Grayscale and Color; code-drawn tests in `crates/trace` and `crates/engine`. +- **Image Trace, Split View:** VectorCraft's own View shows the source image on the part of the image left of a divider and the tracing result everywhere else; the Selection tool drags the divider on the canvas (one undo step, Escape cancels), the Image Trace and Properties panels set it with a Divider slider, and `imageTrace.setView {view: "split", split}` sets it for agents, while exports, printing and Expand keep the result; tests in `crates/render`, `crates/engine`, `crates/tools` and `crates/ui-egui`. - **Advanced art:** live Blends (steps/distance/smooth colour, editable spine, anchor-targeted Blend tool, faithful interpolation, knockout), Envelope Distort (warp/mesh/top object, Reset, full Envelope Options, mesh handles, Edit Contents; type, images, symbols, gradients, patterns and appearance distorted everywhere), Liquify tools with options and pen pressure, Puppet Warp with rotating pins, Perspective Grid with presets, movable planes and projected type (choosing a perspective tool shows the grid; Hide Grid hides it with the tool still chosen), Gradient Mesh, Shape Builder (stroke-only open paths and lines cut the regions they cross and enclose regions of their own, and regions they bound merge without seams where the lines cross at rounded coordinates (#893); filled open paths count as closed; erase mode while Alt/Option is held: a minus pointer, red highlights of what will go, a click or drag deletes the regions touched, the pieces of open lines and the edges (outline pieces between the points where paths meet, opening their paths there) it passes over, one undo step, `shapeBuilder.merge {erase}` and `shapeBuilder.regions` edges over MCP), Live Paint (every path an edge, open lines included), Image Trace (12 presets, colour layers traced in parallel; a trace past two million anchor points is refused with advice rather than running out of memory, an image over 64 megapixels is traced scaled down to that size (aspect kept, paths at the image's own size) and one over 192 megapixels is refused, and a selection too large to outline shows its bounds (#525); Object › Image Trace › Make and Make and Expand trace at once with the Default preset, #543; with an image selected the Control bar and the Properties panel show Image Trace, whose arrow traces with any preset, Mask (`object.maskImage`: a clipping path on the image's outline, selected so its handles crop), Crop Image (a crop box on the image, starting on its part over the artboard, dragged by its handles or inside it, the outside dimmed, with X/Y/W/H, Apply and Cancel in the Control bar, Enter and Escape, #734; an image that isn't turned or skewed, isn't CMYK and can be read at its recorded size is cut from its own pixels when the crop edges fall on its pixel grid, copied as they are without resampling; any other image is drawn, #5534; `object.cropImage {rect}` for agents, `{trim: true}` cuts an image to its pixels that aren't fully transparent, pixel for pixel) and Embed or Unembed in place of Fill and Stroke; with an Image Trace object selected, its Preset (choosing another traces again), View, the Image Trace panel and Expand, plus Release in Properties; the five View modes (Tracing Result, with Outlines, Outlines, Outlines with Source Image, Source Image) redraw a trace on screen without tracing again, are saved with it and `imageTrace.setView` sets them, while exports and Expand keep the result; the panel's Advanced section is a header that stays open or closed as it was left (part of #641); Color mode's Palette: Limited, Full Tone (as many colours as the tones need, Less … More, split into at least one color per step of Color detail before colors that look alike merge), Automatic (flat art with its own colours, else as many as the tones need; a heuristic) and Document Library (the most used colours of the document's swatches or a swatch library, filled with the swatch colours as they are), part of #641; Advanced › Create: Fills and/or Strokes, where lines up to the Stroke width trace as stroked centre lines (distance transform, thinning, a skeleton graph with spurs pruned, curve fitting; one width per line; without Fills, wider areas become stroked outlines), part of #641), pattern swatches with pattern editing mode, live Repeat (radial/grid/mirror). A single selected mirror repeat shows a prominent axis with a center move handle and two rotation handles. Drag the line or center to change spacing, or an end to change angle; Shift snaps rotation to 45°. The original artwork stays in place, the reflected copy previews live, Escape cancels and each drag takes one undo step through `object.repeat.options`. Controls follow zoom/view rotation and hide with edges or the bounding box. Engine and headless canvas regressions passed for gestures, history and visibility; native move, rotation and Escape screenshots were reviewed. [Public mirror-repeat reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-mirror-repeat-options.html). A single selected grid repeat shows a handle below the grid for rows, one right of it for columns and one past its bottom-right corner for both, and sliders between its first two columns and rows for the horizontal and vertical spacing; the source keeps its size, each drag is one undo step and Escape cancels it ([public grid-repeat reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-grid-repeat-options.html), #2691). Object › Expand turns radial, grid and mirror repeats into groups of their instances (#1765, #1756). While Crop Image shows its box, the Control bar also sets the cropped image's resolution (PPI: a list of 72, 96, 150, 200 and 300 ppi with the ones above the image's own disabled, or a typed value; at most the image's own, or 300 ppi for a linked image ([Crop Image](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=352))), a reference point that X and Y name and that W and H resize about, and a link that keeps W and H in proportion; `object.cropImage {ppi}` resamples the cut pixels and refuses a resolution above the limit, and `tool.setOption` sets `ppi`, `reference` and `linked` ([Crop images](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/crop-images-in-illustrator.html)). The list's resolutions and the default (the image's own resolution, the center, unlinked) are VectorCraft's own. Choosing the Blend tool again while it is active (its toolbar button, W or `tool.select`) finishes the blend: the object clicked first is dropped and the next click no longer adds to the blend just made, so the click after it starts a new blend ([Blending objects](https://web.archive.org/web/20241217212108/https://helpx.adobe.com/illustrator/using/blending-objects.html)). @@ -1873,13 +1896,14 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur 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`. + Color Group Options… in the Swatches panel menu names the selected color group: its dialog shows the group's name in a Name field, and OK renames the group (`swatch.renameGroup`, `ui.colorGroupOptions`) while its swatches, their colors and the art linked to them stay as they are ([help page](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/create-color-groups-in-the-color-guide-panel.html)). VectorCraft's own rules: the item is available only when that one group is the whole panel selection; the name is trimmed; a name that is empty or that another color group or a swatch has (swatches and groups share one set of names) is an error and keeps the dialog open; a rename is one undo step, and the group's own name records none. Double-clicking a group's folder and the options button still open Edit or Apply Color Group. Evidence: `rename_group_renames_only_the_group_in_one_undo_step` in `crates/engine/src/tests/swatchcmds.rs`, `renames_the_group_and_keeps_a_refused_name_open` in `crates/ui-egui/src/dialogs/color_group_options.rs` and `color_group_options_opens_on_a_sole_selected_group` in `crates/ui-egui/src/panels/swatches/tests.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. - **Missing library files:** a persistent swatch or graphic style library panel whose file is gone at startup reopens and stays in the preferences, showing the file's path with Locate Library… (`ui.libraryPanel.locate`), which reads the file from where it is now into the same panel. - **Swatch library and Recolor Artwork parameters:** the `swatch.library.*` commands, `swatch.resetDefaults`, the graphic style library save, load and add, the `recolor.*` commands and `color.harmony`'s `limitTo` refuse parameters of the wrong form, such as `names: "Grays"`, `limitTo: 5` or `includeImages: "false"`. Errors name the parameter, except that a `limitTo` that is not a string, such as `5`, gets an unknown-library error. A `null` counts as left out except for `recolor.apply`'s `model`, which must be a string when given. - - **Color Wheel panel (part of #978):** Window › Color Wheel shows the Fill and Stroke proxy beside a hue ring around a square with saturation across and brightness up. It edits what the Color panel's sliders edit (the active proxy's color, the selected gradient stop or freeform point) through the same paint commands, and a drag is one undo step. Alt paints the other proxy, and Shift steps the ring by 45°. A pick goes from display sRGB into the working RGB space; an RGB, CMYK or Lab color keeps its model, and a Gray color or a tint of a global swatch becomes a process color in the document's color mode. A click gives the ring or the square the keyboard focus, and the arrow keys then step the color; both report their names and values to screen readers, and the Color Picker's color field takes the same keys. The panel menu's Box View puts a box in the wheel's place: a color field with a channel strip at its right for Hue, Saturation, Brightness, Red, Green or Blue (Box Channel), on the Color Picker's axes, kept with the preferences (`ui.colorWheel`); the strip and the Color Picker's channel slider take the arrow keys after a click. Scores and estimates are unchanged. + - **Color Wheel panel (part of #978):** Window › Color Wheel shows the Fill and Stroke proxy beside a hue ring around a square with saturation across and brightness up. It edits what the Color panel's sliders edit (the active proxy's color, the selected gradient stop or freeform point) through the same paint commands, and a drag is one undo step. Alt paints the other proxy, and Shift steps the ring by 45°. A pick goes from display sRGB into the working RGB space; an RGB, CMYK or Lab color keeps its model, and a Gray color or a tint of a global swatch becomes a process color in the document's color mode. A click gives the ring or the square the keyboard focus, and the arrow keys then step the color; both report their names and values to screen readers, and the Color Picker's color field takes the same keys. The panel menu's Box View puts a box in the wheel's place: a color field with a channel strip at its right for Hue, Saturation, Brightness, Red, Green or Blue (Box Channel), on the Color Picker's axes, kept with the preferences (`ui.colorWheel`); the strip and the Color Picker's channel slider take the arrow keys after a click. The panel menu's Show Harmony marks the other colors of a harmony rule (Harmony Rule) on the ring; the markers follow the current color, and a click on a marker applies its color (`ui.colorWheel {harmony, harmonyRule}`). Scores and estimates are unchanged. - **Colour:** a Color Picker (colour field, H/S/B/R/G/B channel slider, HSB/RGB/Lab/CMYK fields, hex, web-only snapping, out-of-gamut correction); the Color panel shows a selected colour in its own model and, with nothing selected, the new-art defaults in the mode picked last, which it keeps between sessions; Alt-click paints the other proxy; proxies look through groups and show "?" for mixed paint; Invert, Complement, Apply Last Color (`,`) and Apply Last Gradient (`.`) keep the colour model; every paint command feeds the recent colours. The Color Guide has 21 harmony rules, Steps and Variation options and Limit to Library. Adjust Color Balance (its Global mode shifts tints) and Saturate preview live; Edit Colors and Recolor also reach meshes, images and patterns. Recolor Artwork has colour reduction, five recolour methods, presets, Limit to Library, a colour-wheel Edit tab and Edit Color Group; a local Color Themes panel saves five-colour themes. Fill/Stroke chips open swatch and mixer popovers (the Properties panel has the Control bar's Fill and Stroke chips, Stroke link and weight spinner, with nothing selected too), panels have Illustrator's Window menu keys (Align Shift+F7, Transform Shift+F8, Pathfinder Cmd+Shift+F9, Layers F7, Character Cmd+T…; every panel can be given one in Edit › Keyboard Shortcuts), and Eyedropper Options pick up and apply chosen attributes (Alt and Shift+Alt, image pixels). An ICC CMYK profile converts straight into the RGB working space (not through sRGB, so a wider space such as Wide Gamut RGB keeps colours sRGB can't hold) with the colour settings' black-point compensation, on the canvas and in RGB exports alike (the built-in Generic CMYK compensates both ways, so RGB black separated to a rich black displays as black again). Fills and strokes can overprint (Attributes panel, Overprint Black options), and CMYK documents blend in inks on screen, in PDF and when flattening. Document Color Mode converts the art, symbols, pattern tiles and swatches through the colour settings: Gray stays Gray, RGB grays separate into light grays in cyan, magenta and yellow only, darker four-color grays and a rich black, or go on the black plate only with `grays: "black"` (also for `document.open {colorMode}`). **Color panel spectrum mode tooltip (part of #7235):** hovering the spectrum names the displayed mode (Grayscale, RGB, HSB, CMYK, Web Safe RGB or Lab), including after Shift-clicking to switch modes and with Show Options or Hide Options. Hovering changes no paint or undo history. Spectrum rendering and vertical resizing remain open. Evidence: `spectrum_tooltip_names_its_displayed_mode` and `spectrum_tooltip_follows_shift_cycle_without_painting` in `crates/ui-egui/tests/color_working_components.rs`. Scores and estimates unchanged. @@ -1889,6 +1913,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Unchecking Show Recent Colors in the Color panel's menu hides its Recent Colors row, and checking it shows the row again ([Select colors using the Color panel](https://helpx.adobe.com/illustrator/desktop/manage-colors/select-and-adjust-colors/select-colors-using-the-color-panel.html)). In VectorCraft the item is checked by default and kept between sessions, applied colors still join the list while the row is hidden, Hide Options hides the row either way, and the Swatches panel keeps its row (`ui.colorPanel {recentColors}`). Tests: `show_recent_colors_hides_and_shows_the_row` in `crates/ui-egui/src/panels/color/tests.rs`. The Swatches panel's menu has its own Show Recent Colors item: unchecking it hides the panel's Recent Colors row and checking it shows the row again ([Color Enhancements in Illustrator](https://community.adobe.com/announcements-651/color-enhancements-in-illustrator-816797) puts recent colors in the Color and Swatches panels; [Select colors using the Color panel](https://helpx.adobe.com/illustrator/desktop/manage-colors/select-and-adjust-colors/select-colors-using-the-color-panel.html) hides them with Show Recent Colors in the panel menu; a [community thread](https://community.adobe.com/questions-652/swatches-disappear-in-swatches-panel-when-switching-between-documents-in-29-7-1-on-macos-816823) turns it off from the Swatches panel). In VectorCraft it is checked by default, kept between sessions apart from the Color panel's, and applied colors still join the list while the row is hidden (#6617). Tests: `show_recent_colors_hides_and_shows_the_swatches_row` in `crates/ui-egui/src/panels/swatches/tests.rs`. A Recent Colors chip in the Color or Swatches panel drags into the Swatches panel's list to become a swatch of its color, in its color model, as one undo step ([Select colors using the Color panel](https://helpx.adobe.com/illustrator/desktop/manage-colors/select-and-adjust-colors/select-colors-using-the-color-panel.html)). In VectorCraft a chip dropped on a color group or one of its swatches joins that group, anywhere else in the list it joins the ungrouped swatches at the end, a color that is already a swatch is added again under another name, and dragging a chip does not paint the selected art (`swatch.new`). Tests: `a_recent_color_dragged_onto_the_list_becomes_a_swatch` and `a_recent_color_dragged_from_the_color_panel_becomes_a_swatch` in `crates/ui-egui/src/panels/swatches/tests.rs`. + A color dragged into the Swatches panel with Cmd (macOS) or Ctrl (Windows) held becomes a spot color swatch ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-colors/use-swatches/create-spot-color-swatches.html) gives this drag from the Color panel as one way to make a spot color). VectorCraft's own rules: Ctrl works on Linux too, and Cmd/Ctrl and Alt are read from the release itself, so a key let go in the same frame after the release does not change the drop; the Fill and Stroke squares, Recent Colors chips and Color Guide colors drag the same way; the new swatch is global, keeps the dragged color's model, joins the color group it is dropped on (anywhere else, the ungrouped swatches at the end), takes a name of its own and is one undo step that paints no art; a tint dragged this way becomes a new spot color of the tinted color, and its base swatch stays as it is; a drop uses the color the drag showed, also when the tint's base swatch changes before the release; with Alt also held, a color dropped on a solid swatch replaces it with the color the drag showed and makes no spot color, and one dropped on Registration or a tint swatch becomes a spot color; Alt without Cmd/Ctrl replaces a solid swatch with a dragged tint as before, taking the tint of its base swatch as the base is at the release; gradients, patterns, Registration and swatches dragged within the panel are not made spot colors (`swatch.new {spot: true}`). Tests: `a_color_cmd_dropped_on_the_panel_becomes_a_spot_swatch`, `a_color_cmd_dropped_on_empty_list_space_becomes_a_spot_swatch`, `a_cmd_drop_of_other_paints_or_rows_makes_no_spot_color`, `cmd_drops_of_tints_and_with_alt_follow_the_replacement_rule`, `a_cmd_dropped_tint_makes_its_spot_from_the_captured_color`, `a_tint_alt_dropped_on_a_swatch_replaces_it_with_the_captured_color`, `a_tint_alt_dropped_without_cmd_keeps_the_tint_paint` and `a_drop_follows_the_modifiers_of_its_release` in `crates/ui-egui/src/panels/swatches/tests.rs`. A Cmd/Ctrl-click on the Color panel's spectrum applies Complement and a Cmd/Ctrl+Shift-click applies Invert to the active Fill or Stroke (`paint.complement`, `paint.invert`); with Alt also held, the click recolors the inactive one, as the reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) list them. The Color panel spectrum grows into the vertical space of a resized panel, with Show Options or Hide Options (#8005); compact auto-fit flyouts and embedded mixers retain their previous height. Regression: panels::color::tests::the_spectrum_grows_with_the_color_panel. Scores and estimates unchanged. 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`. @@ -1908,6 +1933,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Recolor Artwork Find:** the Assign tab's Find button finds the colors of the selected rows in the art ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html)): while it is on, their art shows as the preview shows it and the rest of the selected art shows dimmed, until a second click ([archived help, Recolor Artwork](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=149)). VectorCraft's own rules: a dimmed color is a 25% tint of its current color (or the nearest lighter tint when that one is a color a selected row lists), a color a selected row also lists is not dimmed, and Find records no undo step. `findColors` is the dialog field. Tests: `find_dims_the_colors_of_the_rows_not_selected` and `find_shows_the_selected_rows_art_and_dims_the_rest` in `crates/ui-egui/src/dialogs/recolor.rs`. Scores and estimates unchanged. - **Recolor Artwork color groups list:** a list on the right of the dialog shows the document's color groups, and the Show Color Groups button beside the tabs shows or hides it. A click on a group makes it the group being edited, and the rows take its colors. Save Changes rewrites the selected group with the new colors, New Color Group saves them as a new group, and Delete removes the selected group; the Swatches panel shows each change ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html)). VectorCraft's own rules: when the art has colors of the group, Save Changes and OK keep the group's swatches in order, and a swatch no row lists keeps its color; an excluded row leaves its swatch its own color; after a save with art, the rows' new colors take the Global Adjust, which goes back to 0%. `group`, `groupStorage` and `groupAction` are the dialog fields. Tests: `the_color_groups_list_selects_saves_and_deletes_groups`, `a_group_picked_in_the_list_recolors_the_art` and the `saving_a_group_` tests in `crates/ui-egui/src/dialogs/recolor.rs`, and `edit_color_group_with_its_own_colors_records_no_undo_step` and `edit_color_group_with_its_own_color_keys_keeps_the_colors` in `crates/engine/src/tests/swatchcmds.rs`. - **Recolor Artwork New Row:** the Assign tab's New Row button adds a row with no current colors, so current colors can be moved into it and take its new color ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html), [Assign new colors to selected artworks](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/assign-new-colors-to-selected-artwork.html)). VectorCraft's own rules: the row goes above the first selected row (at the top when none is selected) with that row's new color and becomes the selection, and Merge with it as the first selected row moves the other rows' colors into it. The button needs selected art. An empty row recolors nothing, does not count toward Colors, adds no library swatch and gives a rewritten color group no color. While it is empty, Save All Colors and a new color group saved from colors alone leave its new color out, the Edit tab's wheel, bars and chips do not show it and its sliders edit the base color instead, the harmony rules and linked moves leave its new color as it is, and the Color Theme Picker gives it no color. Tests: `a_new_row_goes_above_the_selection_and_takes_merged_colors`, `an_empty_row_gives_the_group_no_color`, `an_empty_row_gives_a_new_group_no_color`, `an_empty_row_takes_no_harmony_or_wheel_color`, `theme_picks_leave_an_empty_row_out`, `save_all_colors_leaves_an_empty_row_out` and `colors_merged_into_a_new_row_take_its_new_color` in `crates/ui-egui/src/dialogs/recolor.rs`, `an_empty_row_recolors_nothing` and `an_empty_row_adds_no_swatch_and_no_group_color` in `crates/engine/src/tests/recolor.rs`. + - **Recolor Artwork Undo Changes and Redo Changes:** two buttons beside the Color Theme Picker go back and forward one color edit made in the open dialog, and Undo Changes has nothing to undo after the dialog is opened again ([Recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/recolor-options-overview.html)); `ui.recolorUndo` and `ui.recolorRedo` run them. VectorCraft's own rules: the dialog's history is separate from the document's, which changes when OK records one undo step and when Save All Colors or Save Prominent Colors adds a color group at once as its own undo step, which Cancel and Undo Changes leave in place; a drag is one step, fields set with `ui.dialog.set` before the next frame with the pointer up or the next step are one step, Reset is a step of its own, a new edit leaves nothing to redo, selecting another color group or Save Changes leaves nothing to undo or redo and an edit after either is a step back to the fields as they were then, a button with no step to go to is disabled, and the dialog keeps at most 64 steps and 4 MiB of them, always keeping the newest step. Tests: `undo_and_redo_changes_step_through_the_dialogs_own_edits`, `a_drag_is_one_step_of_undo_changes`, `undo_changes_reverses_reset`, `the_recolor_undo_and_redo_commands_step_the_open_dialog`, `the_recolor_undo_and_redo_commands_preview_the_step`, `an_edit_with_the_pointer_down_from_the_first_frame_is_a_step` and `rows_and_weights_set_before_the_art_is_read_are_no_step` in `crates/ui-egui/src/tests/recolor.rs`, and `undo_changes_keeps_a_bounded_history` and `another_group_or_save_changes_leaves_nothing_to_undo` and `an_edit_right_after_another_group_is_a_step` and `an_unchanged_save_changes_leaves_nothing_to_redo` in `crates/ui-egui/src/dialogs/recolor.rs`. Scores and estimates unchanged. - **Edit Colors parameters:** `edit.colors.saturate` needs a number `intensity`, the value from -100% to 100% that Saturate takes ([Adjusting colors](https://web.archive.org/web/20230128232631/https://helpx.adobe.com/illustrator/using/adjusting-colors.html)), and answers "missing number `intensity`" without one; a number outside the range counts as its nearest end. A value that is not a number, such as `"40"`, is refused with `` `intensity` must be a number, not "40" ``, as in every command that needs a number (`tests::params::a_malformed_required_number_is_not_reported_as_missing`). `edit.colors.adjustBalance` refuses a channel and `color.harmony` refuses `steps` or `amount` that is not a number; both read `null` as a value left out. `tests::editcolors` and `tests::colorguide` cover them. - **Convert to Indexed Color:** Edit › Edit Colors › Convert to Indexed Color… (`edit.colors.toIndexed`) stores the embedded images in the selection as indexed-color PNGs of at most 256 colors. The palette is chosen as for a PNG-8 export, as evenly spaced levels of red, green and blue, or from the document's swatches, with diffusion, pattern or noise dithering; pixels under half opacity become transparent. The dialog previews live, and OK is one undo step. This is VectorCraft's own command and counts toward no score. `tests::editcolors` and `encode::tests_palette` cover it. Scores and estimates unchanged. - **Working RGB numeric controls:** the Color panel and Color Picker read RGB, HSB, hex and Web Safe RGB values in the active working RGB space. Editing one RGB channel preserves the other native channels, including colors outside display sRGB. Regressions cover sRGB, Display P3, Wide Gamut RGB and ProPhoto RGB, picker initialization, native numeric round trips, and a slider click with one Undo step. Scores and estimates unchanged. @@ -1941,14 +1967,15 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With a gradient stop or a freeform gradient point selected, Alt-clicking a color swatch in the Swatches panel recolors it instead of the inactive Fill or Stroke. - **Freeform gradient colors in their own model:** Object ▸ Expand and Object ▸ Create Gradient Mesh (`object.mesh.create`) mix a freeform gradient's points in the color model they share: points of C50 M20 Y0 K10 give mesh points of C50 M20 Y0 K10, and RGB points keep their values in a working RGB space other than sRGB. The canvas, the gradient chips and the SVG, PDF, EPS and EMF writers mix the points in that model too. PDF and EPS write a gradient whose points are all CMYK, or all Gray in a CMYK file, as a CMYK image, which PDF's Output settings convert as they convert any CMYK image. Points in different models mix in display RGB (on the canvas in a CMYK document that shows transparency, as the inks of each point), and a CMYK document stores the result of Expand as CMYK through the color settings. Points colored along CMYK stops (`paint.editGradient {stops}`, or a CMYK gradient switched to freeform) are CMYK, and so are a point `paint.freeform.splitLine` adds between CMYK points and a point `paint.freeform.addPoint` adds without `color` to CMYK points. Public reference: [Gradients](https://web.archive.org/web/20250714042311/https://helpx.adobe.com/illustrator/using/gradients.html) and [Meshes](https://web.archive.org/web/20250812201019/https://helpx.adobe.com/illustrator/using/meshes.html), which do not state how colors in different models mix; the rule is VectorCraft's own. - **Strokes:** one stroke-geometry module shared by the canvas, SVG, PDF and Outline Stroke; dotted lines (zero-length dashes draw dots or squares); arrowheads with hollow outlines, tip-on-end or extend-past-end alignment and one opacity for line and head. SVG and PDF export arrowheads, width profiles, brushes and aligned strokes exactly as the canvas draws them; Outline Stroke and the live Outline Stroke effect outline every stroke item as drawn (dashes, heads, profiles, alignment); dashes can be fitted to corners and path ends; width profiles carry through dashes, and their corners take the join. The Stroke panel edits type's character strokes, follows the stroke units (its weight presets are round values in that unit: `0.25 mm`, `0.0625 in`, `1 px`, #426; fields show four decimals in mm, cm and inches, three in points), shows mixed values blank and opens from the Control bar. A width profile library, thirty-one more arrowheads (among them Line Arrow: two arms of the head's weight (stroke weight × arrowhead scale, at least 0.25 pt: the line's weight at 100 % for lines of 0.25 pt or more) at right angles, cut square, #5421), and Width Point Edit with multi-select and discontinuous points. Visual bounds and clicks cover the whole painted stroke. Scale Strokes & Effects, Scale Corners and Use Preview Bounds work everywhere, and new art inherits stroke options, a graphic style or the whole last appearance. A width profile's sides run as a smooth C1 curve between the width points (a monotone cubic Hermite, Fritsch–Carlson, with the one-sided three-point PCHIP slope at the profile's ends and flat either side of a step), sampled adaptively along the path (two samples per profile segment, refined where the width bends, and leaning on dense path flattening) so straight runs draw it too; added samples offset along the source curve's exact tangent, not the flattened chord, so high zoom follows the true width; the sampled edges are fitted with G1 cubics within a tenth of the flattening tolerance (0.001 pt at the default 0.01 pt) rather than one cubic per flatten step, so exports stay close to a uniform stroke's path data; a point reshapes the curve as far as its neighbours' neighbours (their slopes depend on it), and coincident points still step. - - **Brushes (part of #852):** double-clicking a brush in the Brushes panel (or the panel menu's Brush Options…) opens Calligraphic Brush Options (Name; Angle, Roundness and Size, each Fixed, Random, Pressure, Tilt, Bearing or Rotation with its Variation; live previews of the nib and of a light–heavy–light stroke) or Bristle Brush Options (Shape and the bristle sliders); OK edits the brush and every stroke painted with it. The Paintbrush records the pen pressure along each stroke (kept with the path, saved, and joined when a stroke continues a path); a Calligraphic value on Pressure goes from value − variation at the lightest pressure to value + variation at the heaviest, on the canvas and in SVG, PDF and the other exports. Brushes saved before keep their look. Scatter Brush Options (Size, Spacing, Scatter and Rotation, each Fixed, Random between two values, Pressure from the first at the lightest pressure to the second at the heaviest, Tilt, Bearing or Rotation; Rotation relative to Page or Path), Art Brush Options (Width, Scale Proportionately, Stretch to Fit Stroke Length or Stretch Between Guides with the guides' start and end, the four Directions, Flip Along and Across, Overlap) and Pattern Brush Options (Scale, Spacing, the five tiles shown, Flip Along and Across, Stretch to fit, Add space to fit or Approximate path) each have Colorization (None, Tints, Tints and Shades, Hue Shift with its Key Color picked from the art's colours) and a live stroke preview; values from files and commands are clamped to their ranges. Art Brush Options › Overlap places art on each run between sharp corners so folds do not overlap (`ArtBrush.overlap`; `art_brush_overlap_splits_at_corners`). Still to come: Stylus Wheel, pen pressure on macOS where the windowing layer reports none, and tilt, bearing and rotation for Pattern and Bristle brushes and on native Wayland and the web. + - **Brushes (part of #852):** double-clicking a brush in the Brushes panel (or the panel menu's Brush Options…) opens Calligraphic Brush Options (Name; Angle, Roundness and Size, each Fixed, Random, Pressure, Tilt, Bearing or Rotation with its Variation; live previews of the nib and of a light–heavy–light stroke) or Bristle Brush Options (Shape and the bristle sliders); OK edits the brush and every stroke painted with it. The Paintbrush records the pen pressure along each stroke (kept with the path, saved, and joined when a stroke continues a path); a Calligraphic value on Pressure goes from value − variation at the lightest pressure to value + variation at the heaviest, on the canvas and in SVG, PDF and the other exports. Brushes saved before keep their look. Scatter Brush Options (Size, Spacing, Scatter and Rotation, each Fixed, Random between two values, Pressure from the first at the lightest pressure to the second at the heaviest, Tilt, Bearing or Rotation; Rotation relative to Page or Path), Art Brush Options (Width, Scale Proportionately, Stretch to Fit Stroke Length or Stretch Between Guides with the guides' start and end, the four Directions, Flip Along and Across, Overlap) and Pattern Brush Options (Scale, Spacing, the five tiles shown, Flip Along and Across, Stretch to fit, Add space to fit or Approximate path) each have Colorization (None, Tints, Tints and Shades, Hue Shift with its Key Color picked from the art's colours) and a live stroke preview; values from files and commands are clamped to their ranges. Art Brush Options › Overlap places art on each run between sharp corners so folds do not overlap (`ArtBrush.overlap`; `art_brush_overlap_splits_at_corners`). Still to come: Stylus Wheel for Pattern brushes and on Windows and the web, pen pressure on macOS where the windowing layer reports none, and tilt, bearing and rotation for Pattern and Bristle brushes and on native Wayland and the web. 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 (<https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html>) 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. + 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). The menu also offers Stylus Wheel (next item). + - **Airbrush stylus wheel:** Calligraphic and Scatter Brush Options offer Stylus Wheel for Size, and Art Brush Options for Width, as the help page lists it (<https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html>). The Paintbrush records where an airbrush pen's finger wheel is set along each stroke (kept with the path, saved, joined when a stroke continues a path, and interpolated by blends). A Calligraphic Size goes from size − variation at one end of the wheel's travel to size + variation at the other, a Scatter Size from its first value to its second, and an Art Width from Width to the second width; a stroke without a wheel draws the value half way. The direction of travel and the half-way value for a stroke without a wheel are VectorCraft's own rules. On Linux under X11 and XWayland the app reads the wheel from XInput2's `Abs Wheel` valuator, and on macOS from AppKit's `tangentialPressure`; Windows pointer messages have no field for it, and the web build does not read it yet. `path.freehand` points take it seventh and `pointer_gesture` events take `wheel`, and `.ai` brush definitions read and write it as variation code 3. Evidence: `tests::the_stylus_wheel_varies_sizes_and_widths` (vectorcraft-brush), `tests_brushsym::freehand_points_record_the_stylus_wheel` (vectorcraft-engine), `more_brush_settings_are_read_back` and `a_calligraphic_brushs_pen_channels_come_in_by_their_codes` (vectorcraft-eps), `tablet::tests::an_airbrush_wheel_goes_into_the_feed` and `mac_tablet::tests::an_airbrush_wheel_goes_into_the_feed` (vectorcraft). Scatter, Art and Pattern Brush Options have the Tips button for Colorization that the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy) describes, beside Method. It opens Colorization Tips, which shows each method's name and what it does beside a sample of the brush, as OK would make it, painted with that method on a blue stroke; Hue Shift's sample uses the dialog's Key Color. `ui.dialog.set {field: "tips", value: true}` opens it. Screen readers name the button, the popover and each sample. Hue Shift set by `brush.new` or `brush.options` without a key color takes the color the art's fills and strokes use most, as Brush Options already offers it, following the Brushes page, where the key color defaults to the color that stands out most in the art (<https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html>). The page does not state how prominence is measured. Counting the fills and strokes that use each solid color, with the first one found winning a tie and black for art with no solid color, is VectorCraft's own rule. A `brush.options` edit that gives only the method keeps the brush's key color, and one that gives only an art brush's start guide keeps its end guide. Evidence: `tests_brushsym::hue_shift_without_a_key_takes_the_most_used_art_color`, `tests_brushsym::art_brush_options_keep_the_scale_fields_an_edit_leaves_out`. Bristle Brush Options and `brush.new` take a bristle brush name of at most 31 characters, as the Brushes page states for the Bristle Brush Options. The Name field stops taking characters at 31, and `brush.new` and `brush.options` refuse a longer new name with an error that names the limit. The page does not say how the limit counts characters or what happens to longer names already saved; counting characters and the number added to a taken name, keeping longer saved names, and leaving `brush.duplicate` unlimited are VectorCraft's own rules. A bristle brush that a document or a saved file already holds under a longer name keeps it, and the other brush types take a name of any length. Test: `bristle_brush_names_have_at_most_31_characters` in `tests/brushsym.rs`. Public reference: [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) (archived copy). @@ -1956,6 +1983,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur In the Brushes panel, Shift-click selects a range of brushes and Ctrl/Cmd-click adds or removes one. Delete Brush and Duplicate Brush then act on all of them (`brush.delete {names}`, `brush.duplicate {names}`). The Brushes panel's Delete Brush button and panel menu item ask "Delete the selected brushes?" with Yes and No when none of the brushes is in use. Alt-click (Option-click on macOS) on the button deletes them without asking, as the [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists for panel deletion outside the Layers panel (archived copy). When a stroke uses one of the brushes, the button, Alt-click and the menu item all ask with Remove Strokes and Cancel; Remove Strokes deletes the brushes and the strokes that used them become plain strokes. Tests: `panels::brushes::tests`, `dialogs::brush_delete::tests`. Document Info has a Brushes category after Graphic Styles. It lists the names and types of the brushes applied to the artwork, as the [Document Info panel](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/document-info-panel.html) page describes, or with Selection Only the brushes that the selected objects' strokes use. The Document Info report and Package's report list them too (`document.info {category: "brushes"}`, `brushNames`, `brushes`). Listing each brush once, leaving out the Brushes panel's brushes no art uses (`panelBrushNames` lists the panel's brushes), hidden strokes, strokes at an opacity of 0, strokes with no paint or width, guides, paths with no segment, type that draws no characters, a group's or layer's own strokes, a compound path member's own strokes and an image's strokes without a shape, and listing a brush the panel does not hold as missing, are VectorCraft's own rules. Tests: `cmd::docinfo::tests::info_lists_the_brushes` and `info_brushes_skip_undrawn_strokes_and_name_missing_brushes` (vectorcraft-engine). + Document Info's Fonts category gives each font's type and number of uses beside its name, as the [help page](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/document-info-panel.html) describes, for the whole document or with Selection Only for the selected type. The Document Info report and Package's report give them too (`document.info {category: "fonts"}`, `fontUses`), and the panel shows the type and count in the interface language. Counting a use as a text object set in the font (once however many of its runs use it, and the type in a mask or in a symbol's or pattern's art once however many objects show it), naming the type by the face's outlines (TrueType for `glyf`, OpenType for `CFF` or `CFF2`) and showing an unknown type for a font that is not installed in the family and style the type names are VectorCraft's own rules. Tests: `cmd::docinfo::tests::info_fonts_give_each_font_s_type_and_uses` (vectorcraft-engine), `panels::doc_info::tests::font_types_and_uses_show_in_the_interface_language` (vectorcraft-ui-egui), `fontdb::face::tests::outline_format_follows_the_outline_tables` (vectorcraft-text). Document Info has a Repeat Objects category after Embedded Images. It lists each radial, grid and mirror Repeat object by name with its kind and the number of instances it makes. For a grid it gives the rows and columns instead, followed by the number of instances it draws when that is fewer. With Selection Only it lists the Repeat objects in the selection. The Document Info report and Package's report list them too (`document.info {category: "repeats"}`, `repeatObjects`). Document Info's Pattern Objects category lists the objects whose fill or stroke is a pattern, the category the [Document Info panel](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/document-info-panel.html) page describes, each by name with the patterns it uses. With Selection Only it lists those in the selection, and the Document Info report and Package's report list them too (`document.info {category: "patterns"}`, `patternObjects`). Listing an object with a pattern fill and a pattern stroke once, listing objects inside groups and type objects whose characters use a pattern, and leaving out hidden fills and strokes, fills and strokes at an opacity of 0, strokes with no width, guides, a compound path member's own fills and strokes, an image's fills and strokes without a shape, characters the type does not draw and patterns no art uses, and counting the listed objects in Objects, are VectorCraft's own rules. Test: `cmd::docinfo::tests::info_lists_the_pattern_objects` (vectorcraft-engine). Document Info's Gradient Objects category lists the objects whose fill or stroke is a gradient, the category the [Document Info panel](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/document-info-panel.html) page describes as the count of objects with gradient fills or strokes. Each object is listed by name with the gradients it uses. With Selection Only it lists those in the selection, and the Document Info report and Package's report list them too (`document.info {category: "gradients"}`, `gradientObjects`). Naming a linked gradient by its swatch and any other gradient by its kind, and leaving out paint that draws nothing by the rules Pattern Objects follows, gradient swatches no art uses, gradient meshes and gradients drawn by effects, are VectorCraft's own rules. Objects counts the listed objects as Gradient Objects. Test: `cmd::docinfo::tests::info_lists_the_gradient_objects` (vectorcraft-engine). @@ -1975,6 +2003,7 @@ 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. + The Appearance panel's row edits (`appearance.setItem`), Duplicate Item (`appearance.duplicateItem`) and fill and stroke edits aimed at a row (`item`) look up which objects had their shown row written in a set, so that step takes time in step with the number of objects. With 20,000 squares, each with one fill and one stroke row and each command given every square's id, that step takes 0.4 ms of thread CPU time on Linux instead of 57 to 63 ms, and the whole `appearance.setItem` command takes 96 ms instead of 158 ms; at 2,000 objects the difference is about 2 ms (`crates/engine/examples/appearance_rows_bench.rs`; `cmd::graph::tests::row_edits_on_several_labels_keep_the_last_written_shown_row`). 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`). @@ -2003,7 +2032,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur PDF export writes a knockout group as one PDF knockout group (`/K true`, with `/I true` when the group isolates; ISO 32000-1, 11.4.6.3), so a knockout group of any size opens again in VectorCraft as a knockout group, and the form nesting of the file does not grow with the number of elements. When an element's opacity or mask defines its knockout shape, or it paints translucently, each element is drawn through one soft mask of the overlapping elements above it instead; past 65,536 objects in a group's masks (or 2,048 elements) the group is a PDF knockout group, with a warning that its translucent elements knock out fully. SVG export draws each element of a knockout group through one mask of the overlapping elements above it, and the masks refer to one copy of each element's shape, so the elements stay siblings and the file nests no deeper with more elements; past 65,536 shapes in a group's masks (or 2,048 elements) the group is written as a plain group, with a warning. Evidence: `pdf/src/tests/blend.rs`, `svg/tests/it/blend_export.rs`, `pdf/tests/gradient_forms.rs` (a gradient in a knockout group reads back in place). A knockout group in Normal mode at full opacity that does not isolate, with nothing blending inside, is written without an isolated group around its elements, clipped or not, so the art below the group is its initial backdrop in the PDF as on the canvas (ISO 32000-1, 11.4.5): neither its `/K` group nor a form around a clipped group carries `/I true`, and an overprinting element in it overprints the art below the group. Evidence: `pdf/src/tests/blend.rs` (`a_knockout_group_without_blending_inside_is_isolated_only_when_it_isolates`, `an_overprinting_element_of_a_knockout_group_that_does_not_isolate_overprints_the_art_below`). PDF import keeps a group's isolation when something inside it overprints as well as when something blends, so an isolated group or knockout group whose objects only overprint opens as an isolated group and is written with `/I true` again, and its overprinting objects still cover the inks of the art below the group. Evidence: `pdf/src/tests/blend.rs` (`an_isolated_group_with_an_overprinting_object_reads_back_isolated`, `an_overprinting_element_of_a_knockout_group_that_does_not_isolate_overprints_the_art_below`). - - **Graphic styles:** styles keep opacity and blend mode, capture groups and type, apply on top with Alt, and link to the objects using them; Redefine, Break Link, Graphic Style Options, Select All Unused, Sort by Name, and Select > Same Graphic Style / Appearance Attribute. The panel has list and thumbnail views with rendered previews, merge, reorder and drag and drop, plus a Control bar Style picker; eleven generated style libraries (including Game HUD, Status Effects, Neon & Glow, Painted and Sketched, whose seven styles each repaint a solid fill with one watercolor, dry brush, pastel, charcoal or ink effect, and Textures) save and load as `.vcstyles`. + - **Graphic styles:** styles keep opacity and blend mode, capture groups and type, apply on top with Alt, and link to the objects using them; Redefine, Break Link, Graphic Style Options, Select All Unused, Sort by Name, and Select > Same Graphic Style / Appearance Attribute. The panel has list and thumbnail views with rendered previews, merge, reorder and drag and drop, plus a Control bar Style picker; twelve generated style libraries (including Game HUD, Status Effects, Neon & Glow, Painted and Sketched, whose seven styles each repaint a solid fill with one watercolor, dry brush, pastel, charcoal or ink effect, Textures, and Paper Cutouts with six original layered-paper looks and crisp cast shadows) save and load as `.vcstyles`. The built-in Textures graphic style library (`graphicStyle.addFromLibrary {library: "textures"}`) has eight styles that paint their fills and strokes with the texture effects: Fine Grain (Grain), Canvas Weave and Burlap Sack (Texturizer), Cracked Glaze (Craquelure), Mosaic Floor (Mosaic Tiles), Quilted Squares (Patchwork), Leaded Glass (Stained Glass) and Damp Paper (Water Paper). The help page names new graphic styles for textures ([What's new](https://helpx.adobe.com/illustrator/desktop/new-features/whats-new.html)) without naming them, so the styles, their names and their settings are VectorCraft's own (`tests::stylelib::textures_styles_apply_their_texture_effects_and_keep_their_params_through_save_and_open`). 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 `<name> 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`). @@ -2168,6 +2197,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur 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`). + The Save PDF dialog's Summary section has a Save Summary… button that writes the summary it shows to a text file, as the help page describes (https://helpx.adobe.com/illustrator/using/pdf-options.html). The file holds the section's lines in UTF-8 with LF line endings, and the save panel suggests `<document> PDF Summary.txt`; both are VectorCraft's own choices (`ui.pdfSummary.save`; `crates/ui-egui/src/dialogs/save_pdf/tests.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`). The Save PDF dialog and the PDF preset editor have a link button beside the four bleed values in Marks and Bleeds: while it is on, editing one value sets the other three to it. [The help page](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=249) describes this button for the PDF dialog. VectorCraft's own rules: the link opens on when the four values are equal and off when they differ, also after choosing a preset or Reset; turning it on gives every side the top value; turning it off leaves the values as they are; with Use Document Bleed Settings on, the button is grayed out and the custom values and link stay as they were. The link is not a PDF option or a preset setting; `ui.dialog.set` sets it as `__bleedLinked` (`crates/ui-egui/src/dialogs/save_pdf/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`). @@ -2208,6 +2238,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Import Slices: File › Open of a PSD or PSB file with slices, and File › Place of one without Link, bring its slices in as user slices, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file that is opened or embedded; PSD Import Options offers Import Slices for such a file. `document.open` and `file.place` take `importSlices`, and `document.psdInfo` counts the slices. The slices are read from image resource 1050 in version 6 and in the descriptor of versions 7 and 8, as the [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/) describes it. VectorCraft's own rules: Import Slices applies to Convert Layers to Objects and to Flatten Layers to a Single Image alike, and makes the dialog ask for a file with fewer than two layers; placed slices move and scale with the art in the same undo step; each slice keeps its name, type, link, target, message, alternative text, cell text and background color; slices the file generated automatically, and slices wholly outside the canvas, are left out; slices that can't be read are left out with a warning while the art comes in; with Show Import Options off, a PSD file is placed with the PSD Import Options chosen last, and on, each PSD file of the place cursor asks for them (`crates/engine/src/cmd/fileio/tests_psdslices.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`). The import fuzz tests open, count and place PSD files whose resource 1050 is in version 6 (with a version 16 descriptor after a record) and in the descriptors of versions 7 and 8, with their data mutated, cut short with the resource's length saying so, and cut short in the file; a slice count past 10,000 or past the slices stored, and data one byte short, bring the art in without its slices and with a warning. `tests_psdslices::damaged_slices_never_panic` now fails when a command reports an internal error (`import_fuzz::the_sliced_psd_samples_bring_in_their_user_slices`, `import_fuzz::sliced_psd_samples_with_huge_counts_or_cut_short_come_in_without_their_slices`, `import_fuzz::mutated_psd_slices_never_panic`). Scores and estimates unchanged. - PSD export writes slices: the user and object slices that reach into the exported artboard go into image resource 1050 in version 6, as the [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/) describes it and as Import Slices reads it, so an opened PSD file's slices survive its export. VectorCraft's own rules: slices are written with Write Layers and as a flat image alike, clipped to the artboard in its pixels; an object slice is written as a user slice over its object's bounds, and an HTML Text slice as No Image with its type's text; auto slices are left out and laid out again on open; text alignment is written as the default (`crates/render/src/encode/tests_psd.rs`, `crates/engine/src/cmd/fileio/tests_psdslices.rs`). + - PSD Import Options' title and choices are shown in the interface language in every catalog with complete menus, and the warnings and errors of opening and placing a PSD or PSB file with its layers and slices are shown in it in every catalog with complete messages, with their counts, names and reasons (`psd_import_strings_are_in_complete_catalogs` in `crates/ui-egui/src/i18n/tests.rs`). Scores and estimates are unchanged. - PCX files (`.pcx`) open and place, from the ZSoft PCX Technical Reference Manual: 1 bit in the header palette's first two colors (black and white when the version has no palette or both colors are the same), 1 bit in two to four planes and 4 bits with up to 16 colors from the header's palette (the EGA colors for versions 0 and 3), 2 bits in the CGA colors that the header's CGA palette settings pick (background, color burst, palette and intensity), 8 bits with the 256-color palette after the image data (gray levels without one) and 24-bit color in three planes, run-length encoded. The header's HDpi and VDpi size the image. A file of another depth or plane count, one cut short, and one whose pixels as RGBA pass the pixel allowance are refused with a message before its pixels are decoded. Open and Place recognize a PCX file by its extension, and `clipboard.importImage` and Glass's Load Texture… by its header; a PCX file copied in a file manager pastes as a bitmap (`crates/engine/src/cmd/fileio/tests_pcxread.rs`). - Pixar picture files (`.pxr`) open, place and paste, from "The Format of Stored Pictures" in the Pixar Image Computer manuals: any set of the R, G, B and A channels in 8 or 12 bits, dumped or run-length encoded with all four packet kinds and block ends, in tiles of any size (pixels of border tiles past the picture are dropped). R alone is gray, a missing color channel is 0 and a missing A opaque; 12-bit samples are clamped to 0.0 to 1.0; color matted to black becomes straight color; a null tile is transparent when the picture has A and black otherwise. The offsets aren't read, and the image takes the default resolution. Version 2 headers read like version 0. A file cut short, one with a tile whose writing wasn't finished, one with header values or packets the format doesn't define, and one whose pixels as RGBA pass the pixel allowance are refused with a message. Every reader recognizes a Pixar file by its magic number. Tested on synthetic files only (`crates/engine/src/cmd/fileio/tests_pxrread.rs`). - JPEG 2000 JP2 and raw codestream images open and place from `.jpf`, `.jpx`, `.jp2`, `.j2k`, `.j2c` and `.jpc`. Each axis uses the valid display resolution (`resd`), else the valid capture resolution (`resc`), whichever box comes first ([ITU-T T.800](https://www.itu.int/rec/T-REC-T.800/en), I.5.3.7.2); an axis with none uses 72 ppi. Multiple codestreams, JPX composition or layers, and unsupported color spaces are refused with a message. The decoder checks image size before allocating (`crates/engine/src/cmd/fileio/tests_jp2read.rs`). @@ -2217,9 +2248,10 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - EMF and WMF type takes its size from the font's height, where a negative height is the em and a positive height is the character cell, and a font's average character width becomes Horizontal Scale against the face's own average width (OS/2 `xAvgCharWidth`) when the face gives one, as [LOGFONT](https://learn.microsoft.com/en-us/windows/win32/api/wingdi/ns-wingdi-logfontw) and [MS-EMF 2.2.13](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-emf/1cd7cb7a-1a7c-48d2-b4a4-c218f9d12100) describe the two fields. VectorCraft's own rules are that the cell is the face's `usWinAscent` plus `usWinDescent` at a variable font's instance (its ascent plus descent without an OS/2 table), that a negative width is read as its absolute value, and that the width is ignored when the height is 0 (`a_font_width_becomes_horizontal_scale`, `a_positive_font_height_is_the_character_cell`, `a_font_the_system_lacks_is_measured_in_the_face_that_draws_it`, `wmf_font_width_becomes_horizontal_scale`). - EMF and WMF files are read by the shared `craft-metafile` reader and open, place and paste as editable paths, clipping groups, images and point type: an EMF drawn with EMF+ records (on their own, or beside plain records) is read from them instead of opening empty, and hatched and pattern brushes fill with their average color (`crates/metafile/src/tests/import.rs`). - EMF, WMF and EMF+ text keeps the character advances the file gives (ExtTextOut's `lpDx`, DrawDriverString positions) as tracking, with pair kerning off; on a single left to right line, an advance that tracking can't give (wider than its range, or a tab) starts a new point type object where the advance puts it, with an underline or strikethrough filled across the space between and on to the end of the last character's advance; type on more than one line is placed a line at a time, each line aligned by its own advances and split as a single line is (`text_is_spaced_by_its_advances`, `multiline_text_with_advances_aligns_each_line`, `wmf_text_is_spaced_by_its_advances`, `emf_plus_driver_strings_keep_their_positions`, `split_type_keeps_its_underline_and_right_to_left_order`). - - EMF and WMF import warns about what the reader leaves out or does not play as the file asks, with counts: a file, or a metafile image inside it, cut short by one of the reader's limits (items, bytes kept, saved states, clip paths), images and pattern brushes that are not read, clips that are not applied, and raster operations other than a plain copy (`a_file_cut_short_by_another_limit_says_so`, `images_the_reader_does_not_read_are_counted`, `clips_that_are_not_applied_are_counted`, `raster_operations_that_are_not_played_are_counted`, `a_wmf_reports_unread_pattern_brushes_and_raster_operations`). + - EMF and WMF import warns about what the reader leaves out or does not play as the file asks: a file, or a metafile image inside it, cut short by one of the reader's limits (items, bytes kept, saved states, clip paths), with one warning without a count, and, with counts, images and pattern brushes that are not read, clips that are not applied, and raster operations other than a plain copy (`a_file_cut_short_by_another_limit_says_so`, `images_the_reader_does_not_read_are_counted`, `clips_that_are_not_applied_are_counted`, `raster_operations_that_are_not_played_are_counted`, `a_wmf_reports_unread_pattern_brushes_and_raster_operations`). - Export As › HP-GL (`document.export {format: "hpgl"}`) writes a `.plt` plot of an artboard, each artboard or the art for pen plotters and cutters: each visible path once along its line in plotter units from the artboard's bottom-left corner or center, a pen per color or a pen table, curves flattened to a tolerance, type as outlines, clipping masks and the artboard's edges applied, and HP-GL or HP-GL/2 (pen colors and encoded polylines); plots read back by the HP-GL reader give the same lines (`crates/cad/src/hpgl/write/tests.rs`, `crates/engine/src/cmd/fileio/tests_hpgl.rs`). - HP-GL export's `insideFirst` cuts each pen's paths inside before outside: a path is drawn only after the pen's paths that lie inside it (a letter's counter, a part's holes, rings within rings), touching outlines counted as inside and crossing ones not, in paint order or nearest first with `sortPaths`, within the plot's work budget; these order rules are VectorCraft's own (`crates/cad/src/hpgl/write/nest.rs`, `crates/cad/src/hpgl/write/tests.rs`, `crates/engine/src/cmd/fileio/tests_hpgl.rs`). + - Export As › HP-GL opens HP-GL Options (`ui.hpglOptionsDialog`): Version, Curve Tolerance, Origin, Pens (One Pen per Color, or a Pen Table that starts from the pens the plotted art gets, with a row per pen to type its color, remove it or add one), Draw the Nearest Path Next and Draw Inner Paths First; OK checks the options and the artboard choice as the export does and remembers the options for the next export (`crates/ui-egui/src/dialogs/tests_hpgl.rs`, `crates/engine/src/cmd/fileio/tests_hpgl.rs`). - EPS and DXF in and out, EMF/WMF in and out; PNG (with PNG-8), JPEG, WebP, GIF, TIFF, BMP, Targa and layered PSD export; grayscale TIFFs with an alpha channel or other extra channels place, relink and open, the alpha as the image's transparency (#1466 in part); PSD and PSB files open and place, linked or embedded, as their merged image in every colour mode and depth (#918). EPS import runs a PostScript Level 3 interpreter written from the PostScript Language Reference: resource categories and `resourceforall`, local and global VM (`currentglobal`/`setglobal`/`gcheck`), `clipsave`/`cliprestore`, subarrays and substrings that share storage, the standard dictionaries in `systemdict`, `dictstack`, `internaldict`, executable filters and strings, `load` by any key, `//name` immediate names, `token`, `execform`, user paths, `cshow`, `rootfont`, `cachestatus`, colour rendering and halftone queries, file `status` and data read with `flushfile`, and `pdfmark` marks dropped (Discord feedback, #466, #469, #474). Masked images (`ImageType 3` in its three interleavings) and reusable streams are read, and an image's several data sources are read in turn, as the reference defines (procedures that read one file get their own rows: such images came in banded, #498). `restore` puts dictionaries back as they were at the `save`, so programs that count their saves in a dictionary read to their end (part of #505). Tiling patterns come in as pattern swatches, uncoloured ones too; Type 3 fonts' glyphs as their outlines, spaced by `ashow`/`widthshow`/`xshow`/`kshow`; mesh and function-based shadings (types 1, 4–7) as gradient meshes; sampled functions (type 0) and Flate/LZW predictors are read. It is tested with programs written from the specification in the ways common generators use these features; Inkscape/cairo EPS files open as vectors. When a file's PostScript still can't be read, it opens as its TIFF preview, its Windows metafile preview (as vectors) or its EPSI preview, and the warning (in the status bar, `document.open`/`app.open`/MCP `open_file` replies and `vectorcraft-cli info`) names the error, the operator that raised it and the procedures it ran in. Legacy PostScript `.ai` files (Illustrator 3–8, written with the prolog that defines their operators) keep their groups and nested groups (`u` … `U`), between and inside clipping groups; EPS and EMF/WMF import nest clips (and groups) at most 128 deep, so a hostile file can't exhaust the stack. DXF TEXT justified Fit or Aligned spans its two points (stretched, or scaled as a whole). PDF export writes type as real, searchable text in embedded subset fonts by default, as Illustrator's PDF presets do (Convert Text to Outlines is an option; printer's marks stay shapes), so text-heavy PDFs stay small (#733). DXF export writes each fill as its outlines followed by its hatch, so laser and cutter software, which skips hatches, gets filled art and type too (#546). - TIFFs that store each channel as its own plane (PlanarConfiguration 2) place, relink and open as the same image stored pixel by pixel does, 8 and 16 bits: grayscale with an alpha channel or other extra channels, and CMYK with or without them. A planar CMYK TIFF keeps its ink amounts and is stored as a CMYK TIFF with each pixel's inks together, at the file's resolution. A TIFF whose header claims more strips or tiles than can be counted is refused as too large to draw (#1466 in part; `crates/engine/src/cmd/fileio/tests.rs`). - A 16-bit CMYK or grayscale TIFF with an alpha channel is converted from its 16-bit samples, and only the resulting color and alpha are rounded to 8 bits; associated alpha is divided out at 16 bits, and a pixel whose associated alpha is zero has no color. [TIFF 6.0](https://printtechnologies.org/standards/files/tiff-v6.pdf) gives extra samples the depth in BitsPerSample, and its Associated Alpha Handling section states the arithmetic and the zero-alpha rule for RGB data; applying them to CMYK and gray samples is VectorCraft's own rule. Each sample was cut to its high byte first, so a faint ink or a low alpha could be lost (`crates/doc/src/cmyk.rs`, `crates/engine/src/cmd/fileio/tests.rs`). @@ -2338,6 +2370,22 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur actual OS display and Caps Lock remain unverified. Behaviour reference: [public tool-pointer documentation](https://helpx.adobe.com/illustrator/using/tools.html#change_tool_pointers). Tool cursors are painted into the window on Wayland (#1652; not run on Linux, #1645 stays open until confirmed). A Precise Cursors command toggles the preference and can take a shortcut (#1663). On macOS the root document canvas now requests native AppKit delivery of the existing artwork, with aligned 1×/2× representations and a visible system fallback (#2292). While the host owns the cursor it sets it again on every pass instead of comparing it with `NSCursor.currentCursor`, which is the app's last set cursor rather than the one on screen, so the tool's cursor no longer gives way to the system arrow when the pointer moves (#6362). `cursors/native_request` and `canvas` tests cover pixel/hotspot alignment, preferences and fallback routing; `mac_cursor` tests cover real AppKit image construction and the ownership protocol against a fake backend. The host releases on native-menu tracking and loss of eligibility; detached document viewports retain the visible system fallback. The pre-platform-output rectangle strategy, real focus/menu/handback behavior, mixed displays, Spotlight and native full-screen Spaces remain unverified; #2020 and #2292 are not declared closed. In a rotated view the resize and rotate cursors turn with the view, to the nearest 45°. - **Performance:** 20k shapes + 1k texts render in 27 ms per full-retina frame (7.8 ms zoomed), 7× faster than the first version. The UI thread never blocks. The web build is 7.1 MB gzipped. Print-size images (more than 512 MB decoded, up to 2 GB) draw in the canvas and in raster exports and can be trimmed with Crop Image; an image with a side past 65,535 px is shrunk to fit, a raster export says when an image could not be decoded, and Crop Image's trim leaves CMYK images alone (#1517). On Windows `vectorcraft-cli perf` reports the cores busy and, with `--deep`, its working set, and warns on a busy machine as it does on macOS and Linux (#1502). + + <a id="text-thread-overlay-filtering"></a> + Text thread overlay filtering (#6543) keeps the first membership lookup direct and indexes later lookups for selections of more than one object. A singleton selection stays direct. Four focused controls cover document ordering, mixed selections, hidden ports and perspective exclusions. + The ignored diagnostic constructs and warms its fixture before timing 2,000 calls; it checks real thread and selection counts, valid ports, disjoint selected IDs and empty output. + In one quiet Windows x64 run using the optimized test profile, the matched two-frame fixtures gave these totals for 2,000 calls (fixture construction and lookup warmup are outside the timer): + + | Threads | Selected unrelated paths | Before (ms) | After (ms) | + |---:|---:|---:|---:| + | 256 | 256 | 192.76 | 81.27 | + | 256 | 512 | 374.79 | 142.70 | + | 512 | 256 | 333.64 | 100.80 | + | 512 | 512 | 647.28 | 160.94 | + | 512 | 1 (control) | 4.07 | 6.97 | + + The control adds 1.45 µs per call; the four large-selection cases take 58–75% less time. These measure filtering, not a complete frame. An additional single 1,024-frame thread with 512 unrelated selected paths passed the same empty-output checks and took 158.75 ms for 2,000 calls; that case has no measured baseline pair. + Hard-edge rendering, including the internal hard-edge frame of Art Optimized supersampled raster exports, draws a knockout element with one opaque solid fill once instead of erasing and adding it through separate layers. Analytical antialiasing keeps the existing compositor and rounding. Synthetic path/compound-hole tests compare exact pixels against the general knockout path across precision, supersampling, translucent parent groups and backdrop blending; translucent fills retain their knockout behavior. An image whose pixels can't be decoded, such as a PNG cut short or an image over the 2 GB decoding allowance as RGBA that can't be drawn at reduced size, is tried once: the renderer notes it and does not try to decode it again on later frames. An image refused only because the images being drawn leave no room for it is tried again on the next render. On the canvas such an image draws as a light gray box crossed from corner to corner, and the status bar says once for each image that it couldn't be decoded; exports leave it out and report it as before. A PNG, JPEG, GIF or WebP image that takes more than 2 GiB as RGBA (512 MiB in the web app) draws in the canvas and in raster exports at the largest size within that allowance, instead of as that crossed box on the canvas and not at all in exports. Each pixel of the result is the mean of the image's pixels it covers, and the document keeps the whole file. A PNG that isn't interlaced is read a row at a time, and other images are read whole when their decoded samples fit in the allowance. A 16-bit PNG that isn't interlaced, whose decoded samples take more than the allowance and whose RGBA fits in it, draws at its own size, read a row at a time. An image of more pixels than the allowance has bytes (on the desktop, 46,341 × 46,341 is more) still draws as the crossed box, and so does one whose decoded samples take more than the allowance, other than a PNG that isn't interlaced. Open, Place and the Links panel say "an image of W × H pixels is shown at reduced size", and say "too large to draw" of an image that is not drawn at reduced size. @@ -2425,6 +2473,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Live objects in documents with many symbols:** a live object, or an object with effects, that shows symbols or patterns is not walked again in a later frame to find them while the document's symbols and patterns stay the same. One that shows a placed file is walked in every frame. At 1000 × 1000 pixels, a page of 2,000 envelopes around instances of the last 2,000 of 10,000 symbols takes 30 ms a frame, and 83 ms when every frame walks them again, with the same pixels. - **Control bar and task bar on large paths:** the Control bar and the contextual task bar read the first selected object in place each frame instead of copying it; the task bar copies the object only when it is a basic shape, for its Shape Properties. With one selected open path of 200,000 anchors, an idle frame with both bars shown takes 3.8 ms in a release build instead of 8.0 ms (medians of five interleaved runs). Tests: `the_control_bar_label_follows_edits_undo_documents_and_selection`, `the_task_bar_follows_the_active_document`, `the_task_bar_follows_edits_and_undo`. +- **Control bar label and Mixed Appearances on large selections:** the Control bar's selection label and the Appearance panel's object row, Mixed Appearances note and shared rows are worked out once for each document revision and list of selected or targeted objects, and repaints with neither changed reuse them. The Control bar no longer copies the selection's ids on each repaint. With 200,000 selected rectangles, the label and summary take 2.1 ms of CPU time per repaint in a release build instead of 58.4 ms when the rectangles are alike, and 3.0 ms instead of 80.7 ms when every second one has another opacity (medians of seven interleaved runs of 20 repaints each). Tests: `the_selection_summary_is_reused_until_the_document_or_its_subjects_change` in `crates/ui-egui/src/panels/appearance/tests.rs`, `the_control_bar_label_follows_every_selected_object` in `crates/ui-egui/src/chrome/tests.rs`. - **Panels on large selections:** the Properties, Transform, Brushes, Appearance, Transparency and Image Trace panels read the selected object where the document holds it each frame instead of copying it, and the Transparency panel removes the mask from a copy of the object only when it draws the object's thumbnail again. With one selected open path of 200,000 anchors, an idle repaint uses 72.9 µs of CPU time in a release build instead of 88.4 µs for the Properties panel, 27.5 µs instead of 37.2 µs for the Appearance panel and 19.6 µs instead of 29.8 µs for the Transparency panel with its thumbnails shown (medians of seven interleaved runs). Tests: `first_selected_is_the_node_the_document_holds`, `first_subject_is_the_node_the_document_holds`, `panels_show_the_selected_object_after_an_edit_and_after_undo`, `state_holds_the_documents_node_and_the_object_thumbnail_leaves_out_the_mask`. - **Paste of many objects:** Paste leaves pasted copies as they are when no resource has another name or color in the document and the objects link no graphic style. It looks up the pasted type in one walk of the tree. A paste and undo of 20,000 rectangles in 200 groups uses 49.2 ms of CPU time in a release build instead of 59.4 ms, and of 5,000 point type objects 25.3 ms instead of 29.4 ms (medians of seven interleaved rounds, each round the CPU time of a 61-paste run minus a 1-paste run, divided by 60). Tests: `crates/engine/tests/it/paste_many.rs`. - **Selected objects in other panes:** under Window › Arrange › Tile and in floating document windows, each pane other than the current document's keeps the outlines of its selected objects between frames, and makes them again when its document, its selection or its view changes; with View › Edges off it keeps none. The outlines drawn are the same as before. With every object selected, a frame of a pane's outlines, tessellation included, takes 28.9 ms of CPU time in a release build instead of 40.1 ms for 20,000 rectangles, 116.7 ms instead of 197.2 ms for 20,000 ellipses, and 0.05 ms instead of 32.0 ms for 150,000 rectangles, which the pane draws as their bounds (medians of seven interleaved runs of 20 frames). Tests: `canvas::panes::tests::other_panes_keep_their_selected_outlines_until_the_document_selection_or_view_changes`; timing: `pane_outlines_timing`. @@ -2828,7 +2877,7 @@ A VectorCraft addition, so no area score moves. Object › Plug-ins › Cutting ## Path Precision Tools add-on: Common Tangents (2026-11-15) -A VectorCraft addition, so no area score moves. Object › Plug-ins › Path Precision Tools › Common Tangents… (`addon.pathtools.commonTangents`) adds the common tangent lines of two convex closed paths ([tangent lines to circles](https://en.wikipedia.org/wiki/Tangent_lines_to_circles)) as separate open paths: external, internal or all, with the line joining the two centers if asked. The rest is VectorCraft's own: an ellipse drawn with the Ellipse tool, turned or scaled, is measured as an exact ellipse, and any other path must be closed, have one outline and bend the same way all around. Each line runs between the points where it touches the two paths. Separate paths have four tangents, overlapping paths only external ones (two for ellipses), and a path inside the other has none, in which case nothing changes and a message says why. Paths that touch, from outside or from inside, share one tangent there instead: a line centered on the point where they touch and as long as the narrower path is wide along it. Since 2026-11-18 one of the two may be a point (a path of one anchor): the lines run from the point to where they touch the path, two from a point outside it, one at a point on its outline or less than the touching tolerance from it (centered on the point, or covering the straight side it lies on), and none from a point inside, with a message; the centerline runs from the point to the path's center, and every Tangents choice gives the same lines. The lines take the current stroke and no fill; one undo step. The dialog has Preview. Tests: `addons::pathtools::tangents::tests` in `vectorcraft-pathops` (circles against the closed form, turned ellipses against a brute-force scan, nested, overlapping and touching circles, a convex Bézier path, flat sides, squares meeting at a corner, a curve touched beside an anchor, a point outside a turned ellipse, on a circle, inside it, beside a square and at its corner, on a turned outline, within the touching tolerance, refused outlines), `cmd::addons::pathtools::tangents::tests` in `vectorcraft-engine`, `common_tangents_previews_cancels_and_runs_on_ok` and `common_tangents_on_a_point_gives_the_same_lines_for_every_choice` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Path Precision Tools add-on. +A VectorCraft addition, so no area score moves. Object › Plug-ins › Path Precision Tools › Common Tangents… (`addon.pathtools.commonTangents`) adds the common tangent lines of two convex closed paths ([tangent lines to circles](https://en.wikipedia.org/wiki/Tangent_lines_to_circles)) as separate open paths: external, internal or all, with the line joining the two centers if asked. The rest is VectorCraft's own: an ellipse drawn with the Ellipse tool, turned or scaled, is measured as an exact ellipse, and any other path must be closed, have one outline and bend the same way all around. Each line runs between the points where it touches the two paths. Separate paths have four tangents, overlapping paths only external ones (two for ellipses), and a path inside the other has none, in which case nothing changes and a message says why. Paths that touch, from outside or from inside, share one tangent there instead: a line centered on the point where they touch and as long as the narrower path is wide along it. Since 2026-11-18 one of the two may be a point (a path of one anchor): the lines run from the point to where they touch the path, two from a point outside it, one at a point on its outline, or at most a billionth of the larger of the path's size and the point's distance from its center away from it (centered on the point, or covering the straight side it lies on), and none from a point inside, with a message; the centerline runs from the point to the path's center, and every Tangents choice gives the same lines. The lines take the current stroke and no fill; one undo step. The dialog has Preview. Tests: `addons::pathtools::tangents::tests` in `vectorcraft-pathops` (circles against the closed form, turned ellipses against a brute-force scan, nested, overlapping and touching circles, a convex Bézier path, flat sides, squares meeting at a corner, a curve touched beside an anchor, a point outside a turned ellipse, on a circle, inside it, beside a square and at its corner, on a turned outline, within the touching tolerance, refused outlines), `cmd::addons::pathtools::tangents::tests` in `vectorcraft-engine`, `common_tangents_previews_cancels_and_runs_on_ok` and `common_tangents_on_a_point_gives_the_same_lines_for_every_choice` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Path Precision Tools add-on. ## Path Precision Tools add-on: Divide into Dashes (2026-11-01) @@ -2838,10 +2887,18 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov A VectorCraft addition, so no area score moves. Object › Plug-ins › Path Precision Tools › Tangent Circle… (`addon.pathtools.tangentCircle`) draws the circles that touch two selected paths or compound paths at a set radius, or that touch three of them; for three circles these are the solutions of the [problem of Apollonius](https://en.wikipedia.org/wiki/Problem_of_Apollonius), up to eight. The rest is VectorCraft's own: a circle touches a shape when it meets the outline without crossing it (the whole outline outside the circle or inside it), so it is tangent at a smooth point and passes through a corner or an open end; circles, ellipses at any angle and other closed or open paths all take part, a compound path's members as one outline. Circles are solved in closed form, each answer then moved onto the drawn Bézier outlines; other shapes are searched on a grid and refined with Newton's method on the curves, and with three shapes circles up to 64 times the diagonal of the box around the shapes' anchors and handles are found. The circles are listed by radius, then top to bottom, then left to right; the dialog previews every circle found, or one picked by number, and OK draws them with the current paint as one undo step. No circle, more than 64 (shapes touched along a whole curve) and more than 2000 segments are errors. Tests: `tangent_circle::tests` in `vectorcraft-pathops` (three circles: two known circles and eight distinct ones in a steady order; two circles and a radius; the search against the closed form; rotated and skewed ellipses against an independent solve of every combination; two circles close together; squares; a compound path moved far off and scaled; open paths and the errors), `cmd::addons::pathtools::tangent_circle::tests` in `vectorcraft-engine`, `tangent_circle_previews_picks_one_cancels_and_runs_on_ok` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Path Precision Tools add-on. +## Path Precision Tools add-on: Add Bounding Rectangle and Add Bounding Circle (2026-11-17) + +A VectorCraft addition, so no area score moves. Object › Plug-ins › Path Precision Tools › Add Bounding Rectangle (`addon.pathtools.boundingRectangle`) draws a live rectangle on the selection's geometric bounding box, and Add Bounding Circle (`addon.pathtools.boundingCircle`) draws the [smallest enclosing circle](https://en.wikipedia.org/wiki/Smallest-circle_problem) of the selected outlines, with curves flattened to within 0.01 pt and the radius 0.01 pt larger, so the circle holds the curves. A curve is split into 1,024 pieces at most. One command makes at most 1,048,576 splits at any depth, and with `each` every shape gets an equal share. A shape that has used up its share splits each further curve into at most 8 pieces, with at most 7,340,032 more splits shared the same way (8,388,608 in all), and then counts each further curve whole. A piece that still bends more counts by the hull of its control points cut down to its bounding box, which can make the circle larger than the smallest one. Before the 0.01 pt is added, the circle around a circle of four curves is less than 0.3% larger when each curve is split into 8 pieces, and about 14% larger when each counts whole. Both use the current paint, go on top of the current layer or the isolated group, and are one undo step; shapes with no size are skipped (#6966). The commands take `each` (one shape per object) and `offset`, and the menu items Add Bounding Rectangle… and Add Bounding Circle… open a dialog with Offset, One per Object and Preview. Tests: `shapes::tests` in `vectorcraft-geom` (`enclosing`, `convex_hull`), `cmd::addons::pathtools::bounding::tests` in `vectorcraft-engine` and `addons::pathtools::tests` in `vectorcraft-ui-egui` (`add_bounding_rectangle_and_circle_open_a_dialog_with_offset_and_one_per_object`). Commands: `docs/mcp.md` › Path Precision Tools add-on. + ## Path Precision Tools add-on: Expand Dashes into Paths (2026-11-01) A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Path Precision Tools › Expand Dashes into Paths turns the dashed stroke of each selected path and compound path into separate open paths, one per dash, for cutters and plotters that need the centre lines rather than Outline Stroke's filled outlines. The dashes are laid out by the renderer's own dash code, so they match what the canvas draws: the dash pattern, its offset and Align Dashes to Corners and Path Ends, a dash running on through the start of a closed path, a dash all the way round staying closed, and under a round or projecting cap each dot (a dash of no length) as a path on its point. Each dash keeps the path's appearance with the top stroke's dashes and arrowheads off; the path's fills stay on it, below its dashes; a compound path's dashes are plain paths. One undo step; the dashes are selected; at most 100000 (more, or a pattern too fine to draw, is refused). Tests: `expand_dashes_*` in `cmd::addons::pathtools::tests` in `vectorcraft-engine` (the stroke kept with dashes off, the offset, one undo step, the fill kept below, dashes centred on corners when aligned, dots under round and butt caps, compound paths, refusals and the piece cap), `the_plugins_submenu_selects_the_tools_and_opens_the_anchor_inspector` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Path Precision Tools add-on. +## Path Precision Tools add-on: Tangent Circle Tool (2026-11-17) + +A VectorCraft addition, so no area score moves. The Tangent Circle Tool (`tangentCircle`; Object › Plug-ins › Path Precision Tools and the All Tools drawer) draws a circle on two clicked path segments: tangent to the first at the point clicked (its center on the normal there) and touching the second segment or one beside it on its subpath, the touch nearest the pointer winning. Shift gives the circle the tool's radius, and a drag from the second segment sets the radius to the drag's length (Shift: steps of 1, 2 or 5 times a power of 10 pt, at least 4 screen pixels; Cmd/Ctrl: a tenth of the movement); with a radius the circle may touch the first segment anywhere along it. Before the click the circle shows with its center, radii and radius, or a note says there is none. The circles are found by sampling the distance to the second segments along the first segment's normal (or along the first segment, for a radius) and taking the places where it equals the radius (samples, bisection where it crosses, and a search where it only touches). Left out are circles whose nearest point of the second segments is not on the circle (within a millionth of the radius: where the first segment turns back on itself the distance jumps past the radius without a touch), circles that cross the first segment, circles that touch both segments at one point, circles without a finite radius above 0, and circles too small or too large for three of their points to give them back in floating point; a circle found twice (the same center, touching the first segment at the same point) is kept once. The circle is a new ellipse with the current paint, one undo step; the first segment stays picked until it is drawn, also when drawing fails or the press is canceled. Tests: `tangent_circle::tests` in `vectorcraft-pathops` (parallel and crossing lines, a curved second segment, a corner's fillet, lines twice the radius apart, a touch between the places tried, the ends of a line with its handles on its anchors, a circle that crosses the first segment, a first segment that turns back, no circle), `addons::tangent_circle::tests` in `vectorcraft-tools` (two clicks, Shift and the radius option, a drag with Shift and Cmd/Ctrl, no circle and Escape, a canceled press, a circle its three points cannot draw), the session test for a failed draw in `vectorcraft-engine` and the Path Precision Tools menu, options, drawer and catalog tests in `vectorcraft-ui-egui`. Commands: `docs/mcp.md` › Path Precision Tools add-on. + ## Path Precision Tools add-on: Trim at Crossings (2026-11-13) A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Path Precision Tools › Trim at Crossings Tool (also in the Scissors tool's group in both shipped toolbars, after the Knife, since 2026-11-16; a toolbar edited before keeps its saved layout until Reset Toolbar; no shortcut) removes stretches of paths between the places where they are crossed by another path or by themselves, on any path that can be edited, 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; each is one undo step, and Escape during a drag removes nothing. A closed path that loses a stretch becomes open, an open path that loses a middle stretch becomes two paths with its appearance in its place in the stacking order, a path that nothing crosses is removed whole, and the stretches that stay get no new anchors. Hidden and locked paths, guides and clipping paths are not trimmed and do not count as crossing. Add Points at / Split at Crossings share the crossing search: segments that meet at an anchor now count where they cross again elsewhere, and with Self Crossings a curved segment that loops over itself crosses itself. Command `addon.pathtools.trim`; `vectorcraft_pathops::addons::pathtools::{crossings_on, spans, without_spans}`. Hovering shows in red the stretch a click would remove, worked out by the same code the command uses (`vectorcraft_tools::addons::trim::plan`), and a drag that reaches at most 32 paths shows what its release would remove; a preview spends at most a twentieth of the crossing work a click may (2026-11-15; tests `hovering_*`, `in_isolation_mode_*`, `a_path_whose_crossings_*` and `a_small_drag_*` in `addons::trim` in `vectorcraft-tools`, `hovering_with_the_tool_shows_the_stretch_its_click_removes` and `what_the_tool_shows_*` in `vectorcraft-engine`). Not yet: crossings with type, images and symbol instances. Tests: `crossings_on_*`, `segments_*`, `a_segment_that_loops_over_itself_crosses_itself`, `one_work_budget_*`, `spans_divide_*`, `a_subpath_without_*` and `a_slice_*` in `addons::pathtools::tests` in `vectorcraft-pathops`, `addons::trim` in `vectorcraft-tools` (click, rectangle, freehand line, Escape), `cmd::addons::pathtools::trim::tests` in `vectorcraft-engine` (a middle and an end stretch, a closed path opening, a rectangle and a line as one undo step, locked and hidden paths, guides and clipping paths, paths nothing crosses, compound path members, the selection, 3,000 other paths, a path too large to search left alone until touched, bad params refused), `the_plugins_submenu_selects_the_tools_and_opens_the_anchor_inspector` in `vectorcraft-ui-egui`, `edit_toolbar::tests` and `command_sweep`. Commands: `docs/mcp.md` › Path Precision Tools add-on. The tool shows the Knife's cursor, now drawn as a knife with the blade's point on the hotspot (2026-11-16; tests `trim_at_crossings_is_in_the_scissors_flyout` and `a_saved_toolbar_without_trim_at_crossings_keeps_its_layout` in `edit_toolbar::tests`, `trim_at_crossings_is_in_the_scissors_group_once` in `addons::tests`, `headless_backend_methods` in `vectorcraft-mcp`, `the_knife_shows_a_knife_with_its_point_on_the_hotspot` in `cursors::tests` and `drawing_tools_show_their_own_cursor` in `vectorcraft-tools`). @@ -2852,7 +2909,7 @@ A trim reads the selection through a set and changes it once at the end, instead 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. -Constant Gap sets the arcs' radius to the smaller circle's radius plus a gap in points (`gap`), so each arc stays that gap from a circle of the smaller circle's size about the arc's center: in a triangular grid of equal circles that gap apart, the channels around an empty place are one width. With three or more circles selected, every two whose outlines are within Reach (`reach`, 10 pt by default) are bridged, the bridges that connect are united into one shape each (holes included, except those smaller than 1% of the smallest circle's area), a pair too far apart for the radius gets no bridge, and a circle bridged to no other stays as it is; at most 2000 circles and 8000 bridges, found through a grid of cells so each circle is compared only with its near neighbors. Reach is unavailable in the dialog with two circles selected, which are bridged at any distance. Tests: `bridge::tests` in `vectorcraft-pathops` (a 3 × 3 grid joined by side neighbors only or with the diagonal ones, a ring of six around an empty place leaving a round hole the gap wider than a circle, each pair's shape the two-circle outline for overlapping, touching and unequal circles, a circle out of reach left alone, a pair too far apart for the arcs left unbridged, the gap form against the percentage form, too many circles or bridges and pairs that can't be bridged refused), `bridge::tests` in `cmd::addons::pathtools` in `vectorcraft-engine` (the grid as one shape in the topmost circle's place with its holes, one undo step, a circle left alone, small circles at the default reach, an id given twice, Keep Originals for several shapes, the gap form, refusals and their messages) and `constant_gap_shows_the_gap_and_bridges_many_circles_within_reach` in `vectorcraft-ui-egui`. +Constant Gap sets the arcs' radius to the smaller circle's radius plus a gap in points (`gap`), so each arc stays that gap from a circle of the smaller circle's size about the arc's center: in a triangular grid of equal circles that gap apart, the channels around an empty place are one width. With three or more circles selected, every two whose outlines are within Reach (`reach`, 10 pt by default) are bridged, the bridges that connect are united into one shape each (holes included, except those smaller than 1% of the smallest circle's area), a pair too far apart for the radius gets no bridge, and a circle bridged to no other stays as it is; at most 2000 circles and 8000 bridges, found through a grid of cells so each circle is compared only with its near neighbors. Reach is unavailable in the dialog with two circles selected, which Reach does not limit; the radius can still be too small to bridge them. Tests: `bridge::tests` in `vectorcraft-pathops` (a 3 × 3 grid joined by side neighbors only or with the diagonal ones, a ring of six around an empty place leaving a round hole the gap wider than a circle, each pair's shape the two-circle outline for overlapping, touching and unequal circles, a circle out of reach left alone, a pair too far apart for the arcs left unbridged, the gap form against the percentage form, too many circles or bridges and pairs that can't be bridged refused, the bridge limit counting only the necks left after those too thin for the precision are dropped), `bridge::tests` in `cmd::addons::pathtools` in `vectorcraft-engine` (the grid as one shape in the topmost circle's place with its holes, one undo step, a circle left alone, small circles at the default reach, an id given twice, Keep Originals for several shapes, the gap form, refusals and their messages) and `constant_gap_shows_the_gap_and_bridges_many_circles_within_reach` in `vectorcraft-ui-egui`. ## Document Tools add-on: Save a Timestamped Copy (2026-11-01) @@ -2993,6 +3050,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | Date | Change | Summary | |---|---|---| +| 2026-11-18 | minor | Layers panel: context menu on guide rows (Release Guide, Duplicate, Delete Guide, Lock/Unlock, Hide/Show) with one-step undo; regression tests in `crates/ui-egui/src/panels/layers/tests.rs`; scores and estimates unchanged. | | 2026-11-18 | minor | Type advanced: Retype phase 1 (`type.retype`, #4934), exact matches of available fonts become point text again; evidence added; near matches, the ranked font list and images remain; score and hours unchanged | | 2026-11-18 | minor | Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538). Scores and estimates unchanged. | | 2026-11-18 | minor | Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged. See [production-preflight.md](production-preflight.md) for scope and limits. | @@ -3042,7 +3100,9 @@ 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 | M5/G15: text thread overlay membership indexing, focused output controls and matched component timings (#6543); scores and 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-11 | minor | Drawing tools: Scissors hover and cuts share the Pen's snapping (#6470), with current view options, Alt Add Anchor and endpoint selection retained; source and headless regressions listed. Scores and hours unchanged (estimated). | | 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 4826df3552..35b097f4ac 100644 --- a/docs/three-d.md +++ b/docs/three-d.md @@ -559,6 +559,49 @@ These rules are VectorCraft's own: in the layers, in the art of symbols, patterns, graph designs, brushes and opacity masks, and in graphic styles, and Select All Unused in the Symbols panel counts a symbol a graphic uses as used, a graphic in a graphic style included. +## Map Art + +The Extrude & Bevel (Classic) and Revolve (Classic) dialogs have a **Map Art…** button on their Object tab. It +shows Map Art in place of the tabs until **Done**, and the dialog's Preview, OK and Cancel apply to the maps with the +other settings ([Map artwork to a 3D object](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=189), +[the same section in the 2010 help](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=274)). +Rotate (Classic) and the other 3D effects take no map. The command is `threeD.mapArt` ([mcp.md](mcp.md#map-art)). + +- **Surface**: the first, previous, next and last buttons and a number field pick the surface, with the count beside + them. A light gray mark shows that the surface faces the viewer and a dark gray mark that it is hidden. With Preview + on, the surface is outlined in red on the artboard. +- **Symbol**: None or one of the document's symbols. Each surface keeps one symbol. +- The surface is shown laid out flat with the box of the mapped art on it. A drag inside the box moves the art, a + drag of a side or corner handle scales it about its center, and a drag just outside the box turns it. X, Y, + Horizontal Scale, Vertical Scale and Rotation give the same values as numbers. +- **Scale to Fit** centers the art and scales it to fill the surface. **Clear** removes the surface's map, as None + does, and **Clear All** removes every map. +- **Shade Artwork** gives the mapped art the tone and highlight of the face it lies on. **Invisible Geometry** + draws the mapped art and leaves out the solid's faces. + +Extrude & Bevel (Classic) numbers its surfaces through the object's solids in the order they are built (the top fill's +solid, then each stroke's): each solid's front cap and back cap, then each side wall from corner to corner of the +outline, then the bevel above each wall. An extruded square has six surfaces. A hollow solid has no caps to number, +and a solid whose bevel is as deep as the solid has no walls. +A side wall is laid out at its own length, which a bevel added around the shape makes longer than the outline. A bevel +is laid out at the length of the wall below it, so mapped art on a bevel is stretched or squeezed along its edge +nearer the cap. Revolve (Classic) has one surface, its swept side, unrolled around the axis as Revolve's graphics are; on a group it is +the side of the member with the longest profile, and Invisible Geometry leaves out every member's faces. The numbering +is VectorCraft's own. + +- A map's X and Y place the center of the art from the center of the surface laid out flat, so a map follows the + center when the surface changes size. A map past the object's surface count draws nothing and stays in the effect. +- Mapped art is drawn on the parts of its surface that face the viewer, clipped to the surface, and over a wall, a + bevel or Revolve's side it bends with the facets. The Wireframe surface draws no mapped art. +- The canvas, exports, printing and **Object › Expand Appearance** draw the mapped art the same way. Renaming a symbol + renames it in the maps, copying the object to another document brings the symbols its maps use, and Select All + Unused counts a symbol a map uses as used. +- A map's art follows the rules and limits of a graphic's art ([Graphics](#graphics)). An object takes up to 64 maps, + and its maps share the 400,000 path elements of one 3D effect's graphics; past that limit the object draws without + its mapped art. The art of the maps on walls, bevels and Revolve's side, at each map's scale and with its curves cut + into straight pieces, may also take at most 400,000 points together, and commands refuse art past it. The limits and the shading of the mapped art are + VectorCraft's own. + ## Parameters (`effect.apply`, `effect.setParams`) `threeD.extrude`: `depth`, `twist`, `taper` (%), `cap`, `bevel` (`none`, `classic`, `rounded`, `cove`, `step`, @@ -634,7 +677,8 @@ out, perspective). No Adobe software, assets, presets or bevel shapes were used. the faces are shaded with it is VectorCraft's own. The Black Overprint shading color keeps each face's paint and draws the shading over it as overprinting black, without the highlight. The shading is on the black plate in Separations Preview and PDF output. Their Rotation tab has the track cube - ([Track cube](#track-cube)). Map art, Turntable and 3D export are separate, unbuilt items. + ([Track cube](#track-cube)). Extrude & Bevel (Classic) and Revolve (Classic) take Map Art + ([Map Art](#map-art)). Turntable and 3D export are separate, unbuilt items. Release measurements and a repeatable CLI scene are in [3D lighting performance](3d-lighting-performance.md). diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 64e6be0b94..496e486a3f 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -16,8 +16,14 @@ > **Flyout update:** 2026-11-06 — resizable icon-strip flyouts and bottom-aligned panel footers (#5713); scores and estimates unchanged. +> Scissors snapping update (2026-11-11): with Alt released, hover and cuts use the Pen's path, alignment, intersection and anchor snaps (#6470). Scores and estimates unchanged. + ## Feature submission evidence +Draft enhancement #5804: Preferences › File Handling can select a raster editor through the native picker, with a private draft outside engine preferences and generic dialog fields. OK saves it, Cancel discards it, and Reset restores PhotoCraft. With Use System Defaults off, a missing chosen editor falls back to PhotoCraft, then the system default; validation and launch failures are reported. Control/MCP and synthetic input cannot choose an application or run external Edit Original. Web behavior, parity scores and estimates are unchanged; macOS/Linux smoke tests remain pending. + +**2026-11-09 revision:** draft implementation and regression coverage for #5804; no parity rescore. + Numeric fields step on wheel hover without taking keyboard focus (#5949). Arrow keys still require focus; modifiers, units, limits, mixed values and existing rounding stay in the shared stepping path. Headless regressions in `tests/numfields.rs` cover hovered unfocused fields, focused fields, trackpad accumulation and panel scroll exclusion. Scores and estimates unchanged. A flare keeps its settings through transforms and saves. With a flare selected, double-clicking the Flare tool opens Flare Tool Options filled from it, and OK draws it again in its place as one undo step (`shape.editFlare`; none when nothing changed); the Flare tool shows the selected flare's center and end handles, and dragging either changes its length or direction; Object › Expand turns it into plain objects ([Draw and edit flares](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-and-edit-flares.html)). Regressions: `edit_flare_draws_a_transformed_flare_again_in_its_place_in_one_undo_step`, `dragging_a_selected_flares_handles_changes_its_length_and_direction` and `with_a_flare_selected_the_options_show_its_settings_and_ok_draws_it_again`. Scores and estimates unchanged. @@ -182,6 +188,7 @@ tools, never checked side by side) isn't captured row by row. | Pen cursors (new path ×, continue /, close o, add +, delete −, convert ^) | done | the nib is a fountain-pen nib, tip on the hotspot, with the slit widening into the breather hole and the heel clipped square to its axis; bitmap tests at 1× and 2× pin the nib and the new-path asterisk, and in-app screenshots compare the Pen with Direct Selection | | Node-editing cursors: Direct Selection's white arrow with a hollow or filled square over an anchor (path unselected or selected); the Reshape Segment cursor over a curved segment (Direct Selection, Anchor Point, the Pen with Alt); the Anchor Point caret for the Pen with Alt; Group Selection's plus (also Direct Selection with Alt); a filled arrow while dragging that turns hollow on a snap; a double arrowhead for an Alt-drag copy | partial | as the public manual describes them, drawn in code; no cue over handles (none documented) | | Anchor Point and Curvature tools' own cursors | done | the caret on the anchor it converts; the pen nib with a curve badge | +| Scissors hover and cuts use the Pen's path, alignment, intersection and anchor snapping (#6470) | implemented | Existing Smart Guides, Snap to Point, pixel and grid options apply; Pixel Preview turns off Smart Guides. Alt still adds an anchor without cutting, and a cut still leaves one new endpoint selected. Headless regressions: `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/scissors_snap.rs`. | | Free Transform's Cmd/Ctrl side-shear cursor | done | two arrows passing along the side (ShearH, ShearV), instead of the resize arrow across it | | Live Paint Bucket cursors | partial | a filled bucket over a face a click fills, a brush over an edge it paints, an empty bucket where it paints nothing, following Paint Fills, Paint Strokes and Shift; the Eyedropper with Alt; the crosshair with Use Precise Cursors. No cursor swatch preview | | Cursors of their own for Lasso, Magic Wand, the freehand tools, Shaper, Measure, Print Tiling, the symbolism tools, vertical type, Scissors (over a segment and away), Mesh and Puppet Warp | partial | each tool returns its own cursor and Use Precise Cursors turns them into the crosshair; until they're drawn they borrow the crosshair, the I-beam, the Pen's add cursor or not-allowed | @@ -254,9 +261,9 @@ tools, never checked side by side) isn't captured row by row. | Escape cancels a Direct Selection drag | done | #1803 (#1743) | | Live Corners widgets (radius readout, Alt-click cycles kind, double-click the Corners dialog) | done | a Direct Selection click on a widget selects its corner (#1239), and with every corner selected a Shift-click on a widget picks that corner alone instead of deselecting it (#5188); a press-and-drag on a widget of a path selected whole still rounds every corner (#908), and adding widgets to the selection by Shift-click (#1232) is missing; the bounding box hides while a widget is dragged with the Selection tool (#1229); a round corner next to a curved side curves smoothly instead of sticking out of the shape (#1512); a corner rounds until its cut reaches its neighbours' cuts, so one corner of a square alone reaches the whole side (#2332) | | Corners between curved sides (#1144), Relative rounding | done | #1144 closed; Relative rounding in the Corners dialog (Relative / Absolute, radius as a percentage of each corner's maximum, kept as the shape is resized; `object.setLiveShape` `relativeRadii`, #3091, `tests_livecorners::relative_corner_rounding_keeps_fraction_on_resize`) | -| Pie widgets on a live ellipse: drag one to set Pie Start or End Angle, double-click one to make the ellipse whole | done | Selection tool, with the bounding box showing | -| Side widget on a live polygon: drag it to set the number of sides from 3 to 11 | done | Selection tool and the Rectangle, Rounded Rectangle, Ellipse, Polygon and Star tools, with the bounding box showing; a drag down adds sides and a drag up removes them; Escape cancels ([the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/add-or-remove-sides-from-polygons.html)) | -| A shape just drawn shows its bounding box and Live Shape widgets with the shape tool still active, and the selection can be moved and turned without switching tools | done | #5477: Rectangle, Rounded Rectangle, Ellipse, Polygon and Star keep the selection's bounding box, corner widgets and pie widgets on show while they draw nothing; a drag on a corner or pie widget adjusts it (arrows step the corner kind, Escape cancels), a press on the selection's centre point (Attributes › Show Center) moves the selection — the Selection tool's move arrow, snapping and Alt copy — a press just outside a corner of the box turns it about the centre (the Selection tool's rotate zone and cursor), and a press anywhere else draws (so a second shape drawn from the first one's centre moves the first: press elsewhere or deselect first). Public descriptions: [Live Shapes](https://helpx.adobe.com/illustrator/using/live-shapes.html) (live shapes adjust without switching tools) and [CreativePro, Working with Live Shapes](https://creativepro.com/?p=23921) (a widget shows in every corner on release; drag one toward the centre to round). A drag on one of the box's handles scales the selection as the Selection tool's handles do. A double-click on a corner widget of a selected live rectangle or polygon shows and selects the Transform panel where it is (closed, docked, floating or in an icon column; a second double-click keeps it on show), and leaves the tool, the selection and the document as they were; a double-click on a pie widget, off the widgets, with Show Corner Widget off or with Line Segment does nothing, and the Selection tool's double-click on a corner widget still opens the Corners dialog. Public description: [Live shape properties](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/live-shape-properties.html) (a double-click on a corner widget of a selected live shape opens the Transform panel). Tests `a_shape_tool_drags_the_selected_shapes_widgets`, `a_shape_tool_moves_the_selection_by_its_centre_point_and_turns_it_from_a_corner`, `a_shape_tool_scales_the_selection_by_its_bounding_box_handles`, `a_double_click_on_a_corner_widget_shows_the_transform_panel`, `a_double_click_on_a_corner_widget_with_a_shape_tool_asks_for_the_transform_panel` (engine), `a_corner_widget_double_click_with_a_shape_tool_requests_the_transform_panel` (MCP: the `pointer_gesture` reply's `requests` carry `{"panel": "transform"}`) and `a_tools_panel_request_shows_the_panel_and_a_second_keeps_it_shown` (UI) | +| Pie widgets on a live ellipse: drag one to set Pie Start or End Angle, double-click one to make the ellipse whole | done | Selection tool, with the bounding box showing, while the Control bar's Hide Shape Widgets has not hidden the widgets | +| Side widget on a live polygon: drag it to set the number of sides from 3 to 11 | done | Selection tool and the Rectangle, Rounded Rectangle, Ellipse, Polygon and Star tools, with the bounding box showing, while the Control bar's Hide Shape Widgets has not hidden the widgets; a drag down adds sides and a drag up removes them; Escape cancels ([the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/add-or-remove-sides-from-polygons.html)) | +| A shape just drawn shows its bounding box and Live Shape widgets with the shape tool still active, and the selection can be moved and turned without switching tools | done | #5477: Rectangle, Rounded Rectangle, Ellipse, Polygon and Star keep the selection's bounding box, corner widgets and pie widgets on show while they draw nothing (the corner and pie widgets only while the Control bar's Hide Shape Widgets has not hidden them; the bounding box stays); a drag on a corner or pie widget adjusts it (arrows step the corner kind, Escape cancels), a press on the selection's centre point (Attributes › Show Center) moves the selection — the Selection tool's move arrow, snapping and Alt copy — a press just outside a corner of the box turns it about the centre (the Selection tool's rotate zone and cursor), and a press anywhere else draws (so a second shape drawn from the first one's centre moves the first: press elsewhere or deselect first). Public descriptions: [Live Shapes](https://helpx.adobe.com/illustrator/using/live-shapes.html) (live shapes adjust without switching tools) and [CreativePro, Working with Live Shapes](https://creativepro.com/?p=23921) (a widget shows in every corner on release; drag one toward the centre to round). A drag on one of the box's handles scales the selection as the Selection tool's handles do. A double-click on a corner widget of a selected live rectangle or polygon shows and selects the Transform panel where it is (closed, docked, floating or in an icon column; a second double-click keeps it on show), and leaves the tool, the selection and the document as they were; a double-click on a pie widget, off the widgets, with Show Corner Widget off or with Line Segment does nothing, and the Selection tool's double-click on a corner widget still opens the Corners dialog. Public description: [Live shape properties](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/live-shape-properties.html) (a double-click on a corner widget of a selected live shape opens the Transform panel). Tests `a_shape_tool_drags_the_selected_shapes_widgets`, `a_shape_tool_moves_the_selection_by_its_centre_point_and_turns_it_from_a_corner`, `a_shape_tool_scales_the_selection_by_its_bounding_box_handles`, `a_double_click_on_a_corner_widget_shows_the_transform_panel`, `a_double_click_on_a_corner_widget_with_a_shape_tool_asks_for_the_transform_panel` (engine), `a_corner_widget_double_click_with_a_shape_tool_requests_the_transform_panel` (MCP: the `pointer_gesture` reply's `requests` carry `{"panel": "transform"}`) and `a_tools_panel_request_shows_the_panel_and_a_second_keeps_it_shown` (UI) | | Isolation mode by double-click (groups and single objects), breadcrumbs, Esc to exit | done | Single paths, compound paths, images, meshes and placed files isolate too ([helpx: Isolate objects](https://helpx.adobe.com/africa/illustrator/desktop/manage-objects/select-objects/isolate-objects.html)); locking or hiding the layer (or a group) around the isolated object afterwards keeps clicks and marquees off it, as outside isolation mode (#5309) | | "Magnetic" moves of selected anchors with a modifier (#955 request) | missing | not a feature of the reference app as documented; under discussion | | Coinciding anchors of overlapping objects: the selected object's anchor is taken, also under another object | done | #1508 | @@ -302,6 +309,7 @@ tools, never checked side by side) isn't captured row by row. | Free Transform, Scale and Reflect along a rotated box | done | The Scale and Reflect tools, dialogs and commands and the Transform and Properties panels' flips act along the turned box until Reset Bounding Box; `basis: "page"` keeps the page's axes | | Free Transform widget: constrain, free distort, perspective distort; the key-held variants | done | | | Transform tools: click sets the reference point (snaps to anchors/centres), Alt-click opens the dialog, Alt-release copies | done | with anchors selected with Direct Selection, the tools, the dialogs and Move transform those anchors alone, about the centre of their box by default (#1408; the default point and whole-object copies are our choices) | +| Reflect tool: a second click reflects across the line through both clicked points; Alt on it reflects a copy | done | [the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/reflect-or-flip-objects.html); one undo step; a second click whose snapped point is within 3 screen pixels of the first one's, Escape or a changed selection leaves nothing reflected (our choices) | | Move, Rotate, Scale, Reflect and Shear dialogs: live Preview; Up/Down step angles and percentages by 1, Shift by 10 | done | #1412; Preview starts off (our choice: the public documentation gives no default), Move's as it was last confirmed; OK is one undo step and Transform Again repeats it | | Transform Again, Transform Each, Scale Strokes & Effects, Scale Corners | done | | | The Transform effect dialog previews valid typed scale, move, rotation, and Copies values while fields remain focused. Preview off defers the artwork change until OK; Cancel restores the original artwork. | done | `crates/ui-egui/src/panels/tests_appearance.rs` covers numeric input, sliders, artwork targets, preview, and undo. | @@ -472,7 +480,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Info panel follows the tool in use: W and H show the change in x and y, with the distance and the angle, while the selection moves, the Gradient tool draws a vector or a Pen drag pulls out an anchor's handle; the Scale tool's percentages; the center and angles of a Rotate, Reflect or Shear tool drag; the Zoom tool's magnification; the Paintbrush's brush. W and H follow Use Preview Bounds, several selected objects show only the paint and type they share, and Show Options names a tint or a gradient swatch | done | `info.readout`; `Tool::readout`; behavior from the Info panel overview in the [archived user guide](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=76); number formats, the rows shown between drags and the Direct Selection and Group Selection readouts are VectorCraft's own | | Make Compound Path on a group (such as outlined type) keeps its backmost path's paint; compound paths joined into one keep their holes | done | #1537 | | Symbol libraries: Window › Symbol Libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, User Defined, Other Library…, Save Symbols…) and the Symbols panel's Symbol Libraries Menu button and its menu's Open Symbol Library / Save Symbol Library…; a click on a library symbol adds it to the document's Symbols (one undo step, it becomes the current symbol), Shift/Cmd-clicks select for Add to Symbols, and a symbol dragged onto the canvas is added and placed where it is dropped | done | [public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html), [Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), [placing from a library](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html); `window.symbolLibrary`, `window.symbolLibrary.other`, `ui.saveSymbolLibrary` (dialog `saveSymbolLibrary`), `window.userSymbolLibrary1`…`10`; `panels::tests_symbol_libraries`; five built-in libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons; original, generated in code) | -| Brush libraries: Window › Brush Libraries (Art Ribbons, Ink and Wash, Calligraphic Nibs, Pressure Sensitive, Bristle Brushes, Pattern Borders, Scatter Shapes, Game Trails, Energy Beams, Dry Media, Tech Circuit, Arrows, User Defined, Other Library…, Save Brushes…) and the Brushes panel's Brush Libraries Menu button and its menu's Open Brush Library / Save Brush Library…; a click on a library brush adds it to the document's Brushes (one undo step, it becomes the current brush, and selected paths take it in the same step), Shift/Cmd-clicks select for Add to Brushes, a brush dragged onto a path is added and applied to it and one dragged onto the Brushes panel is added; thumbnails render with the library's patterns and symbols | done | [public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel overview](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html); `window.brushLibrary`, `window.brushLibrary.other`, `ui.saveBrushLibrary` (dialog `saveBrushLibrary`), `window.userBrushLibrary1`…`10`; `panels::tests_brush_libraries`; twelve built-in libraries (original, generated in code) | +| Brush libraries: Window › Brush Libraries (Art Ribbons, Ink and Wash, Calligraphic Nibs, Pressure Sensitive, Bristle Brushes, Pattern Borders, Scatter Shapes, Stipple, Game Trails, Energy Beams, Dry Media, Tech Circuit, Arrows, User Defined, Other Library…, Save Brushes…) and the Brushes panel's Brush Libraries Menu button and its menu's Open Brush Library / Save Brush Library…; a click on a library brush adds it to the document's Brushes (one undo step, it becomes the current brush, and selected paths take it in the same step), Shift/Cmd-clicks select for Add to Brushes, a brush dragged onto a path is added and applied to it and one dragged onto the Brushes panel is added; thumbnails render with the library's patterns and symbols | done | [public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel overview](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html); `window.brushLibrary`, `window.brushLibrary.other`, `ui.saveBrushLibrary` (dialog `saveBrushLibrary`), `window.userBrushLibrary1`…`10`; `panels::tests_brush_libraries`; thirteen built-in libraries (original, generated in code) | | Brushes panel menu › Options of Selected Object…: changes the selected brushed paths' brush settings on those paths only, leaving the brush and its other strokes as they are; the brush type's options dialog opens without the Name row (and without an art brush's scale and direction options or a pattern brush's tiles), and OK sends only the values changed in it | done | [Modify brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/modify-brushes.html), [Brushes panel overview](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html); `brush.objectOptions`, `ui.brushObjectOptions`; which fields a path can set is VectorCraft's own choice (calligraphic, scatter, art and pattern brushes; not bristle); `options_of_selected_object_*` tests in `crates/engine/src/tests/brushsym.rs` and `crates/ui-egui/src/dialogs/brush_options/tests.rs`, brush tests in `crates/brush/src/tests.rs` | | Symbols panel: New Symbol opens Symbol Options (Name) before making the symbol; Alt-click skips it | partial | #1560 (#1566); Registration 9-point grid in Symbol Options (`symbol.new` / `symbol.place`); Export Type (Graphic / Movie Clip) and Enable Guides for 9-Slice Scaling (scaled instances keep their corners; in symbol editing mode the guides are drawn over the art and the Selection tool drags them); Symbol Type (Dynamic Symbol / Static Symbol, new symbols dynamic; #4938); Align to Pixel Grid (`alignToPixelGrid` on `symbol.new` / `symbol.options`: the art snaps at the symbol's natural size and instances at that size stay on whole points; [Aligning symbols to pixel grid](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=28)) | | Dynamic symbols: an instance changes the fill, stroke, opacity and blend of objects in its symbol's art and stays linked; Reset in the Properties panel's Quick Actions and the Symbols panel menu (Reset Symbol Instance) | partial | #4938; `symbol.instance.setAppearance` (by child-index path) and `symbol.instance.reset`; redefining keeps the changes, Break Link bakes them; Direct Selection of a path, compound path or type object inside an instance, with the Fill/Stroke controls setting its solid fill or stroke, is on canvas; on-canvas editing beyond a solid fill and stroke, and `.ai` read and write, remain | @@ -517,13 +525,15 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Document Tools add-on (VectorCraft addition): Object › Plug-ins › Document Tools › Batch Trace Folder asks for a folder of images, then a destination folder, traces each image with a preset (optionally expanded) and saves it there as `.vectorcraft`, `.svg`, `.pdf`, `.ai` or `.eps` under its own name (taken names numbered, nothing replaced), closing each image again; the status bar counts the images traced and those that couldn't be; off on the web | done | #4921; `addon.document.batchTraceFolder`, `crates/engine/src/cmd/addons/document/batch_trace.rs`, `crates/ui-egui/src/addons/document.rs` and their tests; not a feature of the reference app | | Document Tools add-on (VectorCraft addition): Object › Plug-ins › Document Tools › New Symbols from Layers makes a symbol of each layer's art named after the layer (the highlighted layers when two or more are, else all); Convert Layers to Symbols also replaces each layer's art with an instance in place; empty layers skipped, one undo step | done | #4927; `addon.document.symbolsFromLayers`, `crates/engine/src/cmd/addons/document.rs`, `crates/ui-egui/src/addons/document.rs` and their tests; not a feature of the reference app, so it is not scored | | Smart Pen add-on (VectorCraft addition): Object › Plug-ins › Smart Pen selects the Smart Pen Tool, which the All Tools drawer lists under its own heading but neither toolbar shows as shipped (no shortcut), and opens the Smart Pen panel (next segment straight or curved; Remove Points Keep Shape, Make Smooth, Make Corner, Retract Handles, Close or Join). The tool draws (click: straight or curved segment, a curve after a straight one tangent; drag: smooth anchor, Alt breaks the handle, Shift 45°, Space moves it; Tab switches a segment; rubber band; close, join, continue) and edits without switching tools (click selects a point, drag moves it, Alt-click removes it keeping the shape, Shift+Alt-click deletes it, double-click toggles smooth/corner; handle drags with Shift and Alt; segment drags reshape, Alt-click adds a point) | done | `addon.pen.*`, `crates/tools/src/addons/smart_pen.rs`, `crates/ui-egui/src/addons/pen.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 eight tools (Anchor Eraser Brush, Extend Path, Measure & Inspect, Parametric Shape, Corner Tool, Slide Anchor Along Path, Shared Edge Merge Tool, Trim at Crossings Tool), which the All Tools drawer lists under their own heading but neither toolbar shows as shipped (except Trim at Crossings, which both shipped toolbars and the drawer show in the Scissors tool's group), 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; the Corner Tool cuts editable corners on any path (hover shows the anchor, a click uses its radius and kind, a drag sizes the corner, Shift whole values; a corner's marker selects it and loads its values, drags to resize, to 0 or double-clicked removes it; never past what fits; Alt-marquee cuts every anchor inside) with a Corners section in the Anchor Inspector (radius, kind, selected count, Apply to Selected Anchors); Slide Anchor Along Path drags an anchor along its curve with the segments beside it refitted, Shift snapping where the tangent is a multiple of 45°; the Shared Edge Merge Tool shows, over two paths touching at two coincident anchors, the two stretches and the edge merging them, a click merges them (half way; Shift the upper path, Alt the lower), and near anchors meet or an anchor one path lacks is added to match (Shift+Alt asks for this inside a stretch), with a Shared Edges section in the Anchor Inspector (brush diameter, coincidence 0 to 3 pt, Keep Shared Points Together, which takes coincident anchors along with the add-on's own anchor moves); 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/` 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 nine tools (Anchor Eraser Brush, Extend Path, Measure & Inspect, Parametric Shape, Corner Tool, Slide Anchor Along Path, Shared Edge Merge Tool, Tangent Circle Tool, Trim at Crossings Tool), which the All Tools drawer lists under their own heading but neither toolbar shows as shipped (except Trim at Crossings, which both shipped toolbars and the drawer show in the Scissors tool's group), 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; the Corner Tool cuts editable corners on any path (hover shows the anchor, a click uses its radius and kind, a drag sizes the corner, Shift whole values; a corner's marker selects it and loads its values, drags to resize, to 0 or double-clicked removes it; never past what fits; Alt-marquee cuts every anchor inside) with a Corners section in the Anchor Inspector (radius, kind, selected count, Apply to Selected Anchors); Slide Anchor Along Path drags an anchor along its curve with the segments beside it refitted, Shift snapping where the tangent is a multiple of 45°; the Shared Edge Merge Tool shows, over two paths touching at two coincident anchors, the two stretches and the edge merging them, a click merges them (half way; Shift the upper path, Alt the lower), and near anchors meet or an anchor one path lacks is added to match (Shift+Alt asks for this inside a stretch), with a Shared Edges section in the Anchor Inspector (brush diameter, coincidence 0 to 3 pt, Keep Shared Points Together, which takes coincident anchors along with the add-on's own anchor moves); a double-click on the brush, Extend Path or Tangent Circle tool opens its options | done | `addon.pathtools.*`, `crates/tools/src/addons/`, `crates/ui-egui/src/addons/pathtools.rs`, `crates/ui-egui/src/addons/pathtools/` 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 › Divide into Dashes… (Dash and Gap in any unit, Fit to Corners and Ends, Remove Gaps; Preview) cuts the selected paths, or only their direct-selected segments, into open pieces along the curve, keeping their appearance, one undo step | done | #4950; `addon.pathtools.divideDashes`, `crates/pathops/src/addons/pathtools/dashes.rs`, `crates/ui-egui/src/addons/pathtools/dashes.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 › 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 › Tangent Circle Tool (also in the All Tools drawer): a click on a path segment, then on another, draws the circle tangent to the first at the point clicked that touches the second or a segment beside it; Shift uses the tool's radius (36 pt to start, set in its options) and a drag from the second segment sets the radius (Shift in round steps, Cmd/Ctrl slowly), the circle then touching the first segment anywhere along it; the circle shows with its center and radii first, or a note when there is none; one undo step | done | tool `tangentCircle` (in `crates/tools/src/addons/tangent_circle.rs`, geometry in `crates/pathops/src/addons/pathtools/tangent_circle/on_segments.rs`) and its tests; a VectorCraft addition, 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, or with Constant Gap that radius plus a gap; Reach; Keep Originals; Preview) joins two selected circles into one outline with two concave arcs that touch both circles, or three or more each to the others within reach, united where the bridges connect, in place of the circles or above them (a pair within reach gets no bridge when its arcs would not reach both circles or would cross, or when its neck would be thinner than the precision its shape is united at; a circle bridged to no other stays as it is); 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): Object › Plug-ins › Path Precision Tools › Add Bounding Rectangle… and Add Bounding Circle… draw a live rectangle on the selection's geometric bounding box, or the smallest live circle that holds its outlines, from a dialog with Offset, One per Object (a shape around each object instead of one around the whole selection) and Preview; one undo step | done | `addon.pathtools.boundingRectangle` and `addon.pathtools.boundingCircle` (in `crates/engine/src/cmd/addons/pathtools/bounding.rs`, the circle in `crates/geom/src/shapes.rs`, `enclosing_circle`; the dialog is the command dialog, `crates/ui-egui/src/dialogs/command.rs`) and their tests, with the menu items' test `add_bounding_rectangle_and_circle_open_a_dialog_with_offset_and_one_per_object` in `crates/ui-egui/src/addons/pathtools/tests.rs`; 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 | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools selects its six tools (Anchor Eraser Brush, Extend Path, Measure & Inspect, Parametric Shape, Corner Tool, Slide Anchor Along Path), 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; the Corner Tool cuts editable corners on any path (hover shows the anchor, a click uses its radius and kind, a drag sizes the corner, Shift whole values; a corner's marker selects it and loads its values, drags to resize, to 0 or double-clicked removes it; never past what fits; Alt-marquee cuts every anchor inside) with a Corners section in the Anchor Inspector (radius, kind, selected count, Apply to Selected Anchors); Slide Anchor Along Path drags an anchor along its curve with the segments beside it refitted, Shift snapping where the tangent is a multiple of 45°; 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/` and their tests; not a feature of the reference app, so it is not scored | @@ -620,6 +630,7 @@ before release (#6373). [Paint faces and edges](https://helpx.adobe.com/illustra | 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-11 | minor | Scissors hover and cuts share Pen-style path/align/intersect/anchor snapping (#6470), retaining view options, Alt Add Anchor and cut endpoint selection; headless tool and Session regressions referenced. 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. |