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/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/mem.rs b/crates/doc/src/mem.rs index 278ee7cf22..ff8129426e 100644 --- a/crates/doc/src/mem.rs +++ b/crates/doc/src/mem.rs @@ -354,7 +354,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 +426,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/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/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index c026a1086e..ae0a721b4e 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -165,7 +165,7 @@ pub fn specs() -> Vec { "Brush Options…", [], None, - "{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180° (counter-clockwise from level), roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure|tilt|bearing|rotation for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest; tilt from value − variation with the pen lying flat to value + variation with it upright; bearing and rotation add variation × the pen's bearing (which way it leans, counter-clockwise from leaning right) or its barrel's counter-clockwise rotation over 180°; the angle turns on past ±180°). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180° (counter-clockwise), modes: [fixed|random|pressure|tilt|bearing|rotation for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest; tilt: a with the pen lying flat to b upright; bearing and rotation: a at −180° to b at 180°), rotation_relative_to_path, 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 ), 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/fileio.rs b/crates/engine/src/cmd/fileio.rs index cd6ec30f0d..f9031f3204 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; 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/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/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/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..8e1da7dcf2 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1807,6 +1807,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/lib.rs b/crates/text/src/lib.rs index 6d99928b73..fe54654130 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}; 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/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/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 0aa32d4789..892b8c5848 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -62,6 +62,7 @@ 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; @@ -425,6 +426,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, 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/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/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/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 9f128efaf7..360aa02033 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -1003,6 +1003,15 @@ font-technology Variable Променливи 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 Земни тонове @@ -2244,6 +2253,7 @@ font-technology Variable Променливи Pressure Натиск Tilt Наклон Bearing Азимут + Stylus Wheel Колелце на писалката Shape: Форма: Bristle Length: Дължина на косъма: Bristle Density: Плътност на косъмчетата: @@ -2274,6 +2284,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 липсва diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 58c5e6d3ec..e19f1c087a 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -1122,6 +1122,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… @@ -3420,6 +3429,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 +3559,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 diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 4531f5d5c9..928a803de8 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ó @@ -1469,6 +1470,15 @@ antiAlias Sharp Nítid 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. @@ -3317,6 +3327,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 diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index a74e93499d..6a5d5457f3 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -1147,6 +1147,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… @@ -3507,6 +3516,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 +3662,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í diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 54c3ea243e..6848d8d8ba 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -3794,6 +3794,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… @@ -5971,6 +5980,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 +6115,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 diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index cbdef25b9a..8a8dab1c64 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1023,6 +1023,15 @@ font-technology Variable Variabel 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 @@ -2297,6 +2306,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 +2337,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 diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 5541c72c37..5d925f274e 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -985,6 +985,15 @@ font-technology Variable Μεταβλητές 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 Κείμενο Ανατολικής Ασίας @@ -1976,6 +1985,7 @@ font-technology Variable Μεταβλητές Pressure Πίεση Tilt Κλίση Bearing Αζιμούθιο + Stylus Wheel Τροχός γραφίδας Shape: Σχήμα: New Brush… Νέο πινέλο… New Brush Νέο πινέλο @@ -1991,6 +2001,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 λείπει diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index b2dc5e72c1..693f0951d9 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1034,6 +1034,15 @@ font-technology Variable Variables 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 @@ -2341,6 +2350,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 +2381,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 diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 5c3bb2768f..74d89d7f35 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -1121,6 +1121,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… @@ -3447,6 +3456,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 +3599,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 diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index cad0efa32a..64b4092932 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1037,6 +1037,15 @@ font-technology Variable Variables 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 @@ -2329,6 +2338,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 +2369,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 diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index d7bb081e02..0236ef7aa1 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -4963,6 +4963,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 ગુમ diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 43b4eb32eb..be2f6c02b3 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 पूर्ववत समूह शुरू करें @@ -1891,6 +1892,15 @@ antiAlias Sharp शार्प 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: प्रत्येक डिजाइन का प्रतिनिधित्व करता है: @@ -3857,6 +3867,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 अनुपलब्ध diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index f37adff561..6b72c8a2ee 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 @@ -1322,6 +1323,15 @@ font-technology Variable Változó 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 @@ -3202,6 +3212,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 diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index c381b9c2e8..9c93f445d6 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -1058,6 +1058,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… @@ -3188,6 +3197,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 +3328,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 diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index e715009919..0615025bb6 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1044,6 +1044,15 @@ font-technology Variable Variabili 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 @@ -2382,6 +2391,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 +2422,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 diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 263ca96cc2..3974bad3bf 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1533,6 +1533,15 @@ antiAlias Sharp シャープ 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 +2590,7 @@ antiAlias Sharp シャープ Pressure 筆圧 Tilt 傾き Bearing 方位 + Stylus Wheel スタイラスホイール Shape: 形状: Bristle Length: 毛の長さ: Bristle Density: 毛の密度: @@ -2611,6 +2621,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 見つかりません diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 254b2e2fc0..144eadde31 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -3228,6 +3228,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… ეფექტი… @@ -5276,6 +5285,7 @@ antiAlias Sharp მკვეთრი Width Point Edit სიგანის წერტილის რედაქტირება Art ნახატი Bearing აზიმუტი + Stylus Wheel სტილუსის ბორბალი Bristle ჯაგრისი Calligraphic კალიგრაფიული Dots წერტილები @@ -5415,6 +5425,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 აკლია diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 76437d3316..0b226e5f37 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1523,6 +1523,15 @@ antiAlias Sharp 날카롭게 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 +2580,7 @@ antiAlias Sharp 날카롭게 Pressure 필압 Tilt 기울기 Bearing 방위 + Stylus Wheel 스타일러스 휠 Shape: 모양: Bristle Length: 강모 길이: Bristle Density: 강모 밀도: @@ -2601,6 +2611,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 없음 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index cb4cb1e3b6..c9512b5753 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1663,6 +1663,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… @@ -3842,6 +3851,7 @@ antiAlias Sharp Scherp Width Point Edit Breedtepunt bewerken Art Illustratie Bearing Richting + Stylus Wheel Pennenwiel Bristle Borstel Calligraphic Kalligrafisch Dots Stippen @@ -3976,6 +3986,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 diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 0de8db2b50..d0edc17a49 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -1083,6 +1083,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… @@ -3386,6 +3395,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 +3541,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 diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 797f1c96bb..1cc72b9e01 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -724,6 +724,15 @@ antiAlias Sharp Nítido 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 @@ -1938,6 +1947,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 @@ -5512,6 +5524,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: diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 78586405e3..acb078902d 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1032,6 +1032,15 @@ font-technology Variable Вариативные 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 Земляные тона @@ -2366,6 +2375,7 @@ file-filter Templates Шаблоны Pressure Нажим Tilt Наклон Bearing Азимут + Stylus Wheel Колесико пера Shape: Форма: Bristle Length: Длина щетинок: Bristle Density: Плотность щетинок: @@ -2396,6 +2406,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 отсутствует diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 9f4c45ebac..e4b0da7736 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1017,6 +1017,15 @@ font-technology Variable Variabla 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 @@ -2268,6 +2277,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 +2308,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 diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 19e8f367c6..961dd08a83 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -872,11 +872,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 +900,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 +987,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 e13a24e924..5d03c4e667 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1013,6 +1013,15 @@ font-technology Variable Değişken 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ı @@ -2147,6 +2156,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: @@ -6861,6 +6871,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 diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index bde14afbc6..137a68d39f 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1038,6 +1038,15 @@ font-technology Variable Варіативні 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 Земляні тони @@ -2374,6 +2383,7 @@ file-filter Templates Шаблони Pressure Натиск Tilt Нахил Bearing Азимут + Stylus Wheel Коліщатко пера Shape: Форма: Bristle Length: Довжина щетинок: Bristle Density: Щільність щетинок: @@ -2404,6 +2414,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 відсутній diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 39526383ad..e0033ca6de 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 @@ -1214,6 +1215,15 @@ font-technology Variable Biến thiên 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 @@ -3027,6 +3037,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 diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 5810c2a3dd..4b7a6bd3bc 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -976,6 +976,15 @@ antiAlias Sharp 锐利 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 大地色 @@ -2239,6 +2248,7 @@ file-filter Templates 模板 Pressure 压力 Tilt 倾斜 Bearing 方位 + Stylus Wheel 光笔滚轮 Shape: 形状: Bristle Length: 鬃毛长度: Bristle Density: 鬃毛密度: @@ -2269,6 +2279,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 缺失 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 5f1eb49d00..8772ff7861 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1006,6 +1006,15 @@ font-technology Variable 可變 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 大地色系 @@ -3581,6 +3590,7 @@ liquify-list-end {0}, {1} {0}和{1} Pressure 壓力 Tilt 傾斜 Bearing 方位 + Stylus Wheel 光筆滾輪 Shape: 形狀: Bristle Length: 鬃毛長度: Bristle Density: 鬃毛密度: @@ -3611,6 +3621,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 遺失 diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 909d03b3d2..5e73712448 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -1070,6 +1070,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..c5d0bfeaa8 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -328,7 +328,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/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index fbfd12b24e..60d1f811f9 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1808,6 +1808,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/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 &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/state.rs b/crates/ui-egui/src/state.rs index 8a85aa297d..e227a06f77 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -847,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)] @@ -1325,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/docs/control-protocol.md b/docs/control-protocol.md index a6a7766aca..2016eaf79d 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -881,8 +881,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/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 9f26d9c937..b0c16703af 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,8 @@ # Gaps -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-19 · **Change:** #5804 native-picked raster editor merged with main; scores and estimates unchanged; previously: 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. @@ -16,6 +18,8 @@ Draft enhancement #5804: Preferences › File Handling can select a raster edito **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. @@ -44,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. | @@ -106,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) | @@ -345,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`. @@ -407,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 @@ -419,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 @@ -770,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 @@ -952,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 6c6612ebcb..8ed3b10ad6 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -713,8 +713,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. | @@ -2002,7 +2002,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 @@ -3953,6 +3953,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 @@ -6255,7 +6267,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 +6514,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 +6531,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 +6566,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 @@ -9206,9 +9219,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 @@ -9738,6 +9756,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 @@ -12983,8 +13010,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 4378f82805..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. @@ -151,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 @@ -170,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) | #5804 adds a private native-picked raster editor for Edit Original; `.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 | +| 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; 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 | @@ -258,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 fcb79a2b20..d5c5fa34d3 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,9 +30,7 @@ ## 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. +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. @@ -73,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. | @@ -268,7 +271,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Area | Weight | Done | Main gaps | One agent (h) | Kind | |---|---:|---:|---|---:|---| | Selection, transform & align tools | 6 | 85% | Direct Selection segment click/Delete corrected (#1278); deletion splits an ordinary contour into selected sibling objects with bounds-fitted gradients kept in place (#3380, deletion only; `crates/engine/tests/it/delete_path_pieces.rs`); open-path anchor Delete keeps gaps; Select › Start Global Edit finds the paths, compound paths and symbol instances of the selected object's shape (Appearance, Size and artboard options) and gives an edit of one to all of them in proportion, as one undo step (#3521), and on a group the groups like it, an edit inside one reaching the same object in the others (#4939), and a Shift-click on a highlighted match leaves it out; the Align panel menu's Align to Glyph Bounds › Point Text and Area Text measure type by its glyphs' ink for Align and Distribute (#4231); remaining: Free Transform/Scale/Reflect along a rotated box, Global Edit of rotated copies, transform nuances (no-op anchor Align history regression-tested, #1180 follow-up) | 4–6 | estimated; 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) | @@ -457,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) | @@ -1364,6 +1367,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. @@ -1944,14 +1948,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). @@ -1959,6 +1964,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). @@ -2223,6 +2229,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`). @@ -2341,6 +2348,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. @@ -3045,7 +3068,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/ui-parity.md b/docs/ui-parity.md index 36c6e28077..cf1232b26f 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -16,6 +16,8 @@ > **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. @@ -186,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 | @@ -624,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. |