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/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/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/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..bf347d8ed6 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 @@ -1155,22 +1190,42 @@ fn group_art(doc: Option<&Document>, 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 +1925,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 +2185,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 +2221,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..7d909b7dda 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) 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/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/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/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/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/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/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_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/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/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..b6229b7bd1 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -623,6 +623,7 @@ pub(super) const ALLOWED: &[&str] = &[ "symbol.replace", "symbol.selectInstances", "symbol.setCurrent", + "symbol.setDensity", "symbol.sortByName", "symbol.spray", "symbol.unused", @@ -661,6 +662,7 @@ pub(super) const ALLOWED: &[&str] = &[ "text.thread.remove", "text.touchType", "threeD.addGraphic", + "threeD.mapArt", "threeD.mapGraphic", "transparency.disableOpacityMask", "transparency.editOpacityMask", @@ -684,6 +686,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..dd5d5c1628 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), 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/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/prefs.rs b/crates/engine/src/prefs.rs index d2e615992a..2a4cf188cd 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, @@ -453,6 +456,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, 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/tests.rs b/crates/engine/src/tests.rs index 38692e9056..c6d2d34834 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -199,6 +199,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/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/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/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/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/tooling.rs b/crates/engine/src/tooling.rs index 65ea837527..ee5e87fc90 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -1413,6 +1413,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/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/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..e3f59edba0 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1078,7 +1078,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", @@ -1495,7 +1495,7 @@ 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", @@ -1503,6 +1503,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{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", ), + ( + "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", "Export As…", @@ -1807,6 +1813,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/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/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..fc875fd8f2 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; 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/tools/src/catalog.rs b/crates/tools/src/catalog.rs index cd6cbf627a..3d33d93cbc 100644 --- a/crates/tools/src/catalog.rs +++ b/crates/tools/src/catalog.rs @@ -154,6 +154,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 +244,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/draw2.rs b/crates/tools/src/draw2.rs index 9401dcd4c2..2b1ed3fd80 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). 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/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/settings.rs b/crates/tools/src/settings.rs index 97e980e3c0..ad80fead13 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"]), 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/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 11c87d07ac..ec5f77662b 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"))] @@ -186,6 +187,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(), diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 701c0f5ffc..5a9e7f7b28 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); diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 3adab31ffa..8cc87bff47 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -10985,8 +10985,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 +11011,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 +11037,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 +11556,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 +11587,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 +11630,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 +13126,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 +13338,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..bff6f174b9 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]); 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/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/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..f3b3b6ae37 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -62,11 +62,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 +103,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 +177,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; @@ -385,6 +389,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 +401,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, @@ -425,6 +432,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, @@ -737,9 +745,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; } @@ -813,6 +830,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 +914,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/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/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/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/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/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..8f16594f1d 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 @@ -992,26 +993,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 +1052,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..b4fa08fb01 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(); 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/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index d371a5f1e4..7bf5e7ae2a 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -581,6 +581,9 @@ font-technology Variable Променливи Box Channel Канал на квадрата Color box Цветови квадрат Color Wheel Options Опции на цветното колело + Show Harmony Показване на хармонията + Harmony Rule Правило за хармония + Harmony color Цвят от хармонията Color Type: Цветен тип: Color: Цвят: Colorize Оцветяване @@ -999,10 +1002,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 +1234,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 +1349,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 Плоско лого @@ -2128,6 +2168,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 +2293,7 @@ font-technology Variable Променливи Pressure Натиск Tilt Наклон Bearing Азимут + Stylus Wheel Колелце на писалката Shape: Форма: Bristle Length: Дължина на косъма: Bristle Density: Плътност на косъмчетата: @@ -2274,6 +2324,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 липсва @@ -3278,6 +3331,7 @@ digits Malayalam Малаялам Save Preset Запази предварителна настройка Save Document Preset Запази предварителна настройка на документа Save Preset… Запази предварителна настройка… + Save Summary… Запази обобщението… Save Print Preset Запази предварителна настройка за печат Save Recovery Data Запази данни за възстановяване Save Save for Web Preset Запази предварителна настройка за „Запази за уеб“ @@ -3596,6 +3650,7 @@ digits Malayalam Малаялам Show Thumbnails Показване на миниатюри Show Tile Edge Показване на ръба на плочката Show Tints/Shades Показване на нюанси/затъмнения + Show Tool Cards Показване на карти на инструментите Show Tool Tips Показване на подсказки Show Transparency Grid Показване на шахматна дъска за прозрачност Show Video Rulers Показване на видеолинийки @@ -5001,6 +5056,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 графиката няма граници @@ -5364,6 +5420,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… Зърнистост… @@ -7684,6 +7759,39 @@ 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" +# 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 Комбинации със задържане @@ -7700,3 +7808,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 00d07d469d..44c9cb1f42 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… @@ -793,6 +804,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 +1054,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 +1155,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… @@ -2152,6 +2194,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 +2603,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 +2755,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. @@ -3324,6 +3382,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 +3489,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 +3619,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 +4207,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 @@ -5426,6 +5500,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 @@ -7739,6 +7814,39 @@ 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" +# 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 @@ -7755,3 +7863,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 78e5a77c9e..8deca8492d 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ó @@ -792,6 +793,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 +879,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 +1488,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 +1755,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 +2457,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 @@ -3317,6 +3373,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 @@ -4180,6 +4239,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 @@ -4911,6 +4971,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 @@ -5227,6 +5288,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 @@ -6574,6 +6646,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}` @@ -7180,6 +7253,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 @@ -7337,6 +7411,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 @@ -8641,6 +8758,39 @@ 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" +# 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 @@ -8659,3 +8809,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 bd3e76ec50..26b8adb9b9 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… @@ -807,6 +816,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 +1072,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 +1178,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… @@ -2224,6 +2264,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 +2677,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 +2838,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. @@ -3409,6 +3465,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 +3574,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 +3720,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 +4316,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í @@ -5763,6 +5835,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 @@ -6103,6 +6176,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ý @@ -10406,6 +10522,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 @@ -10452,3 +10601,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 3fb128a27a..b8c3592c2c 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… @@ -3482,6 +3493,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 +3727,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 +3827,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… @@ -4746,6 +4788,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 +5196,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 +5353,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. @@ -5911,6 +5969,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 +6040,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 +6175,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 +6750,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 @@ -7893,6 +7967,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 @@ -8186,6 +8261,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 @@ -10529,6 +10647,39 @@ 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" +# 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 @@ -10546,3 +10697,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 6ad4e3850b..d441ebcce3 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -585,6 +585,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 +1022,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 +1263,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 +1401,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 @@ -2224,6 +2262,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 +2344,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 +2375,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 @@ -3351,6 +3402,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 @@ -3686,6 +3738,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 @@ -5360,6 +5413,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 @@ -5819,6 +5873,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 @@ -5845,6 +5918,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 @@ -10019,6 +10135,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 @@ -10065,3 +10214,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 7d2e5b6363..2bf92b5aea 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -560,6 +560,9 @@ font-technology Variable Μεταβλητές Box Channel Κανάλι τετραγώνου Color box Τετράγωνο χρώματος Color Wheel Options Επιλογές χρωματικού τροχού + Show Harmony Εμφάνιση αρμονίας + Harmony Rule Κανόνας χρωματικής αρμονίας + Harmony color Χρώμα αρμονίας Color Type: Τύπος χρώματος: Color: Χρώμα: Colorize Χρωματισμός @@ -981,10 +984,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 +1223,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 +1339,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 Επίπεδο λογότυπο @@ -1976,6 +2014,7 @@ font-technology Variable Μεταβλητές Pressure Πίεση Tilt Κλίση Bearing Αζιμούθιο + Stylus Wheel Τροχός γραφίδας Shape: Σχήμα: New Brush… Νέο πινέλο… New Brush Νέο πινέλο @@ -1991,6 +2030,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 +2243,7 @@ font-technology Variable Μεταβλητές Save As… Αποθήκευση ως… Save for Web (Legacy)… Αποθήκευση για ιστό (παλαιού τύπου)… Save Preset… Αποθήκευση προεπιλογής… + Save Summary… Αποθήκευση σύνοψης… Save Selection… Αποθήκευση επιλογής… Update Selection Ενημέρωση επιλογής Saved Αποθηκεύτηκε @@ -3316,6 +3359,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 Μόνο προς τα έξω @@ -4388,6 +4440,7 @@ digits Malayalam Μαλαγιάλαμ Show Thumbnails Εμφάνιση μικρογραφιών Show Tile Edge Εμφάνιση ακμής πλακιδίου Show Tints/Shades Εμφάνιση αποχρώσεων/σκιάσεων + Show Tool Cards Εμφάνιση καρτών εργαλείων Show Tool Tips Εμφάνιση συμβουλών εργαλείων Show Transparency Grid Εμφάνιση πλέγματος διαφάνειας Show Video Rulers Εμφάνιση χαράκων βίντεο @@ -5138,6 +5191,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 λείπει ο δείκτης @@ -5413,6 +5467,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 το σχέδιο δεν έχει όρια @@ -5797,6 +5852,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 είναι περικομμένο @@ -5815,6 +5913,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 επιλέγει τη γραμμή τίτλου. @@ -8615,6 +8732,39 @@ 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" +# 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 Συντομεύσεις παρατεταμένου πατήματος @@ -8633,3 +8783,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 30678f8a13..daf3dcf3f9 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -605,6 +605,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 +1033,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 +1288,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 +1426,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 @@ -2223,6 +2261,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 +2388,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 +2419,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 @@ -3387,6 +3438,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 @@ -3719,6 +3771,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 @@ -5475,6 +5528,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 @@ -5841,6 +5895,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 @@ -5868,6 +5965,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… @@ -10361,6 +10477,39 @@ 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" +# 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 @@ -10379,3 +10528,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 873d339833..3328665e11 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… @@ -793,6 +802,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 +1051,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 +1152,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… @@ -2185,6 +2225,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 +2634,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 +2791,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. @@ -3351,6 +3407,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 +3514,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 +3657,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 +4233,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 @@ -5404,6 +5476,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 @@ -5678,6 +5751,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 @@ -6020,6 +6094,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 @@ -8698,6 +8815,39 @@ 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" +# 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 @@ -8716,3 +8866,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 68bcc455b2..2950c0d453 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -606,6 +606,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 +1036,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 +1279,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 +1416,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 @@ -2213,6 +2251,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 +2376,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 +2407,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 @@ -3375,6 +3426,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 @@ -3707,6 +3759,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 @@ -5430,6 +5483,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 @@ -5818,6 +5872,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é @@ -5845,6 +5942,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… @@ -10432,9 +10548,46 @@ 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 +# 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 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 d7bb081e02..11ea63328c 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 કેલિગ્રાફિક બ્રશ વિકલ્પો @@ -890,6 +909,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 +1165,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 ડ્રોઅર મેનુ @@ -3454,6 +3488,7 @@ Save Perspective Grid Preset પર્સ્પેક્ટિવ ગ્રિડ પ્રીસેટ સાચવો Save Preset પ્રીસેટ સાચવો Save Preset… પ્રીસેટ સાચવો… + Save Summary… સારાંશ સાચવો… Save Print Preset પ્રિન્ટ પ્રીસેટ સાચવો Save Recovery Data પુનઃપ્રાપ્તિ ડેટા સાચવો Save Save for Web Preset વેબ માટેનો પ્રીસેટ સાચવો @@ -3822,6 +3857,7 @@ Show Tile Edge ટાઇલ કિનારી બતાવો Show Tints/Shades ટિન્ટ/શેડ બતાવો Show Tool Group Labels ટૂલ ગ્રૂપ લેબલ બતાવો + Show Tool Cards ટૂલ કાર્ડ બતાવો Show Tool Tips ટૂલ ટિપ્સ બતાવો Show Toolbar ટૂલબાર બતાવો Show Transparency Grid પારદર્શિતા ગ્રિડ બતાવો @@ -4091,6 +4127,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 સિમ્બોલ શિફ્ટર ટૂલ @@ -4613,6 +4660,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} @@ -4963,6 +5013,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 ગુમ @@ -5431,6 +5484,39 @@ swatch [Registration] [રજિસ્ટ્રેશન] Standard Single-line Composer સ્ટાન્ડર્ડ સિંગલ-લાઇન કમ્પોઝર Standard Every-line Composer સ્ટાન્ડર્ડ એવરી-લાઇન કમ્પોઝર @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer આમાંથી એક હોવું જોઈએ: "singleLine", "everyLine", "standardSingleLine" અથવા "standardEveryLine" +# 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 2837a15b67..c9590cb688 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 पूर्ववत समूह शुरू करें @@ -1171,6 +1172,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 +1262,9 @@ antiAlias Sharp शार्प Box Channel बॉक्स चैनल Color box कलर बॉक्स Color Wheel Options कलर व्हील ऑप्शन्स + Show Harmony सद्भाव दिखाएँ + Harmony Rule सद्भाव नियम + Harmony color सद्भाव रंग Color Type: रंग का प्रकार: Color wheel कलर व्हील Color: रंग: @@ -1887,10 +1910,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 +2206,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 आईड्रॉपर ऑप्शन्स @@ -2907,6 +2954,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 नॉकआउट समूह @@ -3857,6 +3913,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 अनुपलब्ध @@ -4811,6 +4870,7 @@ antiAlias Sharp शार्प Save Preset प्रीसेट सेव करें Save Document Preset डॉक्यूमेंट प्रीसेट सेव करें Save Preset… प्रीसेट सेव करें… + Save Summary… सारांश सेव करें… Save Print Preset सेव करें प्रिंट प्रीसेट Save Recovery Data रिकवरी डेटा सेव करें Save Save for Web Preset सेव फॉर वेब प्रीसेट @@ -5256,6 +5316,7 @@ antiAlias Sharp शार्प Show Tile Edge टाइल एज Show Tints/Shades शो टिंट्स / शेड्स Show Tool Group Labels टूल ग्रुप लेबल दिखाएं + Show Tool Cards टूल कार्ड दिखाएँ Show Tool Tips टूल युक्तियाँ दिखाएँ Show Toolbar शो टूलबार Show Transparency Grid पारदर्शिता ग्रिड दिखाएँ @@ -5616,6 +5677,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 सिंबल शिफ़्टर टूल @@ -9184,6 +9256,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 खोज शुरू नहीं हो सका: एक पल में फिर से प्रयास करें @@ -9526,6 +9599,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 होना चाहिए @@ -10012,6 +10128,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 होल्ड शॉर्टकट @@ -10058,3 +10207,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 fbc2e30bd1..5f33abcbe2 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 @@ -723,6 +724,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 +807,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 +1341,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 +1607,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ő @@ -2431,6 +2478,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 @@ -3202,6 +3258,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 @@ -3998,6 +4057,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 @@ -4374,6 +4434,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 @@ -4663,6 +4724,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ő @@ -6320,6 +6392,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} @@ -6428,6 +6501,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 @@ -10394,6 +10510,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 @@ -10440,3 +10589,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 ab48475d3d..e4247ba312 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -516,6 +516,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… @@ -746,6 +757,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 +991,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 +1091,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… @@ -1970,6 +2012,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 +2420,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 +2570,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. @@ -3128,6 +3186,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 +3257,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 +3388,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 +3961,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 @@ -5095,6 +5169,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 @@ -7699,6 +7774,39 @@ 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" +# 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 @@ -7715,3 +7823,7 @@ breakText Glyphs Glif Pulse Stroke Goresan Berdenyut Round Flow Aliran Bulat Chisel Flow Aliran Serong + +# #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 a3b493cd1d..c037ab2c4a 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -607,6 +607,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 +1043,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 +1300,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 +1438,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 @@ -2264,6 +2302,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 +2429,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 +2460,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 @@ -3436,6 +3487,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 @@ -3771,6 +3823,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 @@ -5497,6 +5550,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 @@ -5863,6 +5917,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 @@ -5890,6 +5987,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à… @@ -10052,6 +10168,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 @@ -10098,3 +10247,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 5de0cae50c..dbb32f2827 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… マテリアル… @@ -835,6 +853,9 @@ digits Malayalam マラヤーラム数字 Box Channel ボックスのチャンネル Color box カラーボックス Color Wheel Options カラーホイールオプション + Show Harmony ハーモニーを表示 + Harmony Rule ハーモニールール + Harmony color ハーモニーカラー CSS Properties CSS プロパティ Document Info ドキュメント情報 Flattener Preview 分割・統合プレビュー @@ -1529,10 +1550,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 +2617,7 @@ antiAlias Sharp シャープ Pressure 筆圧 Tilt 傾き Bearing 方位 + Stylus Wheel スタイラスホイール Shape: 形状: Bristle Length: 毛の長さ: Bristle Density: 毛の密度: @@ -2611,6 +2648,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 見つかりません @@ -3381,6 +3421,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 用に保存プリセットを保存 @@ -3566,6 +3607,7 @@ mark-style Japanese 日本式 Show Thumbnails サムネールを表示 Show Tile Edge タイルの境界線を表示 Show Tints/Shades ティント/シェードを表示 + Show Tool Cards ツールカードを表示 Show Tool Tips ツールヒントを表示 Show Vivid/Muted ビビッド/ソフトを表示 Show Warm/Cool 暖色/寒色を表示 @@ -4142,6 +4184,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 読み込めるすべてのファイル @@ -5457,6 +5510,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}) @@ -5911,6 +5965,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 ファイルが途中で切れています @@ -5938,6 +6035,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… 粒状… @@ -10116,6 +10232,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 長押しショートカット @@ -10162,3 +10311,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 81fc06870d..8d4ca59a19 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… მასალები… @@ -2916,6 +2925,9 @@ Box Channel კვადრატის არხი Color box ფერის კვადრატი Color Wheel Options ფერთა წრის პარამეტრები + Show Harmony ჰარმონიის ჩვენება + Harmony Rule ჰარმონიის წესი + Harmony color ჰარმონიის ფერი CSS Properties CSS თვისებები Document Info დოკუმენტის ინფორმაცია Flattener Preview გაბრტყელების წინასწარი ნახვა @@ -3147,6 +3159,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 +3259,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… ეფექტი… @@ -4143,6 +4183,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 +4739,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. ჩაშენებული პრესეტები არ იცვლება: „ახალი“ ქმნის რედაქტირებად ასლს. @@ -5220,6 +5270,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 +5337,7 @@ antiAlias Sharp მკვეთრი Width Point Edit სიგანის წერტილის რედაქტირება Art ნახატი Bearing აზიმუტი + Stylus Wheel სტილუსის ბორბალი Bristle ჯაგრისი Calligraphic კალიგრაფიული Dots წერტილები @@ -5415,6 +5477,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 +6053,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 მიბმის დაშვება @@ -7201,6 +7267,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 ნახატს საზღვრები არ აქვს @@ -7507,6 +7574,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 ფაილი შეკვეცილია @@ -10777,6 +10871,39 @@ 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" +# 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 ხანგრძლივი დაჭერის მალსახმობები @@ -10793,3 +10920,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 4a6963bbd2..db60a6f5ab 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… 재질… @@ -828,6 +846,9 @@ digits Malayalam 말라얄람어 Box Channel 상자 채널 Color box 색상 상자 Color Wheel Options 색상환 옵션 + Show Harmony 하모니 표시 + Harmony Rule 하모니 규칙 + Harmony color 하모니 색상 CSS Properties CSS 속성 Document Info 문서 정보 Flattener Preview 병합 미리 보기 @@ -1519,10 +1540,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 +2607,7 @@ antiAlias Sharp 날카롭게 Pressure 필압 Tilt 기울기 Bearing 방위 + Stylus Wheel 스타일러스 휠 Shape: 모양: Bristle Length: 강모 길이: Bristle Density: 강모 밀도: @@ -2601,6 +2638,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 없음 @@ -3370,6 +3410,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 웹용 저장 사전 설정 저장 @@ -3557,6 +3598,7 @@ mark-style Japanese 일본식 Show Thumbnails 축소판 표시 Show Tile Edge 타일 가장자리 표시 Show Tints/Shades 밝은/어두운 색조 표시 + Show Tool Cards 도구 카드 표시 Show Tool Tips 도구 설명 표시 Show Vivid/Muted 선명/탁한 색상 표시 Show Warm/Cool 따뜻한/차가운 색상 표시 @@ -4132,6 +4174,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 읽을 수 있는 모든 파일 @@ -5386,6 +5439,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}) @@ -5840,6 +5894,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 파일이 잘려 있습니다 @@ -5867,6 +5964,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… 그레인… @@ -10015,6 +10131,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 길게 누르기 단축키 @@ -10061,3 +10210,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 894c7096f6..6cef186bd2 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… @@ -1351,6 +1362,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 +1596,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 +1696,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… @@ -2617,6 +2659,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 +3067,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 +3224,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. @@ -3782,6 +3840,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 +3911,7 @@ antiAlias Sharp Scherp Width Point Edit Breedtepunt bewerken Art Illustratie Bearing Richting + Stylus Wheel Pennenwiel Bristle Borstel Calligraphic Kalligrafisch Dots Stippen @@ -3976,6 +4046,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 +4621,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 @@ -5769,6 +5843,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 @@ -6064,6 +6139,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 @@ -10443,6 +10561,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 @@ -10489,3 +10640,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 c69ed2cf28..e120a0c894 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… @@ -756,6 +765,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 +1013,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 +1114,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… @@ -2142,6 +2182,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 +2592,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 +2753,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ę. @@ -3293,6 +3349,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 +3453,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 +3599,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 +4181,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 @@ -5583,6 +5655,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 @@ -5923,6 +5996,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 @@ -10269,6 +10385,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 @@ -10315,3 +10464,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 6bae5e26f1..8f1c40f519 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -544,6 +544,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 +723,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 +1178,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 @@ -1938,6 +1965,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 @@ -2860,6 +2890,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 @@ -3143,6 +3174,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 @@ -3803,6 +3835,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… @@ -3912,6 +3963,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 @@ -3953,6 +4015,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 @@ -4725,6 +4796,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 @@ -5053,6 +5125,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 @@ -5512,6 +5627,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: @@ -10478,6 +10594,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 @@ -10524,3 +10673,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 74156da429..652c369b27 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -603,6 +603,9 @@ font-technology Variable Вариативные Box Channel Канал квадрата Color box Цветовой квадрат Color Wheel Options Параметры цветового круга + Show Harmony Показать гармонию + Harmony Rule Правило гармонии + Harmony color Цвет гармонии Color Type: Тип цвета: Color: Цвет: Colorize Тонировать @@ -1028,10 +1031,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 +1286,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 +1424,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 Плоский логотип @@ -2250,6 +2288,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 +2413,7 @@ file-filter Templates Шаблоны Pressure Нажим Tilt Наклон Bearing Азимут + Stylus Wheel Колесико пера Shape: Форма: Bristle Length: Длина щетинок: Bristle Density: Плотность щетинок: @@ -2396,6 +2444,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 отсутствует @@ -3418,6 +3469,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» @@ -3751,6 +3803,7 @@ digits Malayalam Малаялам Show Thumbnails Показать миниатюры Show Tile Edge Показать край плитки Show Tints/Shades Показать оттенки/тени + Show Tool Cards Показывать карточки инструментов Show Tool Tips Показывать подсказки Show Transparency Grid Показать сетку прозрачности Show Video Rulers Показать видео-линейки @@ -5494,6 +5547,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 у рисунка нет границ @@ -5862,6 +5916,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 обрезан @@ -5889,6 +5986,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… Зерно… @@ -10524,6 +10640,39 @@ 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" +# 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 Клавиши удержания @@ -10540,3 +10689,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 4d683cb1ea..b925732d7e 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -588,6 +588,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 +1016,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 +1257,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 +1373,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 @@ -2152,6 +2190,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 +2315,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 +2346,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 @@ -3306,6 +3357,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 @@ -3624,6 +3676,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 @@ -5349,6 +5402,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 @@ -5735,6 +5789,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 @@ -5762,6 +5859,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… @@ -10127,6 +10243,39 @@ 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 +# 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 @@ -10143,3 +10292,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..2f959de54f 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. @@ -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() { @@ -872,11 +984,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 +1012,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"] @@ -984,6 +1099,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] diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index d0e30b8fdc..28baed0414 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -586,6 +586,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 +1012,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 +1255,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 +1375,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 @@ -2039,6 +2077,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 +2194,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: @@ -3149,6 +3197,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 @@ -3506,6 +3555,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 @@ -5196,6 +5246,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 @@ -5563,6 +5614,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 @@ -5627,6 +5721,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… @@ -6861,6 +6974,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 @@ -10364,6 +10480,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ı @@ -10410,3 +10559,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 82ba9af243..64bc112954 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -601,6 +601,9 @@ font-technology Variable Варіативні Box Channel Канал квадрата Color box Колірний квадрат Color Wheel Options Параметри колірного кола + Show Harmony Показати гармонію + Harmony Rule Правило гармонії + Harmony color Колір гармонії Color Type: Тип кольору: Color: Колір: Colorize Тонувати @@ -1034,10 +1037,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 +1294,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 +1432,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 Плоский логотип @@ -2258,6 +2296,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 +2421,7 @@ file-filter Templates Шаблони Pressure Натиск Tilt Нахил Bearing Азимут + Stylus Wheel Коліщатко пера Shape: Форма: Bristle Length: Довжина щетинок: Bristle Density: Щільність щетинок: @@ -2404,6 +2452,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 відсутній @@ -3428,6 +3479,7 @@ digits Malayalam Малаялам Save Document Preset Зберегти набір документа Preset {number} Набір {number} Save Preset… Зберегти набір… + Save Summary… Зберегти зведення… Save Print Preset Зберегти набір друку Save Recovery Data Зберегти дані відновлення Save Save for Web Preset Зберегти набір «Зберегти для Інтернету» @@ -3763,6 +3815,7 @@ digits Malayalam Малаялам Show Thumbnails Показати мініатюри Show Tile Edge Показати край плитки Show Tints/Shades Показати відтінки/тіні + Show Tool Cards Показувати картки інструментів Show Tool Tips Показувати підказки Show Transparency Grid Показати сітку прозорості Show Video Rulers Показати відео-лінійки @@ -5481,6 +5534,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 малюнок не має меж @@ -5847,6 +5901,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 обрізаний @@ -5874,6 +5971,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… Зерно… @@ -10028,6 +10144,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 Клавіші утримання @@ -10074,3 +10223,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 04ebd9992d..8575042574 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 @@ -637,6 +638,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 +720,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 +1233,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 +1494,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 @@ -2285,6 +2332,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 @@ -3027,6 +3083,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 @@ -3768,6 +3827,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 @@ -4132,6 +4192,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 @@ -4398,6 +4459,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 @@ -5550,6 +5622,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 @@ -6108,6 +6181,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} @@ -6238,6 +6312,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 @@ -8286,6 +8403,39 @@ 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" +# 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ữ @@ -8304,3 +8454,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 d20ae8d9e8..1e048a2b70 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -552,6 +552,9 @@ antiAlias Sharp 锐利 Box Channel 方块色版 Color box 颜色方块 Color Wheel Options 色轮选项 + Show Harmony 显示协调 + Harmony Rule 协调规则 + Harmony color 协调颜色 Color Type: 颜色类型: Color: 颜色: Colorize 上色 @@ -972,10 +975,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 +1231,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 +1369,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: 平滑度: @@ -2239,6 +2277,7 @@ file-filter Templates 模板 Pressure 压力 Tilt 倾斜 Bearing 方位 + Stylus Wheel 光笔滚轮 Shape: 形状: Bristle Length: 鬃毛长度: Bristle Density: 鬃毛密度: @@ -2269,6 +2308,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 缺失 @@ -3283,6 +3325,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 预设 @@ -3583,6 +3626,7 @@ digits Malayalam 马拉雅拉姆数字 Show Thumbnails 显示缩略图 Show Tile Edge 显示拼贴边缘 Show Tints/Shades 显示浅色调/深色调 + Show Tool Cards 显示工具卡片 Show Tool Tips 显示工具提示 Show Transparency Grid 显示透明网格 Show Video Rulers 显示视频标尺 @@ -5135,6 +5179,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}) @@ -5574,6 +5619,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 文件不完整 @@ -5771,6 +5859,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 影片和视频 @@ -5984,6 +6091,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 只推出 @@ -10284,6 +10400,39 @@ 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} 像素):请降低分辨率 +# 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 按住快捷键 @@ -10300,3 +10449,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 d5fde762f9..549cf0edbc 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -569,6 +569,9 @@ font-technology Variable 可變 Box Channel 方塊色版 Color box 顏色方塊 Color Wheel Options 色輪選項 + Show Harmony 顯示色彩調和 + Harmony Rule 色彩調和規則 + Harmony color 調和色彩 Color Type: 顏色類型: Color: 顏色: Colorize 上色 @@ -1002,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 大地色系 @@ -1246,6 +1264,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 +1403,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: 平滑度: @@ -2589,6 +2627,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 +3068,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 +3528,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 +3672,7 @@ liquify-list-end {0}, {1} {0}和{1} Pressure 壓力 Tilt 傾斜 Bearing 方位 + Stylus Wheel 光筆滾輪 Shape: 形狀: Bristle Length: 鬃毛長度: Bristle Density: 鬃毛密度: @@ -3611,6 +3703,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 遺失 @@ -4640,6 +4735,7 @@ digits Malayalam 馬來亞拉姆數字 Save Document Preset 儲存文件預設集 Preset {number} 預設集 {number} Save Preset… 儲存預設集… + Save Summary… 儲存摘要… Save Print Preset 儲存列印預設集 Save Recovery Data 儲存救援資料 Save Save for Web Preset 儲存「儲存為網頁用」預設集 @@ -4973,6 +5069,7 @@ digits Malayalam 馬來亞拉姆數字 Show Thumbnails 顯示縮圖 Show Tile Edge 顯示拼貼邊緣 Show Tints/Shades 顯示淺色調/深色調 + Show Tool Cards 顯示工具卡片 Show Tool Tips 顯示工具提示 Show Transparency Grid 顯示透明度格點 Show Video Rulers 顯示視訊尺標 @@ -6017,6 +6114,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… 顆粒… @@ -10099,6 +10215,39 @@ 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} 個拼貼上:請縮小 +# 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 按住快速鍵 @@ -10115,3 +10264,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/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/lib.rs b/crates/ui-egui/src/lib.rs index 73337d1352..f23cb5927a 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 @@ -349,6 +353,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..3b6d526ca0 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -302,6 +302,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/run.rs b/crates/ui-egui/src/menus/run.rs index 909d03b3d2..6cb16f633d 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -983,6 +983,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 +1071,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..2cb1e46c34 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,6 +275,7 @@ 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())) } @@ -328,7 +329,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/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..66bd9a73d1 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1079,7 +1079,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", @@ -1496,7 +1496,7 @@ 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", @@ -1504,6 +1504,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{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", ), + ( + "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", "Export As…", @@ -1808,6 +1814,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/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/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 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/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/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/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_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/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 9d765e95eb..06a1fc64b9 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."), ( diff --git a/crates/ui-egui/src/prefs_dialog/tests.rs b/crates/ui-egui/src/prefs_dialog/tests.rs index 895d52d1c5..16c8a427e8 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..71e3cd53d8 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", ]; diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index d2bc85ba9a..e227a06f77 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -733,6 +733,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 +847,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)] @@ -1293,6 +1299,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,6 +1328,7 @@ 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, 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/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 80c82a6283..9e78a370bd 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -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..62c5b9e5c4 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 @@ -268,9 +268,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`, @@ -812,6 +813,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 +882,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/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..af411c8b81 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 @@ -723,9 +735,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 +778,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 @@ -948,7 +965,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/mcp.md b/docs/mcp.md index 16b212f64f..e694ddbcf7 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. | @@ -1408,6 +1411,14 @@ 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. @@ -1873,6 +1884,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 +2038,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 +2294,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 +3814,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 +4028,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 @@ -5062,6 +5149,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 @@ -6255,7 +6388,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 +6635,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 +6652,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 +6687,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 @@ -7582,6 +7716,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 @@ -9197,6 +9334,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"}}} @@ -9223,9 +9362,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 @@ -9755,6 +9899,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 @@ -10918,12 +11071,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, @@ -10936,8 +11127,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 @@ -10955,10 +11146,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 @@ -11017,9 +11211,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. @@ -12460,7 +12656,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). @@ -12514,7 +12716,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. @@ -13000,8 +13207,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 diff --git a/docs/roadmap.md b/docs/roadmap.md index 4e23db3070..3f6627b5ba 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,10 +174,10 @@ 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 | @@ -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 6311d05d02..6645d3f731 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) | | 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,7 +287,7 @@ 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 | @@ -298,7 +305,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | 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 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 | +| 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) | @@ -857,7 +864,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 +1051,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. @@ -1181,6 +1190,7 @@ 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`. @@ -1361,6 +1371,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. @@ -1706,7 +1717,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. @@ -1879,7 +1891,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Colorized images (#1466):** a fill color applied to a selected grayscale or 1-bit image (`paint.setFill`) colorizes it with black, white, a process color or a spot color, and refuses a process color when the image has an alpha channel ([Convert color modes](https://web.archive.org/web/20251220223850/https://helpx.adobe.com/illustrator/desktop/manage-colors/select-and-adjust-colors/convert-color-modes.html), "Colorize Grayscale or 1-bit images"); black and white are accepted there too. The canvas draws each pixel in the color as far as the pixel is dark, with white pixels transparent; PDF export writes the image in the color (a spot color as its ink, Registration in every ink) with the image as its soft mask; Separations Preview and printed separations show it on its color's plates; native files keep the color. EPS and SVG write the image's own pixels. - **Missing library files:** a persistent swatch or graphic style library panel whose file is gone at startup reopens and stays in the preferences, showing the file's path with Locate Library… (`ui.libraryPanel.locate`), which reads the file from where it is now into the same panel. - **Swatch library and Recolor Artwork parameters:** the `swatch.library.*` commands, `swatch.resetDefaults`, the graphic style library save, load and add, the `recolor.*` commands and `color.harmony`'s `limitTo` refuse parameters of the wrong form, such as `names: "Grays"`, `limitTo: 5` or `includeImages: "false"`. Errors name the parameter, except that a `limitTo` that is not a string, such as `5`, gets an unknown-library error. A `null` counts as left out except for `recolor.apply`'s `model`, which must be a string when given. - - **Color Wheel panel (part of #978):** Window › Color Wheel shows the Fill and Stroke proxy beside a hue ring around a square with saturation across and brightness up. It edits what the Color panel's sliders edit (the active proxy's color, the selected gradient stop or freeform point) through the same paint commands, and a drag is one undo step. Alt paints the other proxy, and Shift steps the ring by 45°. A pick goes from display sRGB into the working RGB space; an RGB, CMYK or Lab color keeps its model, and a Gray color or a tint of a global swatch becomes a process color in the document's color mode. A click gives the ring or the square the keyboard focus, and the arrow keys then step the color; both report their names and values to screen readers, and the Color Picker's color field takes the same keys. The panel menu's Box View puts a box in the wheel's place: a color field with a channel strip at its right for Hue, Saturation, Brightness, Red, Green or Blue (Box Channel), on the Color Picker's axes, kept with the preferences (`ui.colorWheel`); the strip and the Color Picker's channel slider take the arrow keys after a click. 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. @@ -1941,14 +1953,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 +1969,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). @@ -2168,6 +2182,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 +2223,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`). @@ -2220,6 +2236,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - 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`). - 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 +2355,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. @@ -3042,7 +3075,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..cf1232b26f 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 | @@ -620,6 +627,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. |